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

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


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