Diff for /imach/src/imach.c between versions 1.1 and 1.3

version 1.1, 2000/12/28 18:49:56 version 1.3, 2001/05/02 17:21:42
Line 1 Line 1
          
 /*********************** Imach **************************************          /*********************** Imach **************************************        
   This program computes Healthy Life Expectancies from cross-longitudinal     This program computes Healthy Life Expectancies from cross-longitudinal
   data. Cross-longitudinal consist in a first survey ("cross") where     data. Cross-longitudinal consist in a first survey ("cross") where
   individuals from different ages are interviewed on their health status    individuals from different ages are interviewed on their health status
   or degree of  disability. At least a second wave of interviews     or degree of  disability. At least a second wave of interviews
   ("longitudinal") should  measure each new individual health status.     ("longitudinal") should  measure each new individual health status.
   Health expectancies are computed from the transistions observed between     Health expectancies are computed from the transistions observed between
   waves and are computed for each degree of severity of disability (number    waves and are computed for each degree of severity of disability (number
   of life states). More degrees you consider, more time is necessary to    of life states). More degrees you consider, more time is necessary to
   reach the Maximum Likekilhood of the parameters involved in the model.    reach the Maximum Likelihood of the parameters involved in the model.
   The simplest model is the multinomial logistic model where pij is    The simplest model is the multinomial logistic model where pij is
   the probabibility to be observed in state j at the second wave conditional    the probabibility to be observed in state j at the second wave conditional
   to be observed in state i at the first wave. Therefore the model is:    to be observed in state i at the first wave. Therefore the model is:
   log(pij/pii)= aij + bij*age+ cij*sex + etc , where 'age' is age and 'sex'     log(pij/pii)= aij + bij*age+ cij*sex + etc , where 'age' is age and 'sex'
   is a covariate. If you want to have a more complex model than "constant and    is a covariate. If you want to have a more complex model than "constant and
   age", you should modify the program where the markup     age", you should modify the program where the markup
     *Covariates have to be included here again* invites you to do it.      *Covariates have to be included here again* invites you to do it.
   More covariates you add, less is the speed of the convergence.    More covariates you add, less is the speed of the convergence.
   
   The advantage that this computer programme claims, comes from that if the     The advantage that this computer programme claims, comes from that if the
   delay between waves is not identical for each individual, or if some     delay between waves is not identical for each individual, or if some
   individual missed an interview, the information is not rounded or lost, but    individual missed an interview, the information is not rounded or lost, but
   taken into account using an interpolation or extrapolation.    taken into account using an interpolation or extrapolation.
   hPijx is the probability to be    hPijx is the probability to be
   observed in state i at age x+h conditional to the observed state i at age     observed in state i at age x+h conditional to the observed state i at age
   x. The delay 'h' can be split into an exact number (nh*stepm) of     x. The delay 'h' can be split into an exact number (nh*stepm) of
   unobserved intermediate  states. This elementary transition (by month or     unobserved intermediate  states. This elementary transition (by month or
   quarter trimester, semester or year) is model as a multinomial logistic.     quarter trimester, semester or year) is model as a multinomial logistic.
   The hPx matrix is simply the matrix product of nh*stepm elementary matrices    The hPx matrix is simply the matrix product of nh*stepm elementary matrices
   and the contribution of each individual to the likelihood is simply hPijx.    and the contribution of each individual to the likelihood is simply hPijx.
   
   Also this programme outputs the covariance matrix of the parameters but also    Also this programme outputs the covariance matrix of the parameters but also
   of the life expectancies. It also computes the prevalence limits.     of the life expectancies. It also computes the prevalence limits.
      
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
            Institut national d'études démographiques, Paris.             Institut national d'études démographiques, Paris.
   This software have been partly granted by Euro-REVES, a concerted action    This software have been partly granted by Euro-REVES, a concerted action
   from the European Union.    from the European Union.
   It is copyrighted identically to a GNU software product, ie programme and    It is copyrighted identically to a GNU software product, ie programme and
   software can be distributed freely for non commercial use. Latest version    software can be distributed freely for non commercial use. Latest version
   can be accessed at http://euroreves.ined.fr/imach .    can be accessed at http://euroreves.ined.fr/imach .
   **********************************************************************/    **********************************************************************/
     
 #include <math.h>  #include <math.h>
 #include <stdio.h>  #include <stdio.h>
 #include <stdlib.h>  #include <stdlib.h>
 #include <unistd.h>  #include <unistd.h>
   
 #define MAXLINE 256  #define MAXLINE 256
 #define FILENAMELENGTH 80  #define FILENAMELENGTH 80
 /*#define DEBUG*/  /*#define DEBUG*/
 /*#define win*/  #define windows
   
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncov */  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
   
 #define NINTERVMAX 8  #define NINTERVMAX 8
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 #define NCOVMAX 8 /* Maximum number of covariates */  #define NCOVMAX 8 /* Maximum number of covariates */
 #define MAXN 20000  #define MAXN 20000
 #define YEARM 12. /* Number of months per year */  #define YEARM 12. /* Number of months per year */
 #define AGESUP 130  #define AGESUP 130
 #define AGEBASE 40  #define AGEBASE 40
   
   
 int nvar;  int nvar;
   static int cptcov;
 int npar=NPARMAX;  int cptcovn;
 int nlstate=2; /* Number of live states */  int npar=NPARMAX;
 int ndeath=1; /* Number of dead states */  int nlstate=2; /* Number of live states */
 int ncov;     /* Total number of covariables including constant a12*1 +b12*x ncov=2 */  int ndeath=1; /* Number of dead states */
   int ncovmodel, ncov;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 int *wav; /* Number of waves for this individuual 0 is possible */  
 int maxwav; /* Maxim number of waves */  int *wav; /* Number of waves for this individuual 0 is possible */
 int mle, weightopt;  int maxwav; /* Maxim number of waves */
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */  int mle, weightopt;
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 double **oldm, **newm, **savm; /* Working pointers to matrices */  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */  double **oldm, **newm, **savm; /* Working pointers to matrices */
 FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest;  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 FILE *ficgp, *fichtm;  FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest;
   FILE *ficgp, *fichtm;
 #define NR_END 1  FILE *ficreseij;
 #define FREE_ARG char*    char filerese[FILENAMELENGTH];
 #define FTOL 1.0e-10   FILE  *ficresvij;
     char fileresv[FILENAMELENGTH];
 #define NRANSI    FILE  *ficresvpl;
 #define ITMAX 200     char fileresvpl[FILENAMELENGTH];
   
 #define TOL 2.0e-4   
   
 #define CGOLD 0.3819660   
 #define ZEPS 1.0e-10   #define NR_END 1
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   #define FREE_ARG char*
   #define FTOL 1.0e-10
 #define GOLD 1.618034   
 #define GLIMIT 100.0   #define NRANSI
 #define TINY 1.0e-20   #define ITMAX 200
   
 static double maxarg1,maxarg2;  #define TOL 2.0e-4
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  #define CGOLD 0.3819660
    #define ZEPS 1.0e-10
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
 #define rint(a) floor(a+0.5)  
   #define GOLD 1.618034
 static double sqrarg;  #define GLIMIT 100.0
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  #define TINY 1.0e-20
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   
   static double maxarg1,maxarg2;
 int imx;   #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 int stepm;  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 /* Stepm, step in month: minimum step interpolation*/   
   #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 int m,nb;  #define rint(a) floor(a+0.5)
 int *num, firstpass=0, lastpass=2,*cod;  
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  static double sqrarg;
 double **pmmij;  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
   #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
 double *weight;  
 int **s; /* Status */  int imx;
 double *agedc, **covar, idx;  int stepm;
   /* Stepm, step in month: minimum step interpolation*/
   
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  int m,nb;
 double ftolhess; /* Tolerance for computing hessian */  int *num, firstpass=0, lastpass=4,*cod, *ncodemax;
   double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
   double **pmmij;
 /******************************************/  
   double *weight;
 void replace(char *s, char*t)  int **s; /* Status */
 {  double *agedc, **covar, idx;
   int i;  int **nbcode, *Tcode, *Tvar, **codtab;
   int lg=20;  
   i=0;  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
   lg=strlen(t);  double ftolhess; /* Tolerance for computing hessian */
   for(i=0; i<= lg; i++) {  
     (s[i] = t[i]);  
     if (t[i]== '\\') s[i]='/';  /******************************************/
   }  
 }  void replace(char *s, char*t)
 void cut(char *u,char *v, char*t)  {
 {    int i;
   int i,lg,j,p;    int lg=20;
   i=0;    i=0;
   for(j=0; j<=strlen(t); j++) {    lg=strlen(t);
     if(t[j]=='\\') p=j;    for(i=0; i<= lg; i++) {
   }      (s[i] = t[i]);
       if (t[i]== '\\') s[i]='/';
   lg=strlen(t);    }
   for(j=0; j<p; j++) {  }
     (u[j] = t[j]);  
     u[p]='\0';  int nbocc(char *s, char occ)
   }  {
     int i,j=0;
   for(j=0; j<= lg; j++) {    int lg=20;
     if (j>=(p+1))(v[j-p-1] = t[j]);    i=0;
   }    lg=strlen(s);
 }    for(i=0; i<= lg; i++) {
     if  (s[i] == occ ) j++;
 /********************** nrerror ********************/    }
     return j;
 void nrerror(char error_text[])  }
 {  
   fprintf(stderr,"ERREUR ...\n");  void cutv(char *u,char *v, char*t, char occ)
   fprintf(stderr,"%s\n",error_text);  {
   exit(1);    int i,lg,j,p;
 }    i=0;
 /*********************** vector *******************/    for(j=0; j<=strlen(t)-1; j++) {
 double *vector(int nl, int nh)      if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
 {    }
   double *v;  
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));    lg=strlen(t);
   if (!v) nrerror("allocation failure in vector");    for(j=0; j<p; j++) {
   return v-nl+NR_END;      (u[j] = t[j]);
 }      u[p]='\0';
     }
 /************************ free vector ******************/  
 void free_vector(double*v, int nl, int nh)     for(j=0; j<= lg; j++) {
 {      if (j>=(p+1))(v[j-p-1] = t[j]);
   free((FREE_ARG)(v+nl-NR_END));    }
 }  }
   
 /************************ivector *******************************/  /********************** nrerror ********************/
 int *ivector(long nl,long nh)  
 {  void nrerror(char error_text[])
   int *v;  {
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));    fprintf(stderr,"ERREUR ...\n");
   if (!v) nrerror("allocation failure in ivector");    fprintf(stderr,"%s\n",error_text);
   return v-nl+NR_END;    exit(1);
 }  }
   /*********************** vector *******************/
 /******************free ivector **************************/  double *vector(int nl, int nh)
 void free_ivector(int *v, long nl, long nh)  {
 {    double *v;
   free((FREE_ARG)(v+nl-NR_END));    v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 }    if (!v) nrerror("allocation failure in vector");
     return v-nl+NR_END;
 /******************* imatrix *******************************/  }
 int **imatrix(long nrl, long nrh, long ncl, long nch)   
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */   /************************ free vector ******************/
 {   void free_vector(double*v, int nl, int nh)
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;   {
   int **m;     free((FREE_ARG)(v+nl-NR_END));
     }
   /* allocate pointers to rows */   
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));   /************************ivector *******************************/
   if (!m) nrerror("allocation failure 1 in matrix()");   int *ivector(long nl,long nh)
   m += NR_END;   {
   m -= nrl;     int *v;
       v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
       if (!v) nrerror("allocation failure in ivector");
   /* allocate rows and set pointers to them */     return v-nl+NR_END;
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));   }
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");   
   m[nrl] += NR_END;   /******************free ivector **************************/
   m[nrl] -= ncl;   void free_ivector(int *v, long nl, long nh)
     {
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;     free((FREE_ARG)(v+nl-NR_END));
     }
   /* return pointer to array of pointers to rows */   
   return m;   /******************* imatrix *******************************/
 }   int **imatrix(long nrl, long nrh, long ncl, long nch)
        /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
 /****************** free_imatrix *************************/  {
 void free_imatrix(m,nrl,nrh,ncl,nch)    long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
       int **m;    int **m;
       long nch,ncl,nrh,nrl;    
      /* free an int matrix allocated by imatrix() */     /* allocate pointers to rows */
 {     m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
   free((FREE_ARG) (m[nrl]+ncl-NR_END));     if (!m) nrerror("allocation failure 1 in matrix()");
   free((FREE_ARG) (m+nrl-NR_END));     m += NR_END;
 }     m -= nrl;
    
 /******************* matrix *******************************/   
 double **matrix(long nrl, long nrh, long ncl, long nch)    /* allocate rows and set pointers to them */
 {    m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   double **m;    m[nrl] += NR_END;
     m[nrl] -= ncl;
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));   
   if (!m) nrerror("allocation failure 1 in matrix()");    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
   m += NR_END;   
   m -= nrl;    /* return pointer to array of pointers to rows */
     return m;
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  }
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  
   m[nrl] += NR_END;  /****************** free_imatrix *************************/
   m[nrl] -= ncl;  void free_imatrix(m,nrl,nrh,ncl,nch)
         int **m;
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;        long nch,ncl,nrh,nrl;
   return m;       /* free an int matrix allocated by imatrix() */
 }  {
     free((FREE_ARG) (m[nrl]+ncl-NR_END));
 /*************************free matrix ************************/    free((FREE_ARG) (m+nrl-NR_END));
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)  }
 {  
   free((FREE_ARG)(m[nrl]+ncl-NR_END));  /******************* matrix *******************************/
   free((FREE_ARG)(m+nrl-NR_END));  double **matrix(long nrl, long nrh, long ncl, long nch)
 }  {
     long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 /******************* ma3x *******************************/    double **m;
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)  
 {    m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;    if (!m) nrerror("allocation failure 1 in matrix()");
   double ***m;    m += NR_END;
     m -= nrl;
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  
   if (!m) nrerror("allocation failure 1 in matrix()");    m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   m += NR_END;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   m -= nrl;    m[nrl] += NR_END;
     m[nrl] -= ncl;
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   m[nrl] += NR_END;    return m;
   m[nrl] -= ncl;  }
   
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;  /*************************free matrix ************************/
   void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));  {
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");    free((FREE_ARG)(m[nrl]+ncl-NR_END));
   m[nrl][ncl] += NR_END;    free((FREE_ARG)(m+nrl-NR_END));
   m[nrl][ncl] -= nll;  }
   for (j=ncl+1; j<=nch; j++)   
     m[nrl][j]=m[nrl][j-1]+nlay;  /******************* ma3x *******************************/
     double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
   for (i=nrl+1; i<=nrh; i++) {  {
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;    long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
     for (j=ncl+1; j<=nch; j++)     double ***m;
       m[i][j]=m[i][j-1]+nlay;  
   }    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   return m;    if (!m) nrerror("allocation failure 1 in matrix()");
 }    m += NR_END;
     m -= nrl;
 /*************************free ma3x ************************/  
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)    m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 {    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    m[nrl] += NR_END;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    m[nrl] -= ncl;
   free((FREE_ARG)(m+nrl-NR_END));  
 }    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   
 /***************** f1dim *************************/    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 extern int ncom;     if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 extern double *pcom,*xicom;    m[nrl][ncl] += NR_END;
 extern double (*nrfunc)(double []);     m[nrl][ncl] -= nll;
      for (j=ncl+1; j<=nch; j++)
 double f1dim(double x)       m[nrl][j]=m[nrl][j-1]+nlay;
 {    
   int j;     for (i=nrl+1; i<=nrh; i++) {
   double f;      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
   double *xt;       for (j=ncl+1; j<=nch; j++)
          m[i][j]=m[i][j-1]+nlay;
   xt=vector(1,ncom);     }
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];     return m;
   f=(*nrfunc)(xt);   }
   free_vector(xt,1,ncom);   
   return f;   /*************************free ma3x ************************/
 }   void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
   {
 /*****************brent *************************/    free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)     free((FREE_ARG)(m[nrl]+ncl-NR_END));
 {     free((FREE_ARG)(m+nrl-NR_END));
   int iter;   }
   double a,b,d,etemp;  
   double fu,fv,fw,fx;  /***************** f1dim *************************/
   double ftemp;  extern int ncom;
   double p,q,r,tol1,tol2,u,v,w,x,xm;   extern double *pcom,*xicom;
   double e=0.0;   extern double (*nrfunc)(double []);
     
   a=(ax < cx ? ax : cx);   double f1dim(double x)
   b=(ax > cx ? ax : cx);   {
   x=w=v=bx;     int j;
   fw=fv=fx=(*f)(x);     double f;
   for (iter=1;iter<=ITMAX;iter++) {     double *xt;
     xm=0.5*(a+b);    
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     xt=vector(1,ncom);
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/    for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
     printf(".");fflush(stdout);    f=(*nrfunc)(xt);
 #ifdef DEBUG    free_vector(xt,1,ncom);
     printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);    return f;
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */  }
 #endif  
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){   /*****************brent *************************/
       *xmin=x;   double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
       return fx;   {
     }     int iter;
     ftemp=fu;    double a,b,d,etemp;
     if (fabs(e) > tol1) {     double fu,fv,fw,fx;
       r=(x-w)*(fx-fv);     double ftemp;
       q=(x-v)*(fx-fw);     double p,q,r,tol1,tol2,u,v,w,x,xm;
       p=(x-v)*q-(x-w)*r;     double e=0.0;
       q=2.0*(q-r);    
       if (q > 0.0) p = -p;     a=(ax < cx ? ax : cx);
       q=fabs(q);     b=(ax > cx ? ax : cx);
       etemp=e;     x=w=v=bx;
       e=d;     fw=fv=fx=(*f)(x);
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))     for (iter=1;iter<=ITMAX;iter++) {
         d=CGOLD*(e=(x >= xm ? a-x : b-x));       xm=0.5*(a+b);
       else {       tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
         d=p/q;       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
         u=x+d;       printf(".");fflush(stdout);
         if (u-a < tol2 || b-u < tol2)   #ifdef DEBUG
           d=SIGN(tol1,xm-x);       printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
       }       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
     } else {   #endif
       d=CGOLD*(e=(x >= xm ? a-x : b-x));       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
     }         *xmin=x;
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));         return fx;
     fu=(*f)(u);       }
     if (fu <= fx) {       ftemp=fu;
       if (u >= x) a=x; else b=x;       if (fabs(e) > tol1) {
       SHFT(v,w,x,u)         r=(x-w)*(fx-fv);
         SHFT(fv,fw,fx,fu)         q=(x-v)*(fx-fw);
         } else {         p=(x-v)*q-(x-w)*r;
           if (u < x) a=u; else b=u;         q=2.0*(q-r);
           if (fu <= fw || w == x) {         if (q > 0.0) p = -p;
             v=w;         q=fabs(q);
             w=u;         etemp=e;
             fv=fw;         e=d;
             fw=fu;         if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
           } else if (fu <= fv || v == x || v == w) {           d=CGOLD*(e=(x >= xm ? a-x : b-x));
             v=u;         else {
             fv=fu;           d=p/q;
           }           u=x+d;
         }           if (u-a < tol2 || b-u < tol2)
   }             d=SIGN(tol1,xm-x);
   nrerror("Too many iterations in brent");         }
   *xmin=x;       } else {
   return fx;         d=CGOLD*(e=(x >= xm ? a-x : b-x));
 }       }
       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
 /****************** mnbrak ***********************/      fu=(*f)(u);
       if (fu <= fx) {
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,         if (u >= x) a=x; else b=x;
             double (*func)(double))         SHFT(v,w,x,u)
 {           SHFT(fv,fw,fx,fu)
   double ulim,u,r,q, dum;          } else {
   double fu;             if (u < x) a=u; else b=u;
              if (fu <= fw || w == x) {
   *fa=(*func)(*ax);               v=w;
   *fb=(*func)(*bx);               w=u;
   if (*fb > *fa) {               fv=fw;
     SHFT(dum,*ax,*bx,dum)               fw=fu;
       SHFT(dum,*fb,*fa,dum)             } else if (fu <= fv || v == x || v == w) {
       }               v=u;
   *cx=(*bx)+GOLD*(*bx-*ax);               fv=fu;
   *fc=(*func)(*cx);             }
   while (*fb > *fc) {           }
     r=(*bx-*ax)*(*fb-*fc);     }
     q=(*bx-*cx)*(*fb-*fa);     nrerror("Too many iterations in brent");
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/     *xmin=x;
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));     return fx;
     ulim=(*bx)+GLIMIT*(*cx-*bx);   }
     if ((*bx-u)*(u-*cx) > 0.0) {   
       fu=(*func)(u);   /****************** mnbrak ***********************/
     } else if ((*cx-u)*(u-ulim) > 0.0) {   
       fu=(*func)(u);   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
       if (fu < *fc) {               double (*func)(double))
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))   {
           SHFT(*fb,*fc,fu,(*func)(u))     double ulim,u,r,q, dum;
           }     double fu;
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {    
       u=ulim;     *fa=(*func)(*ax);
       fu=(*func)(u);     *fb=(*func)(*bx);
     } else {     if (*fb > *fa) {
       u=(*cx)+GOLD*(*cx-*bx);       SHFT(dum,*ax,*bx,dum)
       fu=(*func)(u);         SHFT(dum,*fb,*fa,dum)
     }         }
     SHFT(*ax,*bx,*cx,u)     *cx=(*bx)+GOLD*(*bx-*ax);
       SHFT(*fa,*fb,*fc,fu)     *fc=(*func)(*cx);
       }     while (*fb > *fc) {
 }       r=(*bx-*ax)*(*fb-*fc);
       q=(*bx-*cx)*(*fb-*fa);
 /*************** linmin ************************/      u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
 int ncom;       ulim=(*bx)+GLIMIT*(*cx-*bx);
 double *pcom,*xicom;      if ((*bx-u)*(u-*cx) > 0.0) {
 double (*nrfunc)(double []);         fu=(*func)(u);
        } else if ((*cx-u)*(u-ulim) > 0.0) {
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))         fu=(*func)(u);
 {         if (fu < *fc) {
   double brent(double ax, double bx, double cx,           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
                double (*f)(double), double tol, double *xmin);             SHFT(*fb,*fc,fu,(*func)(u))
   double f1dim(double x);             }
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,       } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
               double *fc, double (*func)(double));         u=ulim;
   int j;         fu=(*func)(u);
   double xx,xmin,bx,ax;       } else {
   double fx,fb,fa;        u=(*cx)+GOLD*(*cx-*bx);
          fu=(*func)(u);
   ncom=n;       }
   pcom=vector(1,n);       SHFT(*ax,*bx,*cx,u)
   xicom=vector(1,n);         SHFT(*fa,*fb,*fc,fu)
   nrfunc=func;         }
   for (j=1;j<=n;j++) {   }
     pcom[j]=p[j];   
     xicom[j]=xi[j];   /*************** linmin ************************/
   }   
   ax=0.0;   int ncom;
   xx=1.0;   double *pcom,*xicom;
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);   double (*nrfunc)(double []);
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);    
 #ifdef DEBUG  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  {
 #endif    double brent(double ax, double bx, double cx,
   for (j=1;j<=n;j++) {                  double (*f)(double), double tol, double *xmin);
     xi[j] *= xmin;     double f1dim(double x);
     p[j] += xi[j];     void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
   }                 double *fc, double (*func)(double));
   free_vector(xicom,1,n);     int j;
   free_vector(pcom,1,n);     double xx,xmin,bx,ax;
 }     double fx,fb,fa;
    
 /*************** powell ************************/    ncom=n;
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,     pcom=vector(1,n);
             double (*func)(double []))     xicom=vector(1,n);
     nrfunc=func;
 {     for (j=1;j<=n;j++) {
       pcom[j]=p[j];
       xicom[j]=xi[j];
   void linmin(double p[], double xi[], int n, double *fret,     }
               double (*func)(double []));     ax=0.0;
   int i,ibig,j;     xx=1.0;
   double del,t,*pt,*ptt,*xit;    mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
   double fp,fptt;    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
   double *xits;  #ifdef DEBUG
   pt=vector(1,n);     printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   ptt=vector(1,n);   #endif
   xit=vector(1,n);     for (j=1;j<=n;j++) {
   xits=vector(1,n);       xi[j] *= xmin;
   *fret=(*func)(p);       p[j] += xi[j];
   for (j=1;j<=n;j++) pt[j]=p[j];     }
   for (*iter=1;;++(*iter)) {     free_vector(xicom,1,n);
     fp=(*fret);     free_vector(pcom,1,n);
     ibig=0;   }
     del=0.0;   
     printf("\nPowell iter=%d -2*LL=%.12f",*iter,*fret);  /*************** powell ************************/
     for (i=1;i<=n;i++)   void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
       printf(" %d %.12f",i, p[i]);              double (*func)(double []))
     printf("\n");  {
     for (i=1;i<=n;i++) {     void linmin(double p[], double xi[], int n, double *fret,
       for (j=1;j<=n;j++) xit[j]=xi[j][i];                 double (*func)(double []));
       fptt=(*fret);     int i,ibig,j;
 #ifdef DEBUG    double del,t,*pt,*ptt,*xit;
       printf("fret=%lf \n",*fret);    double fp,fptt;
 #endif    double *xits;
       printf("%d",i);fflush(stdout);    pt=vector(1,n);
       linmin(p,xit,n,fret,func);     ptt=vector(1,n);
       if (fabs(fptt-(*fret)) > del) {     xit=vector(1,n);
         del=fabs(fptt-(*fret));     xits=vector(1,n);
         ibig=i;     *fret=(*func)(p);
       }     for (j=1;j<=n;j++) pt[j]=p[j];
 #ifdef DEBUG    for (*iter=1;;++(*iter)) {
       printf("%d %.12e",i,(*fret));      fp=(*fret);
       for (j=1;j<=n;j++) {      ibig=0;
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);      del=0.0;
         printf(" x(%d)=%.12e",j,xit[j]);      printf("\nPowell iter=%d -2*LL=%.12f",*iter,*fret);
       }      for (i=1;i<=n;i++)
       for(j=1;j<=n;j++)         printf(" %d %.12f",i, p[i]);
         printf(" p=%.12e",p[j]);      printf("\n");
       printf("\n");      for (i=1;i<=n;i++) {
 #endif        for (j=1;j<=n;j++) xit[j]=xi[j][i];
     }         fptt=(*fret);
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {  #ifdef DEBUG
 #ifdef DEBUG        printf("fret=%lf \n",*fret);
       int k[2],l;  #endif
       k[0]=1;        printf("%d",i);fflush(stdout);
       k[1]=-1;        linmin(p,xit,n,fret,func);
       printf("Max: %.12e",(*func)(p));        if (fabs(fptt-(*fret)) > del) {
       for (j=1;j<=n;j++)           del=fabs(fptt-(*fret));
         printf(" %.12e",p[j]);          ibig=i;
       printf("\n");        }
       for(l=0;l<=1;l++) {  #ifdef DEBUG
         for (j=1;j<=n;j++) {        printf("%d %.12e",i,(*fret));
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];        for (j=1;j<=n;j++) {
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
         }          printf(" x(%d)=%.12e",j,xit[j]);
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        }
       }        for(j=1;j<=n;j++)
 #endif          printf(" p=%.12e",p[j]);
         printf("\n");
   #endif
       free_vector(xit,1,n);       }
       free_vector(xits,1,n);       if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
       free_vector(ptt,1,n);   #ifdef DEBUG
       free_vector(pt,1,n);         int k[2],l;
       return;         k[0]=1;
     }         k[1]=-1;
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");         printf("Max: %.12e",(*func)(p));
     for (j=1;j<=n;j++) {         for (j=1;j<=n;j++)
       ptt[j]=2.0*p[j]-pt[j];           printf(" %.12e",p[j]);
       xit[j]=p[j]-pt[j];         printf("\n");
       pt[j]=p[j];         for(l=0;l<=1;l++) {
     }           for (j=1;j<=n;j++) {
     fptt=(*func)(ptt);             ptt[j]=p[j]+(p[j]-pt[j])*k[l];
     if (fptt < fp) {             printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);           }
       if (t < 0.0) {           printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
         linmin(p,xit,n,fret,func);         }
         for (j=1;j<=n;j++) {   #endif
           xi[j][ibig]=xi[j][n];   
           xi[j][n]=xit[j];   
         }        free_vector(xit,1,n);
 #ifdef DEBUG        free_vector(xits,1,n);
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        free_vector(ptt,1,n);
         for(j=1;j<=n;j++)        free_vector(pt,1,n);
           printf(" %.12e",xit[j]);        return;
         printf("\n");      }
 #endif      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
       }       for (j=1;j<=n;j++) {
     }         ptt[j]=2.0*p[j]-pt[j];
   }         xit[j]=p[j]-pt[j];
 }         pt[j]=p[j];
       }
 /**** Prevalence limit ****************/      fptt=(*func)(ptt);
       if (fptt < fp) {
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl)        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
 {        if (t < 0.0) {
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit          linmin(p,xit,n,fret,func);
      matrix by transitions matrix until convergence is reached */          for (j=1;j<=n;j++) {
             xi[j][ibig]=xi[j][n];
   int i, ii,j,k;            xi[j][n]=xit[j];
   double min, max, maxmin, maxmax,sumnew=0.;          }
   double **matprod2();  #ifdef DEBUG
   double **out, cov[NCOVMAX], **pmij();          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
   double **newm;          for(j=1;j<=n;j++)
   double agefin, delaymax=50 ; /* Max number of years to converge */            printf(" %.12e",xit[j]);
           printf("\n");
   for (ii=1;ii<=nlstate+ndeath;ii++)  #endif
     for (j=1;j<=nlstate+ndeath;j++){        }
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);      }
     }    }
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */  }
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){  
     newm=savm;  /**** Prevalence limit ****************/
     /* Covariates have to be included here again */  
     cov[1]=1.;  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
     cov[2]=agefin;  {
     out=matprod2(newm, pmij(pmmij,cov,ncov,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 /*    printf("age=%f agefin=%f po=%f pn=%f\n",age,agefin,oldm[1][1],newm[1][1]);*/       matrix by transitions matrix until convergence is reached */
       
     savm=oldm;    int i, ii,j,k;
     oldm=newm;    double min, max, maxmin, maxmax,sumnew=0.;
     maxmax=0.;    double **matprod2();
     for(j=1;j<=nlstate;j++){    double **out, cov[NCOVMAX], **pmij();
       min=1.;    double **newm;
       max=0.;    double agefin, delaymax=50 ; /* Max number of years to converge */
       for(i=1; i<=nlstate; i++) {  
         sumnew=0;    for (ii=1;ii<=nlstate+ndeath;ii++)
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];      for (j=1;j<=nlstate+ndeath;j++){
         prlim[i][j]= newm[i][j]/(1-sumnew);        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         max=FMAX(max,prlim[i][j]);      }
         min=FMIN(min,prlim[i][j]);    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
       }    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
       maxmin=max-min;      newm=savm;
       maxmax=FMAX(maxmax,maxmin);      /* Covariates have to be included here again */
     }      cov[1]=1.;
     if(maxmax < ftolpl){      cov[2]=agefin;
       return prlim;      if (cptcovn>0){
     }        for (k=1; k<=cptcovn;k++) {cov[2+k]=nbcode[Tvar[k]][codtab[ij][k]];/*printf("Tcode[ij]=%d nbcode=%d\n",Tcode[ij],nbcode[k][Tcode[ij]]);*/}
   }      }
 }      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
   
 /*************** transition probabilities **********/       savm=oldm;
       oldm=newm;
 double **pmij(double **ps, double *cov, int ncov, double *x, int nlstate )      maxmax=0.;
 {      for(j=1;j<=nlstate;j++){
   double s1, s2;        min=1.;
   /*double t34;*/        max=0.;
   int i,j,j1, nc, ii, jj;        for(i=1; i<=nlstate; i++) {
           sumnew=0;
     for(i=1; i<= nlstate; i++){          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
     for(j=1; j<i;j++){          prlim[i][j]= newm[i][j]/(1-sumnew);
       for (nc=1, s2=0.;nc <=ncov; nc++){          max=FMAX(max,prlim[i][j]);
         /*s2 += param[i][j][nc]*cov[nc];*/          min=FMIN(min,prlim[i][j]);
         s2 += x[(i-1)*nlstate*ncov+(j-1)*ncov+nc+(i-1)*(ndeath-1)*ncov]*cov[nc];        }
         /*printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2);*/        maxmin=max-min;
       }        maxmax=FMAX(maxmax,maxmin);
       ps[i][j]=s2;      }
       /*printf("s1=%.17e, s2=%.17e\n",s1,s2);*/      if(maxmax < ftolpl){
     }        return prlim;
     for(j=i+1; j<=nlstate+ndeath;j++){      }
       for (nc=1, s2=0.;nc <=ncov; nc++){    }
         s2 += x[(i-1)*nlstate*ncov+(j-2)*ncov+nc+(i-1)*(ndeath-1)*ncov]*cov[nc];  }
         /*printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2);*/  
       }  /*************** transition probabilities **********/
       ps[i][j]=s2;  
     }  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
   }  {
   for(i=1; i<= nlstate; i++){    double s1, s2;
      s1=0;    /*double t34;*/
     for(j=1; j<i; j++)    int i,j,j1, nc, ii, jj;
       s1+=exp(ps[i][j]);  
     for(j=i+1; j<=nlstate+ndeath; j++)      for(i=1; i<= nlstate; i++){
       s1+=exp(ps[i][j]);      for(j=1; j<i;j++){
     ps[i][i]=1./(s1+1.);        for (nc=1, s2=0.;nc <=ncovmodel; nc++){
     for(j=1; j<i; j++)          /*s2 += param[i][j][nc]*cov[nc];*/
       ps[i][j]= exp(ps[i][j])*ps[i][i];          s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
     for(j=i+1; j<=nlstate+ndeath; j++)          /*printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2);*/
       ps[i][j]= exp(ps[i][j])*ps[i][i];        }
     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */        ps[i][j]=s2;
   } /* end i */        /*printf("s1=%.17e, s2=%.17e\n",s1,s2);*/
       }
   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){      for(j=i+1; j<=nlstate+ndeath;j++){
     for(jj=1; jj<= nlstate+ndeath; jj++){        for (nc=1, s2=0.;nc <=ncovmodel; nc++){
       ps[ii][jj]=0;          s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
       ps[ii][ii]=1;          /*printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2);*/
     }        }
   }        ps[i][j]=s2;
       }
   /*   for(ii=1; ii<= nlstate+ndeath; ii++){    }
     for(jj=1; jj<= nlstate+ndeath; jj++){    for(i=1; i<= nlstate; i++){
      printf("%lf ",ps[ii][jj]);       s1=0;
    }      for(j=1; j<i; j++)
     printf("\n ");        s1+=exp(ps[i][j]);
     }      for(j=i+1; j<=nlstate+ndeath; j++)
     printf("\n ");printf("%lf ",cov[2]);*/        s1+=exp(ps[i][j]);
 /*      ps[i][i]=1./(s1+1.);
   for(i=1; i<= npar; i++) printf("%f ",x[i]);      for(j=1; j<i; j++)
   goto end;*/        ps[i][j]= exp(ps[i][j])*ps[i][i];
     return ps;      for(j=i+1; j<=nlstate+ndeath; j++)
 }        ps[i][j]= exp(ps[i][j])*ps[i][i];
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 /**************** Product of 2 matrices ******************/    } /* end i */
   
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)    for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 {      for(jj=1; jj<= nlstate+ndeath; jj++){
   /* Computes the matric product of in(1,nrh-nrl+1)(1,nch-ncl+1) times        ps[ii][jj]=0;
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */        ps[ii][ii]=1;
   /* in, b, out are matrice of pointers which should have been initialized       }
      before: only the contents of out is modified. The function returns    }
      a pointer to pointers identical to out */  
   long i, j, k;    /*   for(ii=1; ii<= nlstate+ndeath; ii++){
   for(i=nrl; i<= nrh; i++)      for(jj=1; jj<= nlstate+ndeath; jj++){
     for(k=ncolol; k<=ncoloh; k++)       printf("%lf ",ps[ii][jj]);
       for(j=ncl,out[i][k]=0.; j<=nch; j++)     }
         out[i][k] +=in[i][j]*b[j][k];      printf("\n ");
       }
   return out;      printf("\n ");printf("%lf ",cov[2]);*/
 }  /*
     for(i=1; i<= npar; i++) printf("%f ",x[i]);
     goto end;*/
 /************* Higher Matrix Product ***************/      return ps;
   }
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm )  
 {  /**************** Product of 2 matrices ******************/
   /* Computes the transition matrix starting at age 'age' over 'nhstepm*hstepm*stepm' month   
      duration (i.e. until  double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
      age (in years)  age+nhstepm*stepm/12) by multiplying nhstepm*hstepm matrices.   {
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step     /* Computes the matric product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
      (typically every 2 years instead of every month which is too big).       b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
      Model is determined by parameters x and covariates have to be     /* in, b, out are matrice of pointers which should have been initialized
      included manually here.        before: only the contents of out is modified. The function returns
        a pointer to pointers identical to out */
      */    long i, j, k;
     for(i=nrl; i<= nrh; i++)
   int i, j, d, h;      for(k=ncolol; k<=ncoloh; k++)
   double **out, cov[NCOVMAX];        for(j=ncl,out[i][k]=0.; j<=nch; j++)
   double **newm;          out[i][k] +=in[i][j]*b[j][k];
   
   /* Hstepm could be zero and should return the unit matrix */    return out;
   for (i=1;i<=nlstate+ndeath;i++)  }
     for (j=1;j<=nlstate+ndeath;j++){  
       oldm[i][j]=(i==j ? 1.0 : 0.0);  
       po[i][j][0]=(i==j ? 1.0 : 0.0);  /************* Higher Matrix Product ***************/
     }  
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */  double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
   for(h=1; h <=nhstepm; h++){  {
     for(d=1; d <=hstepm; d++){    /* Computes the transition matrix starting at age 'age' over 'nhstepm*hstepm*stepm' month
       newm=savm;       duration (i.e. until
       /* Covariates have to be included here again */       age (in years)  age+nhstepm*stepm/12) by multiplying nhstepm*hstepm matrices.
       cov[1]=1.;       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;       (typically every 2 years instead of every month which is too big).
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/       Model is determined by parameters x and covariates have to be
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,        included manually here.
                    pmij(pmmij,cov,ncov,x,nlstate));  
       savm=oldm;       */
       oldm=newm;  
     }    int i, j, d, h, k;
     for(i=1; i<=nlstate+ndeath; i++)    double **out, cov[NCOVMAX];
       for(j=1;j<=nlstate+ndeath;j++) {    double **newm;
         po[i][j][h]=newm[i][j];  
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);    /* Hstepm could be zero and should return the unit matrix */
          */    for (i=1;i<=nlstate+ndeath;i++)
       }      for (j=1;j<=nlstate+ndeath;j++){
   } /* end h */        oldm[i][j]=(i==j ? 1.0 : 0.0);
   return po;        po[i][j][0]=(i==j ? 1.0 : 0.0);
 }      }
     /* Even if hstepm = 1, at least one multiplication by the unit matrix */
     for(h=1; h <=nhstepm; h++){
 /*************** log-likelihood *************/      for(d=1; d <=hstepm; d++){
 double func( double *x)        newm=savm;
 {        /* Covariates have to be included here again */
   int i, ii, j, k, mi, d;        cov[1]=1.;
   double l, ll[NLSTATEMAX], cov[NCOVMAX];        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
   double **out;        if (cptcovn>0){
   double sw; /* Sum of weights */        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][k]];
   double lli; /* Individual log likelihood */      }
   long ipmx;        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
   /*extern weight */        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
   /* We are differentiating ll according to initial status */        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/                     pmij(pmmij,cov,ncovmodel,x,nlstate));
   /*for(i=1;i<imx;i++)         savm=oldm;
 printf(" %d\n",s[4][i]);        oldm=newm;
   */      }
       for(i=1; i<=nlstate+ndeath; i++)
   for(k=1; k<=nlstate; k++) ll[k]=0.;        for(j=1;j<=nlstate+ndeath;j++) {
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){          po[i][j][h]=newm[i][j];
        for(mi=1; mi<= wav[i]-1; mi++){          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
       for (ii=1;ii<=nlstate+ndeath;ii++)           */
         for (j=1;j<=nlstate+ndeath;j++) oldm[ii][j]=(ii==j ? 1.0 : 0.0);        }
             for(d=0; d<dh[mi][i]; d++){    } /* end h */
         newm=savm;    return po;
           cov[1]=1.;  }
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;  
             out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,  
                        1,nlstate+ndeath,pmij(pmmij,cov,ncov,x,nlstate));  /*************** log-likelihood *************/
           savm=oldm;  double func( double *x)
           oldm=newm;  {
     int i, ii, j, k, mi, d;
     double l, ll[NLSTATEMAX], cov[NCOVMAX];
       } /* end mult */    double **out;
        double sw; /* Sum of weights */
       lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);    double lli; /* Individual log likelihood */
       /* printf(" %f ",out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/    long ipmx;
       ipmx +=1;    /*extern weight */
       sw += weight[i];    /* We are differentiating ll according to initial status */
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     } /* end of wave */    /*for(i=1;i<imx;i++)
   } /* end of individual */  printf(" %d\n",s[4][i]);
     */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];  
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */    for(k=1; k<=nlstate; k++) ll[k]=0.;
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   return -l;         for(mi=1; mi<= wav[i]-1; mi++){
 }        for (ii=1;ii<=nlstate+ndeath;ii++)
           for (j=1;j<=nlstate+ndeath;j++) oldm[ii][j]=(ii==j ? 1.0 : 0.0);
               for(d=0; d<dh[mi][i]; d++){
 /*********** Maximum Likelihood Estimation ***************/          newm=savm;
             cov[1]=1.;
 void mlikeli(FILE *ficres,double p[], int npar, int ncov, int nlstate, double ftol, double (*func)(double []))            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 {            if (cptcovn>0){
   int i,j, iter;              for (k=1; k<=cptcovn;k++) cov[2+k]=covar[1+k-1][i];
   double **xi,*delti;              }
   double fret;            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   xi=matrix(1,npar,1,npar);                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   for (i=1;i<=npar;i++)            savm=oldm;
     for (j=1;j<=npar;j++)            oldm=newm;
       xi[i][j]=(i==j ? 1.0 : 0.0);  
   printf("Powell\n");  
   powell(p,xi,npar,ftol,&iter,&fret,func);        } /* end mult */
      
    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f ",iter,func(p));        /* printf(" %f ",out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/
         ipmx +=1;
 }        sw += weight[i];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 /**** Computes Hessian and covariance matrix ***/      } /* end of wave */
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))    } /* end of individual */
 {  
   double  **a,**y,*x,pd;    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
   double **hess;    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   int i, j,jk;    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
   int *indx;    return -l;
   }
   double hessii(double p[], double delta, int theta, double delti[]);  
   double hessij(double p[], double delti[], int i, int j);  
   void lubksb(double **a, int npar, int *indx, double b[]) ;  /*********** Maximum Likelihood Estimation ***************/
   void ludcmp(double **a, int npar, int *indx, double *d) ;  
   void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   {
   hess=matrix(1,npar,1,npar);    int i,j, iter;
     double **xi,*delti;
   printf("\nCalculation of the hessian matrix. Wait...\n");    double fret;
   for (i=1;i<=npar;i++){    xi=matrix(1,npar,1,npar);
     printf("%d",i);fflush(stdout);    for (i=1;i<=npar;i++)
     hess[i][i]=hessii(p,ftolhess,i,delti);      for (j=1;j<=npar;j++)
     /*printf(" %f ",p[i]);*/        xi[i][j]=(i==j ? 1.0 : 0.0);
   }    printf("Powell\n");
     powell(p,xi,npar,ftol,&iter,&fret,func);
   for (i=1;i<=npar;i++) {  
     for (j=1;j<=npar;j++)  {     printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
       if (j>i) {     fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f ",iter,func(p));
         printf(".%d%d",i,j);fflush(stdout);  
         hess[i][j]=hessij(p,delti,i,j);  }
         hess[j][i]=hess[i][j];  
       }  /**** Computes Hessian and covariance matrix ***/
     }  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
   }  {
   printf("\n");    double  **a,**y,*x,pd;
     double **hess;
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");    int i, j,jk;
       int *indx;
   a=matrix(1,npar,1,npar);  
   y=matrix(1,npar,1,npar);    double hessii(double p[], double delta, int theta, double delti[]);
   x=vector(1,npar);    double hessij(double p[], double delti[], int i, int j);
   indx=ivector(1,npar);    void lubksb(double **a, int npar, int *indx, double b[]) ;
   for (i=1;i<=npar;i++)    void ludcmp(double **a, int npar, int *indx, double *d) ;
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];  
   ludcmp(a,npar,indx,&pd);  
     hess=matrix(1,npar,1,npar);
   for (j=1;j<=npar;j++) {  
     for (i=1;i<=npar;i++) x[i]=0;    printf("\nCalculation of the hessian matrix. Wait...\n");
     x[j]=1;    for (i=1;i<=npar;i++){
     lubksb(a,npar,indx,x);      printf("%d",i);fflush(stdout);
     for (i=1;i<=npar;i++){       hess[i][i]=hessii(p,ftolhess,i,delti);
       matcov[i][j]=x[i];      /*printf(" %f ",p[i]);*/
     }    }
   }  
     for (i=1;i<=npar;i++) {
   printf("\n#Hessian matrix#\n");      for (j=1;j<=npar;j++)  {
   for (i=1;i<=npar;i++) {         if (j>i) {
     for (j=1;j<=npar;j++) {           printf(".%d%d",i,j);fflush(stdout);
       printf("%.3e ",hess[i][j]);          hess[i][j]=hessij(p,delti,i,j);
     }          hess[j][i]=hess[i][j];
     printf("\n");        }
   }      }
     }
   /* Recompute Inverse */    printf("\n");
   for (i=1;i<=npar;i++)  
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
   ludcmp(a,npar,indx,&pd);   
     a=matrix(1,npar,1,npar);
   /*  printf("\n#Hessian matrix recomputed#\n");    y=matrix(1,npar,1,npar);
     x=vector(1,npar);
   for (j=1;j<=npar;j++) {    indx=ivector(1,npar);
     for (i=1;i<=npar;i++) x[i]=0;    for (i=1;i<=npar;i++)
     x[j]=1;      for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
     lubksb(a,npar,indx,x);    ludcmp(a,npar,indx,&pd);
     for (i=1;i<=npar;i++){   
       y[i][j]=x[i];    for (j=1;j<=npar;j++) {
       printf("%.3e ",y[i][j]);      for (i=1;i<=npar;i++) x[i]=0;
     }      x[j]=1;
     printf("\n");      lubksb(a,npar,indx,x);
   }      for (i=1;i<=npar;i++){
   */        matcov[i][j]=x[i];
       }
   free_matrix(a,1,npar,1,npar);    }
   free_matrix(y,1,npar,1,npar);  
   free_vector(x,1,npar);    printf("\n#Hessian matrix#\n");
   free_ivector(indx,1,npar);    for (i=1;i<=npar;i++) {
   free_matrix(hess,1,npar,1,npar);      for (j=1;j<=npar;j++) {
         printf("%.3e ",hess[i][j]);
       }
 }      printf("\n");
     }
 /*************** hessian matrix ****************/  
 double hessii( double x[], double delta, int theta, double delti[])    /* Recompute Inverse */
 {    for (i=1;i<=npar;i++)
   int i;      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
   int l=1, lmax=20;    ludcmp(a,npar,indx,&pd);
   double k1,k2;  
   double p2[NPARMAX+1];    /*  printf("\n#Hessian matrix recomputed#\n");
   double res;  
   double delt, delts, nkhi=10.,nkhif=1., khi=1.e-4;    for (j=1;j<=npar;j++) {
   double fx;      for (i=1;i<=npar;i++) x[i]=0;
   int k=0,kmax=10;      x[j]=1;
   double l1;      lubksb(a,npar,indx,x);
       for (i=1;i<=npar;i++){
   fx=func(x);        y[i][j]=x[i];
   for (i=1;i<=npar;i++) p2[i]=x[i];        printf("%.3e ",y[i][j]);
   for(l=0 ; l <=lmax; l++){      }
     l1=pow(10,l);      printf("\n");
     delts=delt;    }
     for(k=1 ; k <kmax; k=k+1){    */
       delt = delta*(l1*k);  
       p2[theta]=x[theta] +delt;    free_matrix(a,1,npar,1,npar);
       k1=func(p2)-fx;    free_matrix(y,1,npar,1,npar);
       p2[theta]=x[theta]-delt;    free_vector(x,1,npar);
       k2=func(p2)-fx;    free_ivector(indx,1,npar);
       /*res= (k1-2.0*fx+k2)/delt/delt; */    free_matrix(hess,1,npar,1,npar);
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */  
         
 #ifdef DEBUG  }
       printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);  
 #endif  /*************** hessian matrix ****************/
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */  double hessii( double x[], double delta, int theta, double delti[])
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){  {
         k=kmax;    int i;
       }    int l=1, lmax=20;
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */    double k1,k2;
         k=kmax; l=lmax*10.;    double p2[NPARMAX+1];
       }    double res;
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){     double delt, delts, nkhi=10.,nkhif=1., khi=1.e-4;
         delts=delt;    double fx;
       }    int k=0,kmax=10;
     }    double l1;
   }  
   delti[theta]=delts;    fx=func(x);
   return res;    for (i=1;i<=npar;i++) p2[i]=x[i];
       for(l=0 ; l <=lmax; l++){
 }      l1=pow(10,l);
       delts=delt;
 double hessij( double x[], double delti[], int thetai,int thetaj)      for(k=1 ; k <kmax; k=k+1){
 {        delt = delta*(l1*k);
   int i;        p2[theta]=x[theta] +delt;
   int l=1, l1, lmax=20;        k1=func(p2)-fx;
   double k1,k2,k3,k4,res,fx;        p2[theta]=x[theta]-delt;
   double p2[NPARMAX+1];        k2=func(p2)-fx;
   int k;        /*res= (k1-2.0*fx+k2)/delt/delt; */
         res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
   fx=func(x);       
   for (k=1; k<=2; k++) {  #ifdef DEBUG
     for (i=1;i<=npar;i++) p2[i]=x[i];        printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
     p2[thetai]=x[thetai]+delti[thetai]/k;  #endif
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;        /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
     k1=func(p2)-fx;        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
             k=kmax;
     p2[thetai]=x[thetai]+delti[thetai]/k;        }
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;        else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
     k2=func(p2)-fx;          k=kmax; l=lmax*10.;
           }
     p2[thetai]=x[thetai]-delti[thetai]/k;        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;          delts=delt;
     k3=func(p2)-fx;        }
         }
     p2[thetai]=x[thetai]-delti[thetai]/k;    }
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    delti[theta]=delts;
     k4=func(p2)-fx;    return res;
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */   
 #ifdef DEBUG  }
     printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);  
 #endif  double hessij( double x[], double delti[], int thetai,int thetaj)
   }  {
   return res;    int i;
 }    int l=1, l1, lmax=20;
     double k1,k2,k3,k4,res,fx;
 /************** Inverse of matrix **************/    double p2[NPARMAX+1];
 void ludcmp(double **a, int n, int *indx, double *d)     int k;
 {   
   int i,imax,j,k;     fx=func(x);
   double big,dum,sum,temp;     for (k=1; k<=2; k++) {
   double *vv;       for (i=1;i<=npar;i++) p2[i]=x[i];
        p2[thetai]=x[thetai]+delti[thetai]/k;
   vv=vector(1,n);       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   *d=1.0;       k1=func(p2)-fx;
   for (i=1;i<=n;i++) {    
     big=0.0;       p2[thetai]=x[thetai]+delti[thetai]/k;
     for (j=1;j<=n;j++)       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
       if ((temp=fabs(a[i][j])) > big) big=temp;       k2=func(p2)-fx;
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");    
     vv[i]=1.0/big;       p2[thetai]=x[thetai]-delti[thetai]/k;
   }       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   for (j=1;j<=n;j++) {       k3=func(p2)-fx;
     for (i=1;i<j;i++) {    
       sum=a[i][j];       p2[thetai]=x[thetai]-delti[thetai]/k;
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
       a[i][j]=sum;       k4=func(p2)-fx;
     }       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
     big=0.0;   #ifdef DEBUG
     for (i=j;i<=n;i++) {       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
       sum=a[i][j];   #endif
       for (k=1;k<j;k++)     }
         sum -= a[i][k]*a[k][j];     return res;
       a[i][j]=sum;   }
       if ( (dum=vv[i]*fabs(sum)) >= big) {   
         big=dum;   /************** Inverse of matrix **************/
         imax=i;   void ludcmp(double **a, int n, int *indx, double *d)
       }   {
     }     int i,imax,j,k;
     if (j != imax) {     double big,dum,sum,temp;
       for (k=1;k<=n;k++) {     double *vv;
         dum=a[imax][k];    
         a[imax][k]=a[j][k];     vv=vector(1,n);
         a[j][k]=dum;     *d=1.0;
       }     for (i=1;i<=n;i++) {
       *d = -(*d);       big=0.0;
       vv[imax]=vv[j];       for (j=1;j<=n;j++)
     }         if ((temp=fabs(a[i][j])) > big) big=temp;
     indx[j]=imax;       if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
     if (a[j][j] == 0.0) a[j][j]=TINY;       vv[i]=1.0/big;
     if (j != n) {     }
       dum=1.0/(a[j][j]);     for (j=1;j<=n;j++) {
       for (i=j+1;i<=n;i++) a[i][j] *= dum;       for (i=1;i<j;i++) {
     }         sum=a[i][j];
   }         for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
   free_vector(vv,1,n);  /* Doesn't work */        a[i][j]=sum;
 ;      }
 }       big=0.0;
       for (i=j;i<=n;i++) {
 void lubksb(double **a, int n, int *indx, double b[])         sum=a[i][j];
 {         for (k=1;k<j;k++)
   int i,ii=0,ip,j;           sum -= a[i][k]*a[k][j];
   double sum;         a[i][j]=sum;
          if ( (dum=vv[i]*fabs(sum)) >= big) {
   for (i=1;i<=n;i++) {           big=dum;
     ip=indx[i];           imax=i;
     sum=b[ip];         }
     b[ip]=b[i];       }
     if (ii)       if (j != imax) {
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];         for (k=1;k<=n;k++) {
     else if (sum) ii=i;           dum=a[imax][k];
     b[i]=sum;           a[imax][k]=a[j][k];
   }           a[j][k]=dum;
   for (i=n;i>=1;i--) {         }
     sum=b[i];         *d = -(*d);
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];         vv[imax]=vv[j];
     b[i]=sum/a[i][i];       }
   }       indx[j]=imax;
 }       if (a[j][j] == 0.0) a[j][j]=TINY;
       if (j != n) {
 /************ Frequencies ********************/        dum=1.0/(a[j][j]);
 void  freqsummary(char fileres[], int agemin, int agemax, int **s, double **agev, int nlstate, int imx)        for (i=j+1;i<=n;i++) a[i][j] *= dum;
 {  /* Some frequencies */      }
      }
   int i, m, jk;    free_vector(vv,1,n);  /* Doesn't work */
   double ***freq; /* Frequencies */  ;
   double *pp;  }
   double pos;  
   FILE *ficresp;  void lubksb(double **a, int n, int *indx, double b[])
   char fileresp[FILENAMELENGTH];  {
     int i,ii=0,ip,j;
   pp=vector(1,nlstate);    double sum;
    
   strcpy(fileresp,"p");    for (i=1;i<=n;i++) {
   strcat(fileresp,fileres);      ip=indx[i];
   if((ficresp=fopen(fileresp,"w"))==NULL) {      sum=b[ip];
     printf("Problem with prevalence resultfile: %s\n", fileresp);      b[ip]=b[i];
     exit(0);      if (ii)
   }        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
       else if (sum) ii=i;
   freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,agemin,agemax+3);      b[i]=sum;
   for (i=-1; i<=nlstate+ndeath; i++)      }
     for (jk=-1; jk<=nlstate+ndeath; jk++)      for (i=n;i>=1;i--) {
       for(m=agemin; m <= agemax+3; m++)      sum=b[i];
         freq[i][jk][m]=0;      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
       b[i]=sum/a[i][i];
   for (i=1; i<=imx; i++)  {    }
     for(m=firstpass; m<= lastpass-1; m++){  }
       if(agev[m][i]==0) agev[m][i]=agemax+1;  
       if(agev[m][i]==1) agev[m][i]=agemax+2;  /************ Frequencies ********************/
        freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];  void  freqsummary(char fileres[], int agemin, int agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax)
        freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];  {  /* Some frequencies */
     }   
   }    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
     double ***freq; /* Frequencies */
   fprintf(ficresp, "#");    double *pp;
   for(i=1; i<=nlstate;i++)     double pos;
     fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);    FILE *ficresp;
 fprintf(ficresp, "\n");    char fileresp[FILENAMELENGTH];
   
   for(i=(int)agemin; i <= (int)agemax+3; i++){    pp=vector(1,nlstate);
     if(i==(int)agemax+3)  
       printf("Total");    strcpy(fileresp,"p");
     else    strcat(fileresp,fileres);
       printf("Age %d", i);    if((ficresp=fopen(fileresp,"w"))==NULL) {
     for(jk=1; jk <=nlstate ; jk++){      printf("Problem with prevalence resultfile: %s\n", fileresp);
       for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)      exit(0);
         pp[jk] += freq[jk][m][i];    }
     }    freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,agemin,agemax+3);
     for(jk=1; jk <=nlstate ; jk++){    j1=0;
       for(m=-1, pos=0; m <=0 ; m++)  
         pos += freq[jk][m][i];    j=cptcovn;
       if(pp[jk]>=1.e-10)    if (cptcovn<1) {j=1;ncodemax[1]=1;}
         printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);  
       else    for(k1=1; k1<=j;k1++){
         printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);     for(i1=1; i1<=ncodemax[k1];i1++){
     }         j1++;
     for(jk=1; jk <=nlstate ; jk++){  
       for(m=1, pp[jk]=0; m <=nlstate+ndeath; m++)          for (i=-1; i<=nlstate+ndeath; i++)  
         pp[jk] += freq[jk][m][i];           for (jk=-1; jk<=nlstate+ndeath; jk++)  
     }             for(m=agemin; m <= agemax+3; m++)
     for(jk=1,pos=0; jk <=nlstate ; jk++)               freq[i][jk][m]=0;
       pos += pp[jk];         
     for(jk=1; jk <=nlstate ; jk++){         for (i=1; i<=imx; i++) {
       if(pos>=1.e-5)           bool=1;
         printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);           if  (cptcovn>0) {
       else             for (z1=1; z1<=cptcovn; z1++)
         printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);               if (covar[Tvar[z1]][i]!= nbcode[Tvar[z1]][codtab[j1][z1]]) bool=0;
       if( i <= (int) agemax){           }
         if(pos>=1.e-5)            if (bool==1) {
           fprintf(ficresp," %d %.5f %.0f %.0f",i,pp[jk]/pos, pp[jk],pos);             for(m=firstpass; m<=lastpass-1; m++){
       else               if(agev[m][i]==0) agev[m][i]=agemax+1;
           fprintf(ficresp," %d NaNq %.0f %.0f",i,pp[jk],pos);               if(agev[m][i]==1) agev[m][i]=agemax+2;
       }               freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
     }               freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];
     for(jk=-1; jk <=nlstate+ndeath; jk++)             }
       for(m=-1; m <=nlstate+ndeath; m++)           }
         if(freq[jk][m][i] !=0 ) printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);         }
     if(i <= (int) agemax)          if  (cptcovn>0) {
       fprintf(ficresp,"\n");           fprintf(ficresp, "\n#Variable");
     printf("\n");           for (z1=1; z1<=cptcovn; z1++) fprintf(ficresp, " V%d=%d",Tvar[z1],nbcode[Tvar[z1]][codtab[j1][z1]]);
   }         }
          fprintf(ficresp, "\n#");
   fclose(ficresp);         for(i=1; i<=nlstate;i++)
   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath,(int) agemin,(int) agemax+3);           fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
   free_vector(pp,1,nlstate);         fprintf(ficresp, "\n");
          
 }  /* End of Freq */    for(i=(int)agemin; i <= (int)agemax+3; i++){
       if(i==(int)agemax+3)
 /************* Waves Concatenation ***************/        printf("Total");
       else
 void  concatwav(int wav[], int **dh, int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)        printf("Age %d", i);
 {      for(jk=1; jk <=nlstate ; jk++){
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.        for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
      Death is a valid wave (if date is known).          pp[jk] += freq[jk][m][i];
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i      }
      dh[m][i] of dh[mw[mi][i][i] is the delay between two effective waves m=mw[mi][i]      for(jk=1; jk <=nlstate ; jk++){
      and mw[mi+1][i]. dh depends on stepm.        for(m=-1, pos=0; m <=0 ; m++)
      */          pos += freq[jk][m][i];
         if(pp[jk]>=1.e-10)
   int i, mi, m;          printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
   int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;        else
 float sum=0.;          printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
       }
   for(i=1; i<=imx; i++){      for(jk=1; jk <=nlstate ; jk++){
     mi=0;        for(m=1, pp[jk]=0; m <=nlstate+ndeath; m++)
     m=firstpass;          pp[jk] += freq[jk][m][i];
     while(s[m][i] <= nlstate){      }
       if(s[m][i]>=1)      for(jk=1,pos=0; jk <=nlstate ; jk++)
         mw[++mi][i]=m;        pos += pp[jk];
       if(m >=lastpass)      for(jk=1; jk <=nlstate ; jk++){
         break;        if(pos>=1.e-5)
       else          printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
         m++;        else
     }/* end while */          printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
     if (s[m][i] > nlstate){        if( i <= (int) agemax){
       mi++;     /* Death is another wave */          if(pos>=1.e-5)
       /* if(mi==0)  never been interviewed correctly before death */            fprintf(ficresp," %d %.5f %.0f %.0f",i,pp[jk]/pos, pp[jk],pos);
          /* Only death is a correct wave */        else
       mw[mi][i]=m;            fprintf(ficresp," %d NaNq %.0f %.0f",i,pp[jk],pos);
     }        }
       }
     wav[i]=mi;      for(jk=-1; jk <=nlstate+ndeath; jk++)
     if(mi==0)        for(m=-1; m <=nlstate+ndeath; m++)
       printf("Warning, no any valid information for:%d line=%d\n",num[i],i);          if(freq[jk][m][i] !=0 ) printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
   }      if(i <= (int) agemax)
         fprintf(ficresp,"\n");
   for(i=1; i<=imx; i++){      printf("\n");
     for(mi=1; mi<wav[i];mi++){      }
       if (stepm <=0)      }
         dh[mi][i]=1;   }
       else{   
         if (s[mw[mi+1][i]][i] > nlstate) {    fclose(ficresp);
           j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);     free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath,(int) agemin,(int) agemax+3);
           if(j=0) j=1;  /* Survives at least one month after exam */    free_vector(pp,1,nlstate);
         }  
         else{  }  /* End of Freq */
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));  
           k=k+1;  /************* Waves Concatenation ***************/
           if (j >= jmax) jmax=j;  
           else if (j <= jmin)jmin=j;  void  concatwav(int wav[], int **dh, int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
           sum=sum+j;  {
         }    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
         jk= j/stepm;       Death is a valid wave (if date is known).
         jl= j -jk*stepm;       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
         ju= j -(jk+1)*stepm;       dh[m][i] of dh[mw[mi][i][i] is the delay between two effective waves m=mw[mi][i]
         if(jl <= -ju)       and mw[mi+1][i]. dh depends on stepm.
           dh[mi][i]=jk;       */
         else  
           dh[mi][i]=jk+1;    int i, mi, m;
         if(dh[mi][i]==0)    int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
           dh[mi][i]=1; /* At least one step */  float sum=0.;
       }  
     }    for(i=1; i<=imx; i++){
   }      mi=0;
   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,sum/k);      m=firstpass;
 }      while(s[m][i] <= nlstate){
         if(s[m][i]>=1)
 /*********** Health Expectancies ****************/          mw[++mi][i]=m;
         if(m >=lastpass)
 void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm)          break;
 {        else
   /* Health expectancies */          m++;
   int i, j, nhstepm, hstepm, h;      }/* end while */
   double age, agelim,hf;      if (s[m][i] > nlstate){
   double ***p3mat;        mi++;     /* Death is another wave */
         /* if(mi==0)  never been interviewed correctly before death */
   FILE  *ficreseij;           /* Only death is a correct wave */
   char filerese[FILENAMELENGTH];        mw[mi][i]=m;
       }
   strcpy(filerese,"e");  
   strcat(filerese,fileres);      wav[i]=mi;
   if((ficreseij=fopen(filerese,"w"))==NULL) {      if(mi==0)
     printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);        printf("Warning, no any valid information for:%d line=%d\n",num[i],i);
   }    }
   printf("Computing Health Expectancies: result on file '%s' \n", filerese);  
     for(i=1; i<=imx; i++){
   fprintf(ficreseij,"# Health expectancies\n");      for(mi=1; mi<wav[i];mi++){
   fprintf(ficreseij,"# Age");        if (stepm <=0)
   for(i=1; i<=nlstate;i++)          dh[mi][i]=1;
     for(j=1; j<=nlstate;j++)        else{
       fprintf(ficreseij," %1d-%1d",i,j);          if (s[mw[mi+1][i]][i] > nlstate) {
   fprintf(ficreseij,"\n");            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
             if(j=0) j=1;  /* Survives at least one month after exam */
   hstepm=1*YEARM; /*  Every j years of age (in month) */          }
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */           else{
             j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
   agelim=AGESUP;            k=k+1;
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */            if (j >= jmax) jmax=j;
     /* nhstepm age range expressed in number of stepm */            else if (j <= jmin)jmin=j;
     nhstepm=(int) rint((agelim-age)*YEARM/stepm);             sum=sum+j;
     /* Typically if 20 years = 20*12/6=40 stepm */           }
     if (stepm >= YEARM) hstepm=1;          jk= j/stepm;
     nhstepm = nhstepm/hstepm;/* Expressed in hstepm, typically 40/4=10 */          jl= j -jk*stepm;
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          ju= j -(jk+1)*stepm;
     /* Computed by stepm unit matrices, product of hstepm matrices, stored          if(jl <= -ju)
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */            dh[mi][i]=jk;
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm);            else
             dh[mi][i]=jk+1;
           if(dh[mi][i]==0)
     for(i=1; i<=nlstate;i++)            dh[mi][i]=1; /* At least one step */
       for(j=1; j<=nlstate;j++)        }
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm; h++){      }
           eij[i][j][(int)age] +=p3mat[i][j][h];    }
         }    printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,sum/k);
       }
     hf=1;  /*********** Tricode ****************************/
     if (stepm >= YEARM) hf=stepm/YEARM;  void tricode(int *Tvar, int **nbcode, int imx)
     fprintf(ficreseij,"%.0f",age );  {
     for(i=1; i<=nlstate;i++)    int Ndum[80],ij, k, j, i;
       for(j=1; j<=nlstate;j++){    int cptcode=0;
         fprintf(ficreseij," %.4f", hf*eij[i][j][(int)age]);    for (k=0; k<79; k++) Ndum[k]=0;
       }    for (k=1; k<=7; k++) ncodemax[k]=0;
     fprintf(ficreseij,"\n");   
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    for (j=1; j<=cptcovn; j++) {
   }      for (i=1; i<=imx; i++) {
   fclose(ficreseij);        ij=(int)(covar[Tvar[j]][i]);
 }        Ndum[ij]++;
         if (ij > cptcode) cptcode=ij;
 /************ Variance ******************/      }
 void varevsij(char fileres[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl)      /*printf("cptcode=%d cptcovn=%d ",cptcode,cptcovn);*/
 {      for (i=0; i<=cptcode; i++) {
   /* Variance of health expectancies */        if(Ndum[i]!=0) ncodemax[j]++;
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/      }
   double **newm;   
   double **dnewm,**doldm;      ij=1;
   int i, j, nhstepm, hstepm, h;      for (i=1; i<=ncodemax[j]; i++) {
   int k;        for (k=0; k<=79; k++) {
   FILE  *ficresvij;          if (Ndum[k] != 0) {
   char fileresv[FILENAMELENGTH];            nbcode[Tvar[j]][ij]=k;
   double *xp;            ij++;
   double **gp, **gm;          }
   double ***gradg, ***trgradg;          if (ij > ncodemax[j]) break;
   double ***p3mat;        }  
   double age,agelim;      }
   int theta;    }  
   
   strcpy(fileresv,"v");    }
   strcat(fileresv,fileres);  
   if((ficresvij=fopen(fileresv,"w"))==NULL) {  /*********** Health Expectancies ****************/
     printf("Problem with variance resultfile: %s\n", fileresv);exit(0);  
   }  void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij)
   printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);  {
     /* Health expectancies */
     int i, j, nhstepm, hstepm, h;
   fprintf(ficresvij,"# Covariances of life expectancies\n");    double age, agelim,hf;
   fprintf(ficresvij,"# Age");    double ***p3mat;
   for(i=1; i<=nlstate;i++)   
     for(j=1; j<=nlstate;j++)    fprintf(ficreseij,"# Health expectancies\n");
       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);    fprintf(ficreseij,"# Age");
   fprintf(ficresvij,"\n");    for(i=1; i<=nlstate;i++)
       for(j=1; j<=nlstate;j++)
   xp=vector(1,npar);        fprintf(ficreseij," %1d-%1d",i,j);
   dnewm=matrix(1,nlstate,1,npar);    fprintf(ficreseij,"\n");
   doldm=matrix(1,nlstate,1,nlstate);  
       hstepm=1*YEARM; /*  Every j years of age (in month) */
   hstepm=1*YEARM; /* Every year of age */    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */   
   agelim = AGESUP;    agelim=AGESUP;
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */       /* nhstepm age range expressed in number of stepm */
     if (stepm >= YEARM) hstepm=1;      nhstepm=(int) rint((agelim-age)*YEARM/stepm);
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */      /* Typically if 20 years = 20*12/6=40 stepm */
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      if (stepm >= YEARM) hstepm=1;
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);      nhstepm = nhstepm/hstepm;/* Expressed in hstepm, typically 40/4=10 */
     gp=matrix(0,nhstepm,1,nlstate);      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     gm=matrix(0,nhstepm,1,nlstate);      /* Computed by stepm unit matrices, product of hstepm matrices, stored
          in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
     for(theta=1; theta <=npar; theta++){      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);  
       for(i=1; i<=npar; i++){ /* Computes gradient */  
         xp[i] = x[i] + (i==theta ?delti[theta]:0);  
       }      for(i=1; i<=nlstate;i++)
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm);          for(j=1; j<=nlstate;j++)
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm; h++){
       for(j=1; j<= nlstate; j++){            eij[i][j][(int)age] +=p3mat[i][j][h];
         for(h=0; h<=nhstepm; h++){          }
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)     
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];      hf=1;
         }      if (stepm >= YEARM) hf=stepm/YEARM;
       }      fprintf(ficreseij,"%.0f",age );
           for(i=1; i<=nlstate;i++)
       for(i=1; i<=npar; i++) /* Computes gradient */        for(j=1; j<=nlstate;j++){
         xp[i] = x[i] - (i==theta ?delti[theta]:0);          fprintf(ficreseij," %.4f", hf*eij[i][j][(int)age]);
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm);          }
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);      fprintf(ficreseij,"\n");
       for(j=1; j<= nlstate; j++){      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         for(h=0; h<=nhstepm; h++){    }
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)  }
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];  
         }  /************ Variance ******************/
       }  void varevsij(char fileres[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij)
       for(j=1; j<= nlstate; j++)  {
         for(h=0; h<=nhstepm; h++){    /* Variance of health expectancies */
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
         }    double **newm;
     } /* End theta */    double **dnewm,**doldm;
     int i, j, nhstepm, hstepm, h;
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);    int k, cptcode;
      double *xp;
     for(h=0; h<=nhstepm; h++)    double **gp, **gm;
       for(j=1; j<=nlstate;j++)    double ***gradg, ***trgradg;
         for(theta=1; theta <=npar; theta++)    double ***p3mat;
           trgradg[h][j][theta]=gradg[h][theta][j];    double age,agelim;
     int theta;
     for(i=1;i<=nlstate;i++)  
       for(j=1;j<=nlstate;j++)     fprintf(ficresvij,"# Covariances of life expectancies\n");
         vareij[i][j][(int)age] =0.;    fprintf(ficresvij,"# Age");
     for(h=0;h<=nhstepm;h++){    for(i=1; i<=nlstate;i++)
       for(k=0;k<=nhstepm;k++){      for(j=1; j<=nlstate;j++)
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);        fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);    fprintf(ficresvij,"\n");
         for(i=1;i<=nlstate;i++)  
           for(j=1;j<=nlstate;j++)    xp=vector(1,npar);
             vareij[i][j][(int)age] += doldm[i][j];    dnewm=matrix(1,nlstate,1,npar);
       }    doldm=matrix(1,nlstate,1,nlstate);
     }   
     h=1;    hstepm=1*YEARM; /* Every year of age */
     if (stepm >= YEARM) h=stepm/YEARM;    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
     fprintf(ficresvij,"%.0f ",age );    agelim = AGESUP;
     for(i=1; i<=nlstate;i++)    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
       for(j=1; j<=nlstate;j++){      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
         fprintf(ficresvij," %.4f", h*vareij[i][j][(int)age]);      if (stepm >= YEARM) hstepm=1;
       }      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
     fprintf(ficresvij,"\n");      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     free_matrix(gp,0,nhstepm,1,nlstate);      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
     free_matrix(gm,0,nhstepm,1,nlstate);      gp=matrix(0,nhstepm,1,nlstate);
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);      gm=matrix(0,nhstepm,1,nlstate);
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);  
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      for(theta=1; theta <=npar; theta++){
   } /* End age */        for(i=1; i<=npar; i++){ /* Computes gradient */
   fclose(ficresvij);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
   free_vector(xp,1,npar);        }
   free_matrix(doldm,1,nlstate,1,npar);        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
   free_matrix(dnewm,1,nlstate,1,nlstate);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(j=1; j<= nlstate; j++){
 }          for(h=0; h<=nhstepm; h++){
             for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 /************ Variance of prevlim ******************/              gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl)          }
 {        }
   /* Variance of health expectancies */     
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/        for(i=1; i<=npar; i++) /* Computes gradient */
   double **newm;          xp[i] = x[i] - (i==theta ?delti[theta]:0);
   double **dnewm,**doldm;        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
   int i, j, nhstepm, hstepm;        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   int k;        for(j=1; j<= nlstate; j++){
   FILE  *ficresvpl;          for(h=0; h<=nhstepm; h++){
   char fileresvpl[FILENAMELENGTH];            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
   double *xp;              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
   double *gp, *gm;          }
   double **gradg, **trgradg;        }
   double age,agelim;        for(j=1; j<= nlstate; j++)
   int theta;          for(h=0; h<=nhstepm; h++){
             gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
   strcpy(fileresvpl,"vpl");          }
   strcat(fileresvpl,fileres);      } /* End theta */
   if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {  
     printf("Problem with variance prev lim resultfile: %s\n", fileresvpl);      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
     exit(0);  
   }      for(h=0; h<=nhstepm; h++)
   printf("Computing Variance-covariance of Prevalence limit: file '%s' \n", fileresvpl);        for(j=1; j<=nlstate;j++)
           for(theta=1; theta <=npar; theta++)
             trgradg[h][j][theta]=gradg[h][theta][j];
   fprintf(ficresvpl,"# Standard deviation of prevalences limit\n");  
   fprintf(ficresvpl,"# Age");      for(i=1;i<=nlstate;i++)
   for(i=1; i<=nlstate;i++)        for(j=1;j<=nlstate;j++)
       fprintf(ficresvpl," %1d-%1d",i,i);          vareij[i][j][(int)age] =0.;
   fprintf(ficresvpl,"\n");      for(h=0;h<=nhstepm;h++){
         for(k=0;k<=nhstepm;k++){
   xp=vector(1,npar);          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
   dnewm=matrix(1,nlstate,1,npar);          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
   doldm=matrix(1,nlstate,1,nlstate);          for(i=1;i<=nlstate;i++)
               for(j=1;j<=nlstate;j++)
   hstepm=1*YEARM; /* Every year of age */              vareij[i][j][(int)age] += doldm[i][j];
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */         }
   agelim = AGESUP;      }
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */      h=1;
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */       if (stepm >= YEARM) h=stepm/YEARM;
     if (stepm >= YEARM) hstepm=1;      fprintf(ficresvij,"%.0f ",age );
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */      for(i=1; i<=nlstate;i++)
     gradg=matrix(1,npar,1,nlstate);        for(j=1; j<=nlstate;j++){
     gp=vector(1,nlstate);          fprintf(ficresvij," %.4f", h*vareij[i][j][(int)age]);
     gm=vector(1,nlstate);        }
       fprintf(ficresvij,"\n");
     for(theta=1; theta <=npar; theta++){      free_matrix(gp,0,nhstepm,1,nlstate);
       for(i=1; i<=npar; i++){ /* Computes gradient */      free_matrix(gm,0,nhstepm,1,nlstate);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
       }      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       for(i=1;i<=nlstate;i++)    } /* End age */
         gp[i] = prlim[i][i];   
         free_vector(xp,1,npar);
       for(i=1; i<=npar; i++) /* Computes gradient */    free_matrix(doldm,1,nlstate,1,npar);
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    free_matrix(dnewm,1,nlstate,1,nlstate);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl);  
       for(i=1;i<=nlstate;i++)  }
         gm[i] = prlim[i][i];  
   /************ Variance of prevlim ******************/
       for(i=1;i<=nlstate;i++)  void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij)
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];  {
     } /* End theta */    /* Variance of prevalence limit */
     /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
     trgradg =matrix(1,nlstate,1,npar);    double **newm;
     double **dnewm,**doldm;
     for(j=1; j<=nlstate;j++)    int i, j, nhstepm, hstepm;
       for(theta=1; theta <=npar; theta++)    int k, cptcode;
         trgradg[j][theta]=gradg[theta][j];    double *xp;
     double *gp, *gm;
     for(i=1;i<=nlstate;i++)    double **gradg, **trgradg;
       varpl[i][(int)age] =0.;    double age,agelim;
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);    int theta;
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);     
     for(i=1;i<=nlstate;i++)    fprintf(ficresvpl,"# Standard deviation of prevalences limit\n");
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */    fprintf(ficresvpl,"# Age");
     for(i=1; i<=nlstate;i++)
     fprintf(ficresvpl,"%.0f ",age );        fprintf(ficresvpl," %1d-%1d",i,i);
     for(i=1; i<=nlstate;i++)    fprintf(ficresvpl,"\n");
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));  
     fprintf(ficresvpl,"\n");    xp=vector(1,npar);
     free_vector(gp,1,nlstate);    dnewm=matrix(1,nlstate,1,npar);
     free_vector(gm,1,nlstate);    doldm=matrix(1,nlstate,1,nlstate);
     free_matrix(gradg,1,npar,1,nlstate);   
     free_matrix(trgradg,1,nlstate,1,npar);    hstepm=1*YEARM; /* Every year of age */
   } /* End age */    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
   fclose(ficresvpl);    agelim = AGESUP;
   free_vector(xp,1,npar);    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
   free_matrix(doldm,1,nlstate,1,npar);      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
   free_matrix(dnewm,1,nlstate,1,nlstate);      if (stepm >= YEARM) hstepm=1;
       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 }      gradg=matrix(1,npar,1,nlstate);
       gp=vector(1,nlstate);
       gm=vector(1,nlstate);
   
 /***********************************************/      for(theta=1; theta <=npar; theta++){
 /**************** Main Program *****************/        for(i=1; i<=npar; i++){ /* Computes gradient */
 /***********************************************/          xp[i] = x[i] + (i==theta ?delti[theta]:0);
         }
 /*int main(int argc, char *argv[])*/        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 int main()        for(i=1;i<=nlstate;i++)
 {          gp[i] = prlim[i][i];
      
   int i,j, k, n=MAXN,iter,m,size;        for(i=1; i<=npar; i++) /* Computes gradient */
   double agedeb, agefin,hf;          xp[i] = x[i] - (i==theta ?delti[theta]:0);
   double agemin=1.e20, agemax=-1.e20;        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(i=1;i<=nlstate;i++)
   double fret;          gm[i] = prlim[i][i];
   double **xi,tmp,delta;  
         for(i=1;i<=nlstate;i++)
   double dum; /* Dummy variable */          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
   double ***p3mat;      } /* End theta */
   int *indx;  
   char line[MAXLINE], linepar[MAXLINE];      trgradg =matrix(1,nlstate,1,npar);
   char title[MAXLINE];  
   char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];      for(j=1; j<=nlstate;j++)
   char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH];        for(theta=1; theta <=npar; theta++)
   char filerest[FILENAMELENGTH];          trgradg[j][theta]=gradg[theta][j];
   char fileregp[FILENAMELENGTH];  
   char path[80],pathc[80],pathcd[80],pathtot[80];      for(i=1;i<=nlstate;i++)
   int firstobs=1, lastobs=10;        varpl[i][(int)age] =0.;
   int sdeb, sfin; /* Status at beginning and end */      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
   int c,  h , cpt,l;      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
   int ju,jl, mi;      for(i=1;i<=nlstate;i++)
   int i1,j1, k1,jk,aa,bb, stepsize;        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,**adl,*tab;  
         fprintf(ficresvpl,"%.0f ",age );
   int hstepm, nhstepm;      for(i=1; i<=nlstate;i++)
   double bage, fage, age, agelim, agebase;        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
   double ftolpl=FTOL;      fprintf(ficresvpl,"\n");
   double **prlim;      free_vector(gp,1,nlstate);
   double *severity;      free_vector(gm,1,nlstate);
   double ***param; /* Matrix of parameters */      free_matrix(gradg,1,npar,1,nlstate);
   double  *p;      free_matrix(trgradg,1,nlstate,1,npar);
   double **matcov; /* Matrix of covariance */    } /* End age */
   double ***delti3; /* Scale */  
   double *delti; /* Scale */    free_vector(xp,1,npar);
   double ***eij, ***vareij;    free_matrix(doldm,1,nlstate,1,npar);
   double **varpl; /* Variances of prevalence limits by age */    free_matrix(dnewm,1,nlstate,1,nlstate);
   double *epj, vepp;  
   char version[80]="Imach version 0.64, May 2000, INED-EUROREVES ";  }
   char *alph[]={"a","a","b","c","d","e"}, str[4];  
   char z[1]="c";  
 #include <sys/time.h>  
 #include <time.h>  /***********************************************/
   /**************** Main Program *****************/
   /* long total_usecs;  /***********************************************/
   struct timeval start_time, end_time;  
     /*int main(int argc, char *argv[])*/
   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */  int main()
   {
   
   printf("\nIMACH, Version 0.64");    int i,j, k, n=MAXN,iter,m,size,cptcode, aaa, cptcod;
   printf("\nEnter the parameter file name: ");    double agedeb, agefin,hf;
 #define windows 1    double agemin=1.e20, agemax=-1.e20;
 #ifdef windows  
   scanf("%s",pathtot);    double fret;
   getcwd(pathcd, size);    double **xi,tmp,delta;
   cut(path,optionfile,pathtot);  
   chdir(path);    double dum; /* Dummy variable */
   replace(pathc,path);    double ***p3mat;
 #endif    int *indx;
 #ifdef unix    char line[MAXLINE], linepar[MAXLINE];
   scanf("%s",optionfile);    char title[MAXLINE];
 #endif    char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
     char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH];
 /*-------- arguments in the command line --------*/    char filerest[FILENAMELENGTH];
     char fileregp[FILENAMELENGTH];
   strcpy(fileres,"r");    char path[80],pathc[80],pathcd[80],pathtot[80],model[20];
   strcat(fileres, optionfile);    int firstobs=1, lastobs=10;
     int sdeb, sfin; /* Status at beginning and end */
   /*---------arguments file --------*/    int c,  h , cpt,l;
     int ju,jl, mi;
   if((ficpar=fopen(optionfile,"r"))==NULL)    {    int i1,j1, k1,jk,aa,bb, stepsize;
     printf("Problem with optionfile %s\n",optionfile);    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,**adl,*tab;
     goto end;   
   }    int hstepm, nhstepm;
     double bage, fage, age, agelim, agebase;
   strcpy(filereso,"o");    double ftolpl=FTOL;
   strcat(filereso,fileres);    double **prlim;
   if((ficparo=fopen(filereso,"w"))==NULL) {    double *severity;
     printf("Problem with Output resultfile: %s\n", filereso);goto end;    double ***param; /* Matrix of parameters */
   }    double  *p;
     double **matcov; /* Matrix of covariance */
 /*--------- index.htm --------*/    double ***delti3; /* Scale */
     double *delti; /* Scale */
   if((fichtm=fopen("index.htm","w"))==NULL)    {    double ***eij, ***vareij;
     printf("Problem with index.htm \n");goto end;    double **varpl; /* Variances of prevalence limits by age */
   }    double *epj, vepp;
     char version[80]="Imach version 62c, May 1999, INED-EUROREVES ";
  fprintf(fichtm,"<body><ul><li>Outputs files<br><br>\n    char *alph[]={"a","a","b","c","d","e"}, str[4];
         - Observed prevalence in each state: <a href=\"p%s\">p%s</a> <br>\n    char z[1]="c", occ;
 - Estimated parameters and the covariance matrix: <a href=\"%s\">%s</a> <br>  #include <sys/time.h>
         - Stationary prevalence in each state: <a href=\"pl%s\">pl%s</a> <br>  #include <time.h>
         - Transition probabilities: <a href=\"pij%s\">pij%s</a><br>    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
         - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>    /* long total_usecs;
         - Life expectancies by age and initial health status: <a href=\"e%s\">e%s</a> <br>    struct timeval start_time, end_time;
         - Variances of life expectancies by age and initial health status: <a href=\"v%s\">v%s</a><br>   
         - Health expectancies with their variances: <a href=\"t%s\">t%s</a> <br>    gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
         - Standard deviation of stationary prevalences: <a href=\"vpl%s\">vpl%s</a> <br><br>",fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres);  
   
  fprintf(fichtm," <li>Graphs<br> <br>");    printf("\nIMACH, Version 0.63");
      printf("\nEnter the parameter file name: ");
 for(cpt=1; cpt<nlstate;cpt++)  
    fprintf(fichtm,"- Prevalence of disability: p%s1.gif<br>  #ifdef windows
 <img src=\"p%s1.gif\"><br>",strtok(optionfile, "."),strtok(optionfile, "."),cpt);    scanf("%s",pathtot);
  for(cpt=1; cpt<=nlstate;cpt++)    getcwd(pathcd, size);
      fprintf(fichtm,"- Observed and stationary  prevalence (with confident    cutv(path,optionfile,pathtot,'\\');
 interval) in state (%d): v%s%d.gif <br>    chdir(path);
 <img src=\"v%s%d.gif\"><br>",cpt,strtok(optionfile, "."),cpt,strtok(optionfile, "."),cpt);    replace(pathc,path);
    #endif
  for(cpt=1; cpt<=nlstate;cpt++)  #ifdef unix
      fprintf(fichtm,"- Health life expectancies by age and initial health state (%d): exp%s%d.gif <br>    scanf("%s",optionfile);
 <img src=\"ex%s%d.gif\"><br>",cpt,strtok(optionfile, "."),cpt,strtok(optionfile, "."),cpt);  #endif
      
  fprintf(fichtm,"- Total life expectancy by age and  /*-------- arguments in the command line --------*/
         health expectancies in states (1) and (2): e%s.gif<br>  
         <img src=\"e%s.gif\"></li> </ul></body>",strtok(optionfile, "."),strtok(optionfile, "."));    strcpy(fileres,"r");
     strcat(fileres, optionfile);
   
 fclose(fichtm);    /*---------arguments file --------*/
   
   /* Reads comments: lines beginning with '#' */    if((ficpar=fopen(optionfile,"r"))==NULL)    {
   while((c=getc(ficpar))=='#' && c!= EOF){      printf("Problem with optionfile %s\n",optionfile);
     ungetc(c,ficpar);      goto end;
     fgets(line, MAXLINE, ficpar);    }
     puts(line);  
     fputs(line,ficparo);    strcpy(filereso,"o");
   }    strcat(filereso,fileres);
   ungetc(c,ficpar);    if((ficparo=fopen(filereso,"w"))==NULL) {
       printf("Problem with Output resultfile: %s\n", filereso);goto end;
   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncov, &nlstate,&ndeath, &maxwav, &mle, &weightopt);    }
   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncov, nlstate,ndeath, maxwav, mle, weightopt);  
   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncov,nlstate,ndeath,maxwav, mle, weightopt);    /* Reads comments: lines beginning with '#' */
       while((c=getc(ficpar))=='#' && c!= EOF){
   nvar=ncov-1; /* Suppressing age as a basic covariate */      ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
   /* Read guess parameters */      puts(line);
   /* Reads comments: lines beginning with '#' */      fputs(line,ficparo);
   while((c=getc(ficpar))=='#' && c!= EOF){    }
     ungetc(c,ficpar);    ungetc(c,ficpar);
     fgets(line, MAXLINE, ficpar);  
     puts(line);    fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncov, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
     fputs(line,ficparo);    printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncov, nlstate,ndeath, maxwav, mle, weightopt,model);
   }    fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncov,nlstate,ndeath,maxwav, mle, weightopt,model);
   ungetc(c,ficpar);  
       covar=matrix(1,NCOVMAX,1,n);    
   param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncov);    if (strlen(model)<=1) cptcovn=0;
     for(i=1; i <=nlstate; i++)    else {
     for(j=1; j <=nlstate+ndeath-1; j++){      j=0;
       fscanf(ficpar,"%1d%1d",&i1,&j1);      j=nbocc(model,'+');
       fprintf(ficparo,"%1d%1d",i1,j1);      cptcovn=j+1;
       printf("%1d%1d",i,j);    }
       for(k=1; k<=ncov;k++){  
         fscanf(ficpar," %lf",&param[i][j][k]);    ncovmodel=2+cptcovn;
         printf(" %lf",param[i][j][k]);    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
         fprintf(ficparo," %lf",param[i][j][k]);   
       }    /* Read guess parameters */
       fscanf(ficpar,"\n");    /* Reads comments: lines beginning with '#' */
       printf("\n");    while((c=getc(ficpar))=='#' && c!= EOF){
       fprintf(ficparo,"\n");      ungetc(c,ficpar);
     }      fgets(line, MAXLINE, ficpar);
         puts(line);
   npar= (nlstate+ndeath-1)*nlstate*ncov;      fputs(line,ficparo);
   p=param[1][1];    }
       ungetc(c,ficpar);
   /* Reads comments: lines beginning with '#' */   
   while((c=getc(ficpar))=='#' && c!= EOF){    param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     ungetc(c,ficpar);      for(i=1; i <=nlstate; i++)
     fgets(line, MAXLINE, ficpar);      for(j=1; j <=nlstate+ndeath-1; j++){
     puts(line);        fscanf(ficpar,"%1d%1d",&i1,&j1);
     fputs(line,ficparo);        fprintf(ficparo,"%1d%1d",i1,j1);
   }        printf("%1d%1d",i,j);
   ungetc(c,ficpar);        for(k=1; k<=ncovmodel;k++){
           fscanf(ficpar," %lf",&param[i][j][k]);
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncov);          printf(" %lf",param[i][j][k]);
   delti=vector(1,npar); /* Scale of each paramater (output from hesscov) */          fprintf(ficparo," %lf",param[i][j][k]);
   for(i=1; i <=nlstate; i++){        }
     for(j=1; j <=nlstate+ndeath-1; j++){        fscanf(ficpar,"\n");
       fscanf(ficpar,"%1d%1d",&i1,&j1);        printf("\n");
       printf("%1d%1d",i,j);        fprintf(ficparo,"\n");
       fprintf(ficparo,"%1d%1d",i1,j1);      }
       for(k=1; k<=ncov;k++){   
         fscanf(ficpar,"%le",&delti3[i][j][k]);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel;
         printf(" %le",delti3[i][j][k]);    p=param[1][1];
         fprintf(ficparo," %le",delti3[i][j][k]);   
       }    /* Reads comments: lines beginning with '#' */
       fscanf(ficpar,"\n");    while((c=getc(ficpar))=='#' && c!= EOF){
       printf("\n");      ungetc(c,ficpar);
       fprintf(ficparo,"\n");      fgets(line, MAXLINE, ficpar);
     }      puts(line);
   }      fputs(line,ficparo);
   delti=delti3[1][1];    }
       ungetc(c,ficpar);
   /* Reads comments: lines beginning with '#' */  
   while((c=getc(ficpar))=='#' && c!= EOF){    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     ungetc(c,ficpar);    delti=vector(1,npar); /* Scale of each paramater (output from hesscov) */
     fgets(line, MAXLINE, ficpar);    for(i=1; i <=nlstate; i++){
     puts(line);      for(j=1; j <=nlstate+ndeath-1; j++){
     fputs(line,ficparo);        fscanf(ficpar,"%1d%1d",&i1,&j1);
   }        printf("%1d%1d",i,j);
   ungetc(c,ficpar);        fprintf(ficparo,"%1d%1d",i1,j1);
           for(k=1; k<=ncovmodel;k++){
   matcov=matrix(1,npar,1,npar);          fscanf(ficpar,"%le",&delti3[i][j][k]);
   for(i=1; i <=npar; i++){          printf(" %le",delti3[i][j][k]);
     fscanf(ficpar,"%s",&str);          fprintf(ficparo," %le",delti3[i][j][k]);
     printf("%s",str);        }
     fprintf(ficparo,"%s",str);        fscanf(ficpar,"\n");
     for(j=1; j <=i; j++){        printf("\n");
       fscanf(ficpar," %le",&matcov[i][j]);        fprintf(ficparo,"\n");
       printf(" %.5le",matcov[i][j]);      }
       fprintf(ficparo," %.5le",matcov[i][j]);    }
     }    delti=delti3[1][1];
     fscanf(ficpar,"\n");   
     printf("\n");    /* Reads comments: lines beginning with '#' */
     fprintf(ficparo,"\n");    while((c=getc(ficpar))=='#' && c!= EOF){
   }      ungetc(c,ficpar);
   for(i=1; i <=npar; i++)      fgets(line, MAXLINE, ficpar);
     for(j=i+1;j<=npar;j++)      puts(line);
       matcov[i][j]=matcov[j][i];      fputs(line,ficparo);
        }
   printf("\n");    ungetc(c,ficpar);
      
       matcov=matrix(1,npar,1,npar);
   if(mle==1){    for(i=1; i <=npar; i++){
     /*-------- data file ----------*/      fscanf(ficpar,"%s",&str);
     if((ficres =fopen(fileres,"w"))==NULL) {      printf("%s",str);
       printf("Problem with resultfile: %s\n", fileres);goto end;      fprintf(ficparo,"%s",str);
     }      for(j=1; j <=i; j++){
     fprintf(ficres,"#%s\n",version);        fscanf(ficpar," %le",&matcov[i][j]);
             printf(" %.5le",matcov[i][j]);
     if((fic=fopen(datafile,"r"))==NULL)    {        fprintf(ficparo," %.5le",matcov[i][j]);
       printf("Problem with datafile: %s\n", datafile);goto end;      }
     }      fscanf(ficpar,"\n");
           printf("\n");
     n= lastobs;      fprintf(ficparo,"\n");
     severity = vector(1,maxwav);    }
     outcome=imatrix(1,maxwav+1,1,n);    for(i=1; i <=npar; i++)
     num=ivector(1,n);      for(j=i+1;j<=npar;j++)
     moisnais=vector(1,n);        matcov[i][j]=matcov[j][i];
     annais=vector(1,n);     
     moisdc=vector(1,n);    printf("\n");
     andc=vector(1,n);  
     agedc=vector(1,n);  
     cod=ivector(1,n);     if(mle==1){
     weight=vector(1,n);      /*-------- data file ----------*/
     for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */      if((ficres =fopen(fileres,"w"))==NULL) {
     mint=matrix(1,maxwav,1,n);        printf("Problem with resultfile: %s\n", fileres);goto end;
     anint=matrix(1,maxwav,1,n);      }
     covar=matrix(1,NCOVMAX,1,n);      fprintf(ficres,"#%s\n",version);
     s=imatrix(1,maxwav+1,1,n);     
     adl=imatrix(1,maxwav+1,1,n);          if((fic=fopen(datafile,"r"))==NULL)    {
     tab=ivector(1,NCOVMAX);        printf("Problem with datafile: %s\n", datafile);goto end;
     i=1;       }
     while (fgets(line, MAXLINE, fic) != NULL)    {  
       if ((i >= firstobs) && (i <lastobs)) {      n= lastobs;
 sscanf(line,"%d %lf %lf %lf %lf/%lf %lf/%lf %lf/%lf %d %lf/%lf %d %lf/%lf %d %lf/%lf %d", &num[i], &covar[1][i], &covar[2][i],&weight[i],&moisnais[i],&annais[i],&moisdc[i],&andc[i], &mint[1][i], &anint[1][i], &s[1][i], &mint[2][i],&anint[2][i], &s[2][i],&mint[3][i],&anint[3][i], &s[3][i],&mint[4][i],&anint[4][i], &s[4][i]);      severity = vector(1,maxwav);
         i=i+1;      outcome=imatrix(1,maxwav+1,1,n);
       }      num=ivector(1,n);
     }       moisnais=vector(1,n);
   imx=i-1; /* Number of individuals */      annais=vector(1,n);
       moisdc=vector(1,n);
     fclose(fic);      andc=vector(1,n);
       agedc=vector(1,n);
     if (weightopt != 1) { /* Maximisation without weights*/      cod=ivector(1,n);
       for(i=1;i<=n;i++) weight[i]=1.0;      weight=vector(1,n);
     }      for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
     /*-calculation of age at interview from date of interview and age at death -*/      mint=matrix(1,maxwav,1,n);
     agev=matrix(1,maxwav,1,imx);      anint=matrix(1,maxwav,1,n);
           s=imatrix(1,maxwav+1,1,n);
     for (i=1; i<=imx; i++)  {      adl=imatrix(1,maxwav+1,1,n);    
       agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);      tab=ivector(1,NCOVMAX);
       for(m=1; (m<= maxwav); m++){      ncodemax=ivector(1,8);
         if(s[m][i] >0){  
           if (s[m][i] == nlstate+1) {      i=1;
             if(agedc[i]>0)      while (fgets(line, MAXLINE, fic) != NULL)    {
               agev[m][i]=agedc[i];        if ((i >= firstobs) && (i <=lastobs)) {
             else{         
               printf("Warning negative age at death: %d line:%d\n",num[i],i);          for (j=maxwav;j>=1;j--){
               agev[m][i]=-1;            cutv(stra, strb,line,' '); s[j][i]=atoi(strb);
             }            strcpy(line,stra);
           }            cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
           else if(s[m][i] !=9){ /* Should no more exist */            cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
             agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);          }
             if(mint[m][i]==99 || anint[m][i]==9999)         
               agev[m][i]=1;          cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);
             else if(agev[m][i] <agemin){           cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);
               agemin=agev[m][i];  
               /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/          cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);
             }          cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);
             else if(agev[m][i] >agemax){  
               agemax=agev[m][i];          cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);
              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/          for (j=ncov;j>=1;j--){
             }            cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);
             /*agev[m][i]=anint[m][i]-annais[i];*/          }
             /*   agev[m][i] = age[i]+2*m;*/          num[i]=atol(stra);
           }  
           else { /* =9 */          /*printf("%d %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]),  (mint[5][i]), (anint[5][i]), (s[5][i]),  (mint[6][i]), (anint[6][i]), (s[6][i]));*/
             agev[m][i]=1;  
             s[m][i]=-1;          i=i+1;
           }        }
         }      }
         else /*= 0 Unknown */  
           agev[m][i]=1;      /*scanf("%d",i);*/
       }    imx=i-1; /* Number of individuals */
       
     }    /* Calculation of the number of parameter from char model*/
     for (i=1; i<=imx; i++)  {    Tvar=ivector(1,8);    
       for(m=1; (m<= maxwav); m++){     
         if (s[m][i] > (nlstate+ndeath)) {    if (strlen(model) >1){
           printf("Error: Wrong value in nlstate or ndeath\n");        j=0;
           goto end;      j=nbocc(model,'+');
         }      cptcovn=j+1;
       }     
     }      strcpy(modelsav,model);
       if (j==0) {
 printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);        cutv(stra,strb,modelsav,'V'); Tvar[1]=atoi(strb);
       }
     free_vector(severity,1,maxwav);      else {
     free_imatrix(outcome,1,maxwav+1,1,n);        for(i=j; i>=1;i--){
     free_vector(moisnais,1,n);          cutv(stra,strb,modelsav,'+');
     free_vector(annais,1,n);          if (strchr(strb,'*')) {
     free_matrix(mint,1,maxwav,1,n);            cutv(strd,strc,strb,'*');
     free_matrix(anint,1,maxwav,1,n);            cutv(strb,stre,strc,'V');Tvar[i+1]=ncov+1;
     free_vector(moisdc,1,n);            cutv(strb,strc,strd,'V');
     free_vector(andc,1,n);            for (k=1; k<=lastobs;k++)
               covar[ncov+1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
              }
     wav=ivector(1,imx);          else {cutv(strd,strc,strb,'V');
     dh=imatrix(1,lastpass-firstpass+1,1,imx);          Tvar[i+1]=atoi(strc);
     mw=imatrix(1,lastpass-firstpass+1,1,imx);          }
              strcpy(modelsav,stra);  
     /* Concatenates waves */        }
       concatwav(wav, dh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);        cutv(strd,strc,stra,'V');
             Tvar[1]=atoi(strc);
    /* Calculates basic frequencies. Computes observed prevalence at single age      }
        and prints on file fileres'p'. */    }
       freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx);     /*printf("tvar=%d ",Tvar[1]);
     scanf("%d ",i);*/
     pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      fclose(fic);
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      if (weightopt != 1) { /* Maximisation without weights*/
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */        for(i=1;i<=n;i++) weight[i]=1.0;
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */      }
           /*-calculation of age at interview from date of interview and age at death -*/
     /* For Powell, parameters are in a vector p[] starting at p[1]      agev=matrix(1,maxwav,1,imx);
        so we point p on param[1][1] so that p[1] maps on param[1][1][1] */     
     p=param[1][1]; /* *(*(*(param +1)+1)+0) */      for (i=1; i<=imx; i++)  {
             agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
     mlikeli(ficres,p, npar, ncov, nlstate, ftol, func);        for(m=1; (m<= maxwav); m++){
           if(s[m][i] >0){
                 if (s[m][i] == nlstate+1) {
     /*--------- results files --------------*/              if(agedc[i]>0)
     fprintf(ficres,"\ntitle=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncov, nlstate, ndeath, maxwav, mle,weightopt);                if(moisdc[i]!=99 && andc[i]!=9999)
                     agev[m][i]=agedc[i];
    jk=1;              else{
    fprintf(ficres,"# Parameters\n");                printf("Warning negative age at death: %d line:%d\n",num[i],i);
    printf("# Parameters\n");                agev[m][i]=-1;
    for(i=1,jk=1; i <=nlstate; i++){              }
      for(k=1; k <=(nlstate+ndeath); k++){            }
        if (k != i)             else if(s[m][i] !=9){ /* Should no more exist */
          {              agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
            printf("%d%d ",i,k);              if(mint[m][i]==99 || anint[m][i]==9999)
            fprintf(ficres,"%1d%1d ",i,k);                agev[m][i]=1;
            for(j=1; j <=ncov; j++){              else if(agev[m][i] <agemin){
              printf("%f ",p[jk]);                agemin=agev[m][i];
              fprintf(ficres,"%f ",p[jk]);                /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
              jk++;               }
            }              else if(agev[m][i] >agemax){
            printf("\n");                agemax=agev[m][i];
            fprintf(ficres,"\n");               /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
          }              }
      }              /*agev[m][i]=anint[m][i]-annais[i];*/
    }              /*   agev[m][i] = age[i]+2*m;*/
             }
     /* Computing hessian and covariance matrix */            else { /* =9 */
     ftolhess=ftol; /* Usually correct */              agev[m][i]=1;
     hesscov(matcov, p, npar, delti, ftolhess, func);              s[m][i]=-1;
     fprintf(ficres,"# Scales\n");            }
     printf("# Scales\n");          }
      for(i=1,jk=1; i <=nlstate; i++){          else /*= 0 Unknown */
       for(j=1; j <=nlstate+ndeath; j++){            agev[m][i]=1;
         if (j!=i) {        }
           fprintf(ficres,"%1d%1d",i,j);     
           printf("%1d%1d",i,j);      }
           for(k=1; k<=ncov;k++){      for (i=1; i<=imx; i++)  {
             printf(" %.5e",delti[jk]);        for(m=1; (m<= maxwav); m++){
             fprintf(ficres," %.5e",delti[jk]);          if (s[m][i] > (nlstate+ndeath)) {
             jk++;            printf("Error: Wrong value in nlstate or ndeath\n");  
           }            goto end;
           printf("\n");          }
           fprintf(ficres,"\n");        }
         }      }
       }  
       }  printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
       
     k=1;      free_vector(severity,1,maxwav);
     fprintf(ficres,"# Covariance\n");      free_imatrix(outcome,1,maxwav+1,1,n);
     printf("# Covariance\n");      free_vector(moisnais,1,n);
     for(i=1;i<=npar;i++){      free_vector(annais,1,n);
       /*  if (k>nlstate) k=1;      free_matrix(mint,1,maxwav,1,n);
       i1=(i-1)/(ncov*nlstate)+1;       free_matrix(anint,1,maxwav,1,n);
       fprintf(ficres,"%s%d%d",alph[k],i1,tab[i]);      free_vector(moisdc,1,n);
       printf("%s%d%d",alph[k],i1,tab[i]);*/      free_vector(andc,1,n);
       fprintf(ficres,"%3d",i);  
       printf("%3d",i);     
       for(j=1; j<=i;j++){      wav=ivector(1,imx);
         fprintf(ficres," %.5e",matcov[i][j]);      dh=imatrix(1,lastpass-firstpass+1,1,imx);
         printf(" %.5e",matcov[i][j]);      mw=imatrix(1,lastpass-firstpass+1,1,imx);
       }     
       fprintf(ficres,"\n");      /* Concatenates waves */
       printf("\n");        concatwav(wav, dh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
       k++;  
     }  
       Tcode=ivector(1,100);
     while((c=getc(ficpar))=='#' && c!= EOF){     nbcode=imatrix(1,nvar,1,8);  
       ungetc(c,ficpar);     ncodemax[1]=1;
       fgets(line, MAXLINE, ficpar);     if (cptcovn > 0) tricode(Tvar,nbcode,imx);
       puts(line);   
       fputs(line,ficparo);     codtab=imatrix(1,100,1,10);
     }     h=0;
     ungetc(c,ficpar);     m=pow(2,cptcovn);
      
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);     for(k=1;k<=cptcovn; k++){
            for(i=1; i <=(m/pow(2,k));i++){
     if (fage <= 2) {         for(j=1; j <= ncodemax[k]; j++){
       bage = agemin;           for(cpt=1; cpt <=(m/pow(2,cptcovn+1-k)); cpt++){
       fage = agemax;             h++;
     }             if (h>m) h=1;codtab[h][k]=j;
            }
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");         }
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);       }
 /*------------ gnuplot -------------*/     }
 chdir(pathcd);  
   if((ficgp=fopen("graph.gp","w"))==NULL) {     /*for(i=1; i <=m ;i++){
     printf("Problem with file graph.gp");goto end;       for(k=1; k <=cptcovn; k++){
   }         printf("i=%d k=%d %d ",i,k,codtab[i][k]);
 #ifdef windows       }
   fprintf(ficgp,"cd \"%s\" \n",pathc);       printf("\n");
 #endif     }*/
    /* 1eme*/     /*scanf("%d",i);*/
      
   for (cpt=1; cpt<= nlstate ; cpt ++) {     /* Calculates basic frequencies. Computes observed prevalence at single age
 #ifdef windows         and prints on file fileres'p'. */
     fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter gif small size 400,300\nplot [%.f:%.f] \"vpl%s\" u 1:%d \"\%%lf",agemin,fage,fileres,cpt*2);    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvar,nbcode, ncodemax);
 #endif  
 #ifdef unix  
 fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nplot [%.f:%.f] \"vpl%s\" u 1:%d \"\%%lf",agemin,fage,fileres,cpt*2);    /*scanf("%d ",i);*/
 #endif  
     for (i=1; i<= nlstate ; i ++) fprintf(ficgp," \%%lf (\%%lf)");  
     fprintf(ficgp,"\" t\"Stationary prevalence\" w l 0,\"vpl%s\" u 1:($%d+2*$%d) \"\%%lf",fileres,2*cpt,cpt*2+1);      pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     for (i=1; i<= nlstate ; i ++) fprintf(ficgp," \%%lf (\%%lf)");      oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
   fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"vpl%s\" u 1:($%d-2*$%d) \"\%%lf",fileres,2*cpt,2*cpt+1);       newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
      for (i=1; i<= nlstate ; i ++) fprintf(ficgp," \%%lf (\%%lf)");       savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
      fprintf(ficgp,"\" t\"\" w l 1,\"p%s\" u 1:($%d) t\"Observed prevalence \" w l 2",fileres,2+4*(cpt-1));      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 #ifdef unix     
 fprintf(ficgp,"\nset ter gif small size 400,300");      /* For Powell, parameters are in a vector p[] starting at p[1]
 #endif         so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 fprintf(ficgp,"\nset out \"v%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt);      p=param[1][1]; /* *(*(*(param +1)+1)+0) */
       
   }      mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
   /*2 eme*/  
       
   fprintf(ficgp,"set ylabel \"Years\" \nset ter gif small size 400,300\nplot [%.f:%.f] ",agemin,fage);      /*--------- results files --------------*/
   for (i=1; i<= nlstate+1 ; i ++) {      fprintf(ficres,"\ntitle=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncov=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncov, nlstate, ndeath, maxwav, mle,weightopt,model);
 k=2*i;     
     fprintf(ficgp,"\"t%s\" u 1:%d \"\%%lf \%%lf (\%%lf) \%%lf (\%%lf)",fileres,k);     jk=1;
     for (j=1; j< nlstate ; j ++) fprintf(ficgp," \%%lf (\%%lf)");     fprintf(ficres,"# Parameters\n");
     if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");     printf("# Parameters\n");
     else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);     for(i=1,jk=1; i <=nlstate; i++){
     fprintf(ficgp,"\"t%s\" u 1:($%d-2*$%d) \"\%%lf \%%lf (\%%lf) \%%lf (\%%lf)",fileres,k,k+1);       for(k=1; k <=(nlstate+ndeath); k++){
     for (j=1; j< nlstate ; j ++) fprintf(ficgp," \%%lf (\%%lf)");         if (k != i)
     fprintf(ficgp,"\" t\"\" w l 0,");           {
 fprintf(ficgp,"\"t%s\" u 1:($%d+2*$%d) \"\%%lf \%%lf (\%%lf) \%%lf (\%%lf)",fileres,k,k+1);             printf("%d%d ",i,k);
     for (j=1; j< nlstate ; j ++) fprintf(ficgp," \%%lf (\%%lf)");             fprintf(ficres,"%1d%1d ",i,k);
     if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");             for(j=1; j <=ncovmodel; j++){
 else fprintf(ficgp,"\" t\"\" w l 0,");               printf("%f ",p[jk]);
   }                fprintf(ficres,"%f ",p[jk]);
   fprintf(ficgp,"\nset out \"e%s.gif\" \nreplot\n\n",strtok(optionfile, "."));               jk++;
              }
   /*3eme*/             printf("\n");
 for (cpt=1; cpt<= nlstate ; cpt ++) {             fprintf(ficres,"\n");
   k=2+nlstate*(cpt-1);           }
     fprintf(ficgp,"set ter gif small size 400,300\nplot [%.f:%.f] \"e%s\" u 1:%d t \"e%d1\" w l",agemin,fage,fileres,k,cpt);       }
 for (i=1; i< nlstate ; i ++) {     }
 fprintf(ficgp,",\"e%s\" u 1:%d t \"e%d%d\" w l",fileres,k+1,cpt,i+1);  
 }       /* Computing hessian and covariance matrix */
 fprintf(ficgp,"\nset out \"ex%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt);      ftolhess=ftol; /* Usually correct */
 }      hesscov(matcov, p, npar, delti, ftolhess, func);
        fprintf(ficres,"# Scales\n");
 /* CV preval stat */      printf("# Scales\n");
 for (cpt=1; cpt<nlstate ; cpt ++) {       for(i=1,jk=1; i <=nlstate; i++){
     k=3;        for(j=1; j <=nlstate+ndeath; j++){
     fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter gif small size 400,300\nplot [%.f:%.f] \"pij%s\" u 2:($%d/($%d",agemin,agemax,fileres,k+cpt,k);          if (j!=i) {
     for (i=1; i< nlstate ; i ++)            fprintf(ficres,"%1d%1d",i,j);
       fprintf(ficgp,"+$%d",k+i);            printf("%1d%1d",i,j);
     fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);            for(k=1; k<=ncovmodel;k++){
                   printf(" %.5e",delti[jk]);
  l=3+(nlstate+ndeath)*cpt;              fprintf(ficres," %.5e",delti[jk]);
    fprintf(ficgp,",\"pij%s\" u 2:($%d/($%d",fileres,l+cpt,l);              jk++;
              }
    for (i=1; i< nlstate ; i ++) {            printf("\n");
    l=3+(nlstate+ndeath)*cpt;            fprintf(ficres,"\n");
     fprintf(ficgp,"+$%d",l+i);          }
    }        }
   fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);        }
        
         k=1;
   fprintf(ficgp,"set out \"p%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt);      fprintf(ficres,"# Covariance\n");
   }       printf("# Covariance\n");
       for(i=1;i<=npar;i++){
         /*  if (k>nlstate) k=1;
   fclose(ficgp);        i1=(i-1)/(ncovmodel*nlstate)+1;
            fprintf(ficres,"%s%d%d",alph[k],i1,tab[i]);
 chdir(path);        printf("%s%d%d",alph[k],i1,tab[i]);*/
     free_matrix(agev,1,maxwav,1,imx);        fprintf(ficres,"%3d",i);
     free_ivector(wav,1,imx);        printf("%3d",i);
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);        for(j=1; j<=i;j++){
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);          fprintf(ficres," %.5e",matcov[i][j]);
               printf(" %.5e",matcov[i][j]);
     free_imatrix(s,1,maxwav+1,1,n);        }
             fprintf(ficres,"\n");
             printf("\n");
     free_ivector(num,1,n);        k++;
     free_vector(agedc,1,n);      }
     free_vector(weight,1,n);     
     free_matrix(covar,1,NCOVMAX,1,n);      while((c=getc(ficpar))=='#' && c!= EOF){
     fclose(ficparo);        ungetc(c,ficpar);
     fclose(ficres);        fgets(line, MAXLINE, ficpar);
   }        puts(line);
         fputs(line,ficparo);
   /*________fin mle=1_________*/      }
         ungetc(c,ficpar);
      
       fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);
   /* No more information from the sample is required now */     
   /* Reads comments: lines beginning with '#' */      if (fage <= 2) {
   while((c=getc(ficpar))=='#' && c!= EOF){        bage = agemin;
     ungetc(c,ficpar);        fage = agemax;
     fgets(line, MAXLINE, ficpar);      }
     puts(line);  
     fputs(line,ficparo);      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
   }      fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);
   ungetc(c,ficpar);  /*------------ gnuplot -------------*/
     chdir(pathcd);
   fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);    if((ficgp=fopen("graph.plt","w"))==NULL) {
   printf("agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax, bage, fage);      printf("Problem with file graph.gp");goto end;
   fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);    }
   #ifdef windows
   /*--------------- Prevalence limit --------------*/    fprintf(ficgp,"cd \"%s\" \n",pathc);
     #endif
   strcpy(filerespl,"pl");  m=pow(2,cptcovn);
   strcat(filerespl,fileres);   
   if((ficrespl=fopen(filerespl,"w"))==NULL) {   /* 1eme*/
     printf("Problem with Prev limit resultfile: %s\n", filerespl);goto end;    for (cpt=1; cpt<= nlstate ; cpt ++) {
   }     for (k1=1; k1<= m ; k1 ++) {
   printf("Computing prevalence limit: result on file '%s' \n", filerespl);  
   fprintf(ficrespl,"#Prevalence limit\n");  #ifdef windows
   fprintf(ficrespl,"#Age ");      fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter gif small size 400,300\nplot [%.f:%.f] \"vpl%s\" every :::%d::%d u 1:2 \"\%%lf",agemin,fage,fileres,k1-1,k1-1);
   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);  #endif
   fprintf(ficrespl,"\n");  #ifdef unix
     fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nplot [%.f:%.f] \"vpl%s\" u 1:2 \"\%%lf",agemin,fage,fileres);
   prlim=matrix(1,nlstate,1,nlstate);  #endif
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  
   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  for (i=1; i<= nlstate ; i ++) {
   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    else fprintf(ficgp," \%%*lf (\%%*lf)");
   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */  }
         fprintf(ficgp,"\" t\"Stationary prevalence\" w l 0,\"vpl%s\" every :::%d::%d u 1:($2+2*$3) \"\%%lf",fileres,k1-1,k1-1);
   agebase=agemin;      for (i=1; i<= nlstate ; i ++) {
   agelim=agemax;    if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
   ftolpl=1.e-10;    else fprintf(ficgp," \%%*lf (\%%*lf)");
   for (age=agebase; age<=agelim; age++){  }
     prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl);    fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"vpl%s\" every :::%d::%d u 1:($2-2*$3) \"\%%lf",fileres,k1-1,k1-1);
     fprintf(ficrespl,"%.0f",age );       for (i=1; i<= nlstate ; i ++) {
     for(i=1; i<=nlstate;i++)    if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficrespl," %.5f", prlim[i][i]);    else fprintf(ficgp," \%%*lf (\%%*lf)");
     fprintf(ficrespl,"\n");  }  
   }       fprintf(ficgp,"\" t\"\" w l 1,\"p%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",fileres,k1-1,k1-1,2+4*(cpt-1));
   fclose(ficrespl);  #ifdef unix
     fprintf(ficgp,"\nset ter gif small size 400,300");
   /*------------- h Pij x at various ages ------------*/  #endif
     fprintf(ficgp,"\nset out \"v%s%d%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt,k1);
   strcpy(filerespij,"pij");  strcat(filerespij,fileres);     }
   if((ficrespij=fopen(filerespij,"w"))==NULL) {    }
     printf("Problem with Pij resultfile: %s\n", filerespij);goto end;    /*2 eme*/
   }  
   printf("Computing pij: result on file '%s' \n", filerespij);    for (k1=1; k1<= m ; k1 ++) {
   stepsize=(int) (stepm+YEARM-1)/YEARM;      fprintf(ficgp,"set ylabel \"Years\" \nset ter gif small size 400,300\nplot [%.f:%.f] ",agemin,fage);
   if (stepm<=24) stepsize=2;     
       for (i=1; i<= nlstate+1 ; i ++) {
   agelim=AGESUP;        k=2*i;
   hstepm=stepsize*YEARM; /* Every year of age */        fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:2 \"\%%lf",fileres,k1-1,k1-1);
   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */         for (j=1; j<= nlstate+1 ; j ++) {
   for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */    if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
     nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     else fprintf(ficgp," \%%*lf (\%%*lf)");
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */  }  
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
     oldm=oldms;savm=savms;        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
     hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm);        fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",fileres,k1-1,k1-1);
     fprintf(ficrespij,"# Age");        for (j=1; j<= nlstate+1 ; j ++) {
     for(i=1; i<=nlstate;i++)          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       for(j=1; j<=nlstate+ndeath;j++)          else fprintf(ficgp," \%%*lf (\%%*lf)");
         fprintf(ficrespij," %1d-%1d",i,j);  }  
     fprintf(ficrespij,"\n");        fprintf(ficgp,"\" t\"\" w l 0,");
     for (h=0; h<=nhstepm; h++){       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",fileres,k1-1,k1-1);
       fprintf(ficrespij,"%.0f %.0f",agedeb, agedeb+ h*hstepm/YEARM*stepm );        for (j=1; j<= nlstate+1 ; j ++) {
       for(i=1; i<=nlstate;i++)    if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
         for(j=1; j<=nlstate+ndeath;j++)    else fprintf(ficgp," \%%*lf (\%%*lf)");
           fprintf(ficrespij," %.5f", p3mat[i][j][h]);  }  
       fprintf(ficrespij,"\n");        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
     }        else fprintf(ficgp,"\" t\"\" w l 0,");
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      }
     fprintf(ficrespij,"\n");      fprintf(ficgp,"\nset out \"e%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),k1);
   }    }
   fclose(ficrespij);   
     /*3eme*/
   /*---------- Health expectancies and variances ------------*/  
        for (k1=1; k1<= m ; k1 ++) {
   eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      for (cpt=1; cpt<= nlstate ; cpt ++) {
   oldm=oldms;savm=savms;        k=2+nlstate*(cpt-1);
   evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm);        fprintf(ficgp,"set ter gif small size 400,300\nplot [%.f:%.f] \"e%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",agemin,fage,fileres,k1-1,k1-1,k,cpt);
           for (i=1; i< nlstate ; i ++) {
   vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",fileres,k1-1,k1-1,k+i,cpt,i+1);
   oldm=oldms;savm=savms;        }
   varevsij(fileres, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl);        fprintf(ficgp,"\nset out \"exp%s%d%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt,k1);
       }
   strcpy(filerest,"t");     }
   strcat(filerest,fileres);   
   if((ficrest=fopen(filerest,"w"))==NULL) {    /* CV preval stat */
     printf("Problem with total LE resultfile: %s\n", filerest);goto end;      for (k1=1; k1<= m ; k1 ++) {
   }      for (cpt=1; cpt<nlstate ; cpt ++) {
   printf("Computing Total LEs with variances: file '%s' \n", filerest);        k=3;
   fprintf(ficrest,"#Total LEs with variances: e.. (std) ");        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter gif small size 400,300\nplot [%.f:%.f] \"pij%s\" u ($1==%d ? ($3):1/0):($%d/($%d",agemin,agemax,fileres,k1,k+cpt+1,k+1);
   for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);        for (i=1; i< nlstate ; i ++)
   fprintf(ficrest,"\n");          fprintf(ficgp,"+$%d",k+i+1);
         fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
   hf=1;       
   if (stepm >= YEARM) hf=stepm/YEARM;        l=3+(nlstate+ndeath)*cpt;
   epj=vector(1,nlstate+1);        fprintf(ficgp,",\"pij%s\" u ($1==%d ? ($3):1/0):($%d/($%d",fileres,k1,l+cpt+1,l+1);
   for(age=bage; age <=fage ;age++){        for (i=1; i< nlstate ; i ++) {
     prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl);          l=3+(nlstate+ndeath)*cpt;
     fprintf(ficrest," %.0f",age);          fprintf(ficgp,"+$%d",l+i+1);
     for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){        }
       for(i=1, epj[j]=0.;i <=nlstate;i++) {        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
         epj[j] += prlim[i][i]*hf*eij[i][j][(int)age];        fprintf(ficgp,"set out \"p%s%d%d.gif\" \nreplot\n\n",strtok(optionfile, "."),cpt,k1);
       }      }
       epj[nlstate+1] +=epj[j];    }
     }   
     for(i=1, vepp=0.;i <=nlstate;i++)    /* proba elementaires */
       for(j=1;j <=nlstate;j++)    for(i=1,jk=1; i <=nlstate; i++){
         vepp += vareij[i][j][(int)age];      for(k=1; k <=(nlstate+ndeath); k++){
     fprintf(ficrest," %.2f (%.2f)", epj[nlstate+1],hf*sqrt(vepp));        if (k != i) {
     for(j=1;j <=nlstate;j++){          /*  fprintf(ficgp,"%1d%1d ",i,k);*/
       fprintf(ficrest," %.2f (%.2f)", epj[j],hf*sqrt(vareij[j][j][(int)age]));          for(j=1; j <=ncovmodel; j++){
     }            fprintf(ficgp,"%s%1d%1d=%f ",alph[j],i,k,p[jk]);
     fprintf(ficrest,"\n");            jk++;
   }            fprintf(ficgp,"\n");
   fclose(ficrest);          }
   fclose(ficpar);        }
   free_vector(epj,1,nlstate+1);      }
     }
   /*------- Variance limit prevalence------*/       for(jk=1; jk <=m; jk++) {
     fprintf(ficgp,"\nset ter gif small size 400,300\nset log y\nplot  [%.f:%.f] ",agemin,agemax);
   varpl=matrix(1,nlstate,(int) bage, (int) fage);    for(i=1; i <=nlstate; i++) {
   oldm=oldms;savm=savms;      for(k=1; k <=(nlstate+ndeath); k++){
   varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl);        if (k != i) {
             fprintf(ficgp," exp(a%d%d+b%d%d*x",i,k,i,k);
             for(j=3; j <=ncovmodel; j++)
   free_matrix(varpl,1,nlstate,(int) bage, (int)fage);            fprintf(ficgp,"+%s%d%d*%d",alph[j],i,k,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
             fprintf(ficgp,")/(1");
   free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);          for(k1=1; k1 <=(nlstate+ndeath); k1++)
   free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);            if (k1 != i) {
                 fprintf(ficgp,"+exp(a%d%d+b%d%d*x",i,k1,i,k1);
                 for(j=3; j <=ncovmodel; j++)
   free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);                fprintf(ficgp,"+%s%d%d*%d",alph[j],i,k,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);              fprintf(ficgp,")");
   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);            }
   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);          fprintf(ficgp,") t \"p%d%d\" ", i,k);
           if ((i+k)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
   free_matrix(matcov,1,npar,1,npar);        }
   free_vector(delti,1,npar);      }
       }
   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncov);  fprintf(ficgp,"\nset out \"pe%s%d.gif\" \nreplot\n\n",strtok(optionfile, "."),jk);  
     }
   printf("End of Imach\n");   
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */   fclose(ficgp);
     
   /* printf("Total time was %d Sec. %d uSec.\n", end_time.tv_sec -start_time.tv_sec, end_time.tv_usec -start_time.tv_usec);*/      chdir(path);
   /*printf("Total time was %d uSec.\n", total_usecs);*/      free_matrix(agev,1,maxwav,1,imx);
   /*------ End -----------*/      free_ivector(wav,1,imx);
       free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
  end:      free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
 #ifdef windows     
  chdir(pathcd);      free_imatrix(s,1,maxwav+1,1,n);
 #endif      
  system("gnuplot graph.gp");     
       free_ivector(num,1,n);
 #ifdef windows      free_vector(agedc,1,n);
   while (z[0] != 'q') {      free_vector(weight,1,n);
     chdir(pathcd);       /*free_matrix(covar,1,NCOVMAX,1,n);*/
     printf("\nType e to edit output files, c to start again, and q for exiting: ");      fclose(ficparo);
     scanf("%s",z);      fclose(ficres);
     if (z[0] == 'c') system("./imach");     }
     else if (z[0] == 'e') {     
       chdir(path);     /*________fin mle=1_________*/
       system("index.htm");     
     }  
     else if (z[0] == 'q') exit(0);   
   }      /* No more information from the sample is required now */
 #endif     /* Reads comments: lines beginning with '#' */
 }    while((c=getc(ficpar))=='#' && c!= EOF){
       ungetc(c,ficpar);
       fgets(line, MAXLINE, ficpar);
       puts(line);
       fputs(line,ficparo);
     }
     ungetc(c,ficpar);
    
   
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf\n",&agemin,&agemax, &bage, &fage);
     printf("agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax, bage, fage);
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f\n",agemin,agemax,bage,fage);
   /*--------- index.htm --------*/
   
     if((fichtm=fopen("index.htm","w"))==NULL)    {
       printf("Problem with index.htm \n");goto end;
     }
   
    fprintf(fichtm,"<body><ul> Imach, Version 0.63<hr> <li>Outputs files<br><br>\n
           - Observed prevalence in each state: <a href=\"p%s\">p%s</a> <br>\n
   - Estimated parameters and the covariance matrix: <a href=\"%s\">%s</a> <br>
           - Stationary prevalence in each state: <a href=\"pl%s\">pl%s</a> <br>
           - Transition probabilities: <a href=\"pij%s\">pij%s</a><br>
           - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>
           - Life expectancies by age and initial health status: <a href=\"e%s\">e%s</a> <br>
           - Variances of life expectancies by age and initial health status: <a href=\"v%s\">v%s</a><br>
           - Health expectancies with their variances: <a href=\"t%s\">t%s</a> <br>
           - Standard deviation of stationary prevalences: <a href=\"vpl%s\">vpl%s</a> <br><br>",fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres,fileres);
   
    fprintf(fichtm," <li>Graphs</li>\n<p>");
   
    m=cptcovn;
    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   
    j1=0;
    for(k1=1; k1<=m;k1++){
      for(i1=1; i1<=ncodemax[k1];i1++){
          j1++;
          if (cptcovn > 0) {
            fprintf(fichtm,"<hr>************ Results for covariates");
            for (cpt=1; cpt<=cptcovn;cpt++)
              fprintf(fichtm," V%d=%d ",Tvar[cpt],nbcode[Tvar[cpt]][codtab[j1][cpt]]);
            fprintf(fichtm," ************\n<hr>");
          }
          fprintf(fichtm,"<br>- Probabilities: pe%s%d.gif<br>
   <img src=\"pe%s%d.gif\">",strtok(optionfile, "."),j1,strtok(optionfile, "."),j1);    
          for(cpt=1; cpt<nlstate;cpt++){
            fprintf(fichtm,"<br>- Prevalence of disability : p%s%d%d.gif<br>
   <img src=\"p%s%d%d.gif\">",strtok(optionfile, "."),cpt,j1,strtok(optionfile, "."),cpt,j1);
          }
       for(cpt=1; cpt<=nlstate;cpt++) {
          fprintf(fichtm,"<br>- Observed and stationary prevalence (with confident
   interval) in state (%d): v%s%d%d.gif <br>
   <img src=\"v%s%d%d.gif\">",cpt,strtok(optionfile, "."),cpt,j1,strtok(optionfile, "."),cpt,j1);  
        }
        for(cpt=1; cpt<=nlstate;cpt++) {
           fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): exp%s%d%d.gif <br>
   <img src=\"ex%s%d%d.gif\">",cpt,strtok(optionfile, "."),cpt,j1,strtok(optionfile, "."),cpt,j1);
        }
        fprintf(fichtm,"\n<br>- Total life expectancy by age and
   health expectancies in states (1) and (2): e%s%d.gif<br>
   <img src=\"e%s%d.gif\">",strtok(optionfile, "."),j1,strtok(optionfile, "."),j1);
   fprintf(fichtm,"\n</body>");
      }
    }
   fclose(fichtm);
   
     /*--------------- Prevalence limit --------------*/
    
     strcpy(filerespl,"pl");
     strcat(filerespl,fileres);
     if((ficrespl=fopen(filerespl,"w"))==NULL) {
       printf("Problem with Prev limit resultfile: %s\n", filerespl);goto end;
     }
     printf("Computing prevalence limit: result on file '%s' \n", filerespl);
     fprintf(ficrespl,"#Prevalence limit\n");
     fprintf(ficrespl,"#Age ");
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
     fprintf(ficrespl,"\n");
    
     prlim=matrix(1,nlstate,1,nlstate);
     pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
     k=0;
     agebase=agemin;
     agelim=agemax;
     ftolpl=1.e-10;
     i1=cptcovn;
     if (cptcovn < 1){i1=1;}
   
     for(cptcov=1;cptcov<=i1;cptcov++){
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
           fprintf(ficrespl,"\n#****** ");
           for(j=1;j<=cptcovn;j++)
             fprintf(ficrespl,"V%d=%d ",Tvar[j],nbcode[Tvar[j]][codtab[k][j]]);
           fprintf(ficrespl,"******\n");
          
           for (age=agebase; age<=agelim; age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
             fprintf(ficrespl,"%.0f",age );
             for(i=1; i<=nlstate;i++)
             fprintf(ficrespl," %.5f", prlim[i][i]);
             fprintf(ficrespl,"\n");
           }
         }
       }
     fclose(ficrespl);
     /*------------- h Pij x at various ages ------------*/
    
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
     if((ficrespij=fopen(filerespij,"w"))==NULL) {
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
     }
     printf("Computing pij: result on file '%s' \n", filerespij);
    
     stepsize=(int) (stepm+YEARM-1)/YEARM;
     if (stepm<=24) stepsize=2;
   
     agelim=AGESUP;
     hstepm=stepsize*YEARM; /* Every year of age */
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
    
     k=0;
     for(cptcov=1;cptcov<=i1;cptcov++){
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
         k=k+1;
           fprintf(ficrespij,"\n#****** ");
           for(j=1;j<=cptcovn;j++)
             fprintf(ficrespij,"V%d=%d ",Tvar[j],nbcode[Tvar[j]][codtab[k][j]]);
           fprintf(ficrespij,"******\n");
          
           for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
             nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             oldm=oldms;savm=savms;
             hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
             fprintf(ficrespij,"# Age");
             for(i=1; i<=nlstate;i++)
               for(j=1; j<=nlstate+ndeath;j++)
                 fprintf(ficrespij," %1d-%1d",i,j);
             fprintf(ficrespij,"\n");
             for (h=0; h<=nhstepm; h++){
               fprintf(ficrespij,"%d %.0f %.0f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
               for(i=1; i<=nlstate;i++)
                 for(j=1; j<=nlstate+ndeath;j++)
                   fprintf(ficrespij," %.5f", p3mat[i][j][h]);
               fprintf(ficrespij,"\n");
             }
             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             fprintf(ficrespij,"\n");
           }
       }
     }
   
     fclose(ficrespij);
   
     /*---------- Health expectancies and variances ------------*/
   
     strcpy(filerest,"t");
     strcat(filerest,fileres);
     if((ficrest=fopen(filerest,"w"))==NULL) {
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
     }
     printf("Computing Total LEs with variances: file '%s' \n", filerest);
   
   
     strcpy(filerese,"e");
     strcat(filerese,fileres);
     if((ficreseij=fopen(filerese,"w"))==NULL) {
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
     }
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
   
    strcpy(fileresv,"v");
     strcat(fileresv,fileres);
     if((ficresvij=fopen(fileresv,"w"))==NULL) {
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
     }
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
   
     k=0;
     for(cptcov=1;cptcov<=i1;cptcov++){
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
         k=k+1;
         fprintf(ficrest,"\n#****** ");
         for(j=1;j<=cptcovn;j++)
           fprintf(ficrest,"V%d=%d ",Tvar[j],nbcode[Tvar[j]][codtab[k][j]]);
         fprintf(ficrest,"******\n");
   
         fprintf(ficreseij,"\n#****** ");
         for(j=1;j<=cptcovn;j++)
           fprintf(ficreseij,"V%d=%d ",j,nbcode[j][codtab[k][j]]);
         fprintf(ficreseij,"******\n");
   
         fprintf(ficresvij,"\n#****** ");
         for(j=1;j<=cptcovn;j++)
           fprintf(ficresvij,"V%d=%d ",j,nbcode[j][codtab[k][j]]);
         fprintf(ficresvij,"******\n");
   
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
         oldm=oldms;savm=savms;
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k);  
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
         oldm=oldms;savm=savms;
         varevsij(fileres, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k);
        
         fprintf(ficrest,"#Total LEs with variances: e.. (std) ");
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
         fprintf(ficrest,"\n");
          
         hf=1;
         if (stepm >= YEARM) hf=stepm/YEARM;
         epj=vector(1,nlstate+1);
         for(age=bage; age <=fage ;age++){
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
           fprintf(ficrest," %.0f",age);
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
             for(i=1, epj[j]=0.;i <=nlstate;i++) {
               epj[j] += prlim[i][i]*hf*eij[i][j][(int)age];
             }
             epj[nlstate+1] +=epj[j];
           }
           for(i=1, vepp=0.;i <=nlstate;i++)
             for(j=1;j <=nlstate;j++)
               vepp += vareij[i][j][(int)age];
           fprintf(ficrest," %.2f (%.2f)", epj[nlstate+1],hf*sqrt(vepp));
           for(j=1;j <=nlstate;j++){
             fprintf(ficrest," %.2f (%.2f)", epj[j],hf*sqrt(vareij[j][j][(int)age]));
           }
           fprintf(ficrest,"\n");
         }
       }
     }
          
    fclose(ficreseij);
    fclose(ficresvij);
     fclose(ficrest);
     fclose(ficpar);
     free_vector(epj,1,nlstate+1);
     /*scanf("%d ",i); */
   
     /*------- Variance limit prevalence------*/  
   
   strcpy(fileresvpl,"vpl");
     strcat(fileresvpl,fileres);
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
       printf("Problem with variance prev lim resultfile: %s\n", fileresvpl);
       exit(0);
     }
     printf("Computing Variance-covariance of Prevalence limit: file '%s' \n", fileresvpl);
   
    k=0;
    for(cptcov=1;cptcov<=i1;cptcov++){
      for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
        k=k+1;
        fprintf(ficresvpl,"\n#****** ");
        for(j=1;j<=cptcovn;j++)
          fprintf(ficresvpl,"V%d=%d ",Tvar[j],nbcode[Tvar[j]][codtab[k][j]]);
        fprintf(ficresvpl,"******\n");
        
        varpl=matrix(1,nlstate,(int) bage, (int) fage);
        oldm=oldms;savm=savms;
        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k);
      }
    }
   
     fclose(ficresvpl);
   
     /*---------- End : free ----------------*/
     free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
    
     free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
    
    
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
    
     free_matrix(matcov,1,npar,1,npar);
     free_vector(delti,1,npar);
    
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
   
     printf("End of Imach\n");
     /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
    
     /* printf("Total time was %d Sec. %d uSec.\n", end_time.tv_sec -start_time.tv_sec, end_time.tv_usec -start_time.tv_usec);*/
     /*printf("Total time was %d uSec.\n", total_usecs);*/
     /*------ End -----------*/
   
    end:
   #ifdef windows
    chdir(pathcd);
   #endif
    system("wgnuplot graph.plt");
   
   #ifdef windows
     while (z[0] != 'q') {
       chdir(pathcd);
       printf("\nType e to edit output files, c to start again, and q for exiting: ");
       scanf("%s",z);
       if (z[0] == 'c') system("./imach");
       else if (z[0] == 'e') {
         chdir(path);
         system("index.htm");
       }
       else if (z[0] == 'q') exit(0);
     }
   #endif
   }
   
   

Removed from v.1.1  
changed lines
  Added in v.1.3


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>