#include <NLPAPI.h>
#include <assert.h>

// sum of squares
double fSq(int n,double *x,void *d){return(x[0]*x[0]+x[1]*x[1]+(x[2]-3)*(x[2]-3)+x[3]*x[3]);}

// a simple constraint (yes, it's linear...)
double cSq(int n,double *x,void *d){return(2.0-(x[0]+x[1]+x[2]+x[3]));}

int main()
{

  // repeat the optimization 4 times... to illustrate memory problem.
  for(int i=0;i<4;i++) {
    double x[4],x0[4];
    int v[4],rc;
    char probname[]="test";
    NLProblem P=NLCreateProblem(probname,4);
    
    for(int i=0;i<4;i++) {
      v[i]=i;
      x0[i]=5.0;
    }

    char objname[]="fobj";
    rc=NLPSetObjective(P,objname,4,v,fSq,0,0,0,0);
    assert(!rc);

    char constname[]="eqconst";
    // add a constraint -- WITHOUT THIS, IT WORKS FINE
    rc=NLPAddEqualityConstraint(P,constname,4,v,cSq,0,0, 0,0);
    assert(!rc);

    NLIpopt Ip=NLCreateIpopt();
    NLClearErrors();

    rc=IPMinimize(Ip,P,x0,(double*)NULL,(double*)NULL,x);

    printf("Solution from IPOPT is ( ");
    for(int i=0;i<4;i++)
      printf("%lf ",x[i]);
    printf(")\n");

    printf("There were %d errors in IPOPT\n",NLGetNErrors());

    NLClearErrors();
    NLFreeIpopt(Ip);
    NLFreeProblem(P);
 
  }
 return(0);
}
