Annotation of imach096d/src/imach.c, revision 1.58

1.58    ! lievre      1: /* $Id: imach.c,v 1.57 2002/07/25 07:37:44 lievre Exp $
1.53      brouard     2:    Interpolated Markov Chain
                      3: 
                      4:   Short summary of the programme:
                      5:   
                      6:   This program computes Healthy Life Expectancies from
                      7:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                      8:   first survey ("cross") where individuals from different ages are
                      9:   interviewed on their health status or degree of disability (in the
                     10:   case of a health survey which is our main interest) -2- at least a
                     11:   second wave of interviews ("longitudinal") which measure each change
                     12:   (if any) in individual health status.  Health expectancies are
                     13:   computed from the time spent in each health state according to a
                     14:   model. More health states you consider, more time is necessary to reach the
                     15:   Maximum Likelihood of the parameters involved in the model.  The
                     16:   simplest model is the multinomial logistic model where pij is the
                     17:   probability to be observed in state j at the second wave
                     18:   conditional to be observed in state i at the first wave. Therefore
                     19:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                     20:   'age' is age and 'sex' is a covariate. If you want to have a more
                     21:   complex model than "constant and age", you should modify the program
                     22:   where the markup *Covariates have to be included here again* invites
                     23:   you to do it.  More covariates you add, slower the
                     24:   convergence.
                     25: 
                     26:   The advantage of this computer programme, compared to a simple
                     27:   multinomial logistic model, is clear when the delay between waves is not
                     28:   identical for each individual. Also, if a individual missed an
                     29:   intermediate interview, the information is lost, but taken into
                     30:   account using an interpolation or extrapolation.  
                     31: 
                     32:   hPijx is the probability to be observed in state i at age x+h
                     33:   conditional to the observed state i at age x. The delay 'h' can be
                     34:   split into an exact number (nh*stepm) of unobserved intermediate
                     35:   states. This elementary transition (by month or quarter trimester,
                     36:   semester or year) is model as a multinomial logistic.  The hPx
                     37:   matrix is simply the matrix product of nh*stepm elementary matrices
                     38:   and the contribution of each individual to the likelihood is simply
                     39:   hPijx.
                     40: 
                     41:   Also this programme outputs the covariance matrix of the parameters but also
1.54      brouard    42:   of the life expectancies. It also computes the stable prevalence. 
1.53      brouard    43:   
                     44:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                     45:            Institut national d'études démographiques, Paris.
                     46:   This software have been partly granted by Euro-REVES, a concerted action
                     47:   from the European Union.
                     48:   It is copyrighted identically to a GNU software product, ie programme and
                     49:   software can be distributed freely for non commercial use. Latest version
                     50:   can be accessed at http://euroreves.ined.fr/imach .
                     51:   **********************************************************************/
                     52:  
                     53: #include <math.h>
                     54: #include <stdio.h>
                     55: #include <stdlib.h>
                     56: #include <unistd.h>
                     57: 
                     58: #define MAXLINE 256
                     59: #define GNUPLOTPROGRAM "gnuplot"
                     60: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                     61: #define FILENAMELENGTH 80
                     62: /*#define DEBUG*/
1.55      lievre     63: #define windows
1.53      brouard    64: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                     65: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                     66: 
                     67: #define MAXPARM 30 /* Maximum number of parameters for the optimization */
                     68: #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
                     69: 
                     70: #define NINTERVMAX 8
                     71: #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
                     72: #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
                     73: #define NCOVMAX 8 /* Maximum number of covariates */
                     74: #define MAXN 20000
                     75: #define YEARM 12. /* Number of months per year */
                     76: #define AGESUP 130
                     77: #define AGEBASE 40
                     78: #ifdef windows
                     79: #define DIRSEPARATOR '\\'
                     80: #define ODIRSEPARATOR '/'
                     81: #else
                     82: #define DIRSEPARATOR '/'
                     83: #define ODIRSEPARATOR '\\'
                     84: #endif
                     85: 
1.54      brouard    86: char version[80]="Imach version 0.8k, July 2002, INED-EUROREVES ";
1.53      brouard    87: int erreur; /* Error number */
                     88: int nvar;
                     89: int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
                     90: int npar=NPARMAX;
                     91: int nlstate=2; /* Number of live states */
                     92: int ndeath=1; /* Number of dead states */
                     93: int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
                     94: int popbased=0;
                     95: 
                     96: int *wav; /* Number of waves for this individuual 0 is possible */
                     97: int maxwav; /* Maxim number of waves */
                     98: int jmin, jmax; /* min, max spacing between 2 waves */
                     99: int mle, weightopt;
                    100: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    101: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    102: double jmean; /* Mean space between 2 waves */
                    103: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    104: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
                    105: FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
                    106: FILE *ficlog;
                    107: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    108: FILE *ficresprobmorprev;
                    109: FILE *fichtm; /* Html File */
                    110: FILE *ficreseij;
                    111: char filerese[FILENAMELENGTH];
                    112: FILE  *ficresvij;
                    113: char fileresv[FILENAMELENGTH];
                    114: FILE  *ficresvpl;
                    115: char fileresvpl[FILENAMELENGTH];
                    116: char title[MAXLINE];
                    117: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    118: char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH];
                    119: 
                    120: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    121: char filelog[FILENAMELENGTH]; /* Log file */
                    122: char filerest[FILENAMELENGTH];
                    123: char fileregp[FILENAMELENGTH];
                    124: char popfile[FILENAMELENGTH];
                    125: 
                    126: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH];
                    127: 
                    128: #define NR_END 1
                    129: #define FREE_ARG char*
                    130: #define FTOL 1.0e-10
                    131: 
                    132: #define NRANSI 
                    133: #define ITMAX 200 
                    134: 
                    135: #define TOL 2.0e-4 
                    136: 
                    137: #define CGOLD 0.3819660 
                    138: #define ZEPS 1.0e-10 
                    139: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    140: 
                    141: #define GOLD 1.618034 
                    142: #define GLIMIT 100.0 
                    143: #define TINY 1.0e-20 
                    144: 
                    145: static double maxarg1,maxarg2;
                    146: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    147: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    148:   
                    149: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    150: #define rint(a) floor(a+0.5)
                    151: 
                    152: static double sqrarg;
                    153: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    154: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    155: 
                    156: int imx; 
                    157: int stepm;
                    158: /* Stepm, step in month: minimum step interpolation*/
                    159: 
                    160: int estepm;
                    161: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    162: 
                    163: int m,nb;
                    164: int *num, firstpass=0, lastpass=4,*cod, *ncodemax, *Tage;
                    165: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.55      lievre    166: double **pmmij, ***probs;
1.53      brouard   167: double dateintmean=0;
                    168: 
                    169: double *weight;
                    170: int **s; /* Status */
                    171: double *agedc, **covar, idx;
                    172: int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
                    173: 
                    174: double ftol=FTOL; /* Tolerance for computing Max Likelihood */
                    175: double ftolhess; /* Tolerance for computing hessian */
                    176: 
                    177: /**************** split *************************/
                    178: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    179: {
                    180:    char        *s;                             /* pointer */
                    181:    int l1, l2;                         /* length counters */
                    182: 
                    183:    l1 = strlen( path );                        /* length of path */
                    184:    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    185:    s= strrchr( path, DIRSEPARATOR );           /* find last / */
                    186:    if ( s == NULL ) {                  /* no directory, so use current */
                    187:      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    188:        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    189: #if    defined(__bsd__)                /* get current working directory */
                    190:       extern char      *getwd( );
                    191: 
                    192:       if ( getwd( dirc ) == NULL ) {
                    193: #else
                    194:       extern char      *getcwd( );
                    195: 
                    196:       if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    197: #endif
                    198:          return( GLOCK_ERROR_GETCWD );
                    199:       }
                    200:       strcpy( name, path );            /* we've got it */
                    201:    } else {                            /* strip direcotry from path */
                    202:       s++;                             /* after this, the filename */
                    203:       l2 = strlen( s );                        /* length of filename */
                    204:       if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    205:       strcpy( name, s );               /* save file name */
                    206:       strncpy( dirc, path, l1 - l2 );  /* now the directory */
                    207:       dirc[l1-l2] = 0;                 /* add zero */
                    208:    }
                    209:    l1 = strlen( dirc );                        /* length of directory */
                    210: #ifdef windows
                    211:    if ( dirc[l1-1] != '\\' ) { dirc[l1] = '\\'; dirc[l1+1] = 0; }
                    212: #else
                    213:    if ( dirc[l1-1] != '/' ) { dirc[l1] = '/'; dirc[l1+1] = 0; }
                    214: #endif
                    215:    s = strrchr( name, '.' );           /* find last / */
                    216:    s++;
                    217:    strcpy(ext,s);                      /* save extension */
                    218:    l1= strlen( name);
                    219:    l2= strlen( s)+1;
                    220:    strncpy( finame, name, l1-l2);
                    221:    finame[l1-l2]= 0;
                    222:    return( 0 );                                /* we're done */
                    223: }
                    224: 
                    225: 
                    226: /******************************************/
                    227: 
                    228: void replace(char *s, char*t)
                    229: {
                    230:   int i;
                    231:   int lg=20;
                    232:   i=0;
                    233:   lg=strlen(t);
                    234:   for(i=0; i<= lg; i++) {
                    235:     (s[i] = t[i]);
                    236:     if (t[i]== '\\') s[i]='/';
                    237:   }
                    238: }
                    239: 
                    240: int nbocc(char *s, char occ)
                    241: {
                    242:   int i,j=0;
                    243:   int lg=20;
                    244:   i=0;
                    245:   lg=strlen(s);
                    246:   for(i=0; i<= lg; i++) {
                    247:   if  (s[i] == occ ) j++;
                    248:   }
                    249:   return j;
                    250: }
                    251: 
                    252: void cutv(char *u,char *v, char*t, char occ)
                    253: {
                    254:   /* cuts string t into u and v where u is ended by char occ excluding it
                    255:      and v is after occ excluding it too : ex cutv(u,v,"abcdef2ghi2j",2)
                    256:      gives u="abcedf" and v="ghi2j" */
                    257:   int i,lg,j,p=0;
                    258:   i=0;
                    259:   for(j=0; j<=strlen(t)-1; j++) {
                    260:     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
                    261:   }
                    262: 
                    263:   lg=strlen(t);
                    264:   for(j=0; j<p; j++) {
                    265:     (u[j] = t[j]);
                    266:   }
                    267:      u[p]='\0';
                    268: 
                    269:    for(j=0; j<= lg; j++) {
                    270:     if (j>=(p+1))(v[j-p-1] = t[j]);
                    271:   }
                    272: }
                    273: 
                    274: /********************** nrerror ********************/
                    275: 
                    276: void nrerror(char error_text[])
                    277: {
                    278:   fprintf(stderr,"ERREUR ...\n");
                    279:   fprintf(stderr,"%s\n",error_text);
                    280:   exit(1);
                    281: }
                    282: /*********************** vector *******************/
                    283: double *vector(int nl, int nh)
                    284: {
                    285:   double *v;
                    286:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                    287:   if (!v) nrerror("allocation failure in vector");
                    288:   return v-nl+NR_END;
                    289: }
                    290: 
                    291: /************************ free vector ******************/
                    292: void free_vector(double*v, int nl, int nh)
                    293: {
                    294:   free((FREE_ARG)(v+nl-NR_END));
                    295: }
                    296: 
                    297: /************************ivector *******************************/
                    298: int *ivector(long nl,long nh)
                    299: {
                    300:   int *v;
                    301:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                    302:   if (!v) nrerror("allocation failure in ivector");
                    303:   return v-nl+NR_END;
                    304: }
                    305: 
                    306: /******************free ivector **************************/
                    307: void free_ivector(int *v, long nl, long nh)
                    308: {
                    309:   free((FREE_ARG)(v+nl-NR_END));
                    310: }
                    311: 
                    312: /******************* imatrix *******************************/
                    313: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                    314:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                    315: { 
                    316:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                    317:   int **m; 
                    318:   
                    319:   /* allocate pointers to rows */ 
                    320:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                    321:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                    322:   m += NR_END; 
                    323:   m -= nrl; 
                    324:   
                    325:   
                    326:   /* allocate rows and set pointers to them */ 
                    327:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                    328:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                    329:   m[nrl] += NR_END; 
                    330:   m[nrl] -= ncl; 
                    331:   
                    332:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                    333:   
                    334:   /* return pointer to array of pointers to rows */ 
                    335:   return m; 
                    336: } 
                    337: 
                    338: /****************** free_imatrix *************************/
                    339: void free_imatrix(m,nrl,nrh,ncl,nch)
                    340:       int **m;
                    341:       long nch,ncl,nrh,nrl; 
                    342:      /* free an int matrix allocated by imatrix() */ 
                    343: { 
                    344:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                    345:   free((FREE_ARG) (m+nrl-NR_END)); 
                    346: } 
                    347: 
                    348: /******************* matrix *******************************/
                    349: double **matrix(long nrl, long nrh, long ncl, long nch)
                    350: {
                    351:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                    352:   double **m;
                    353: 
                    354:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    355:   if (!m) nrerror("allocation failure 1 in matrix()");
                    356:   m += NR_END;
                    357:   m -= nrl;
                    358: 
                    359:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    360:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    361:   m[nrl] += NR_END;
                    362:   m[nrl] -= ncl;
                    363: 
                    364:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    365:   return m;
                    366: }
                    367: 
                    368: /*************************free matrix ************************/
                    369: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                    370: {
                    371:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    372:   free((FREE_ARG)(m+nrl-NR_END));
                    373: }
                    374: 
                    375: /******************* ma3x *******************************/
                    376: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                    377: {
                    378:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                    379:   double ***m;
                    380: 
                    381:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    382:   if (!m) nrerror("allocation failure 1 in matrix()");
                    383:   m += NR_END;
                    384:   m -= nrl;
                    385: 
                    386:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    387:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    388:   m[nrl] += NR_END;
                    389:   m[nrl] -= ncl;
                    390: 
                    391:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    392: 
                    393:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                    394:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                    395:   m[nrl][ncl] += NR_END;
                    396:   m[nrl][ncl] -= nll;
                    397:   for (j=ncl+1; j<=nch; j++) 
                    398:     m[nrl][j]=m[nrl][j-1]+nlay;
                    399:   
                    400:   for (i=nrl+1; i<=nrh; i++) {
                    401:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                    402:     for (j=ncl+1; j<=nch; j++) 
                    403:       m[i][j]=m[i][j-1]+nlay;
                    404:   }
                    405:   return m;
                    406: }
                    407: 
                    408: /*************************free ma3x ************************/
                    409: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                    410: {
                    411:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                    412:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    413:   free((FREE_ARG)(m+nrl-NR_END));
                    414: }
                    415: 
                    416: /***************** f1dim *************************/
                    417: extern int ncom; 
                    418: extern double *pcom,*xicom;
                    419: extern double (*nrfunc)(double []); 
                    420:  
                    421: double f1dim(double x) 
                    422: { 
                    423:   int j; 
                    424:   double f;
                    425:   double *xt; 
                    426:  
                    427:   xt=vector(1,ncom); 
                    428:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                    429:   f=(*nrfunc)(xt); 
                    430:   free_vector(xt,1,ncom); 
                    431:   return f; 
                    432: } 
                    433: 
                    434: /*****************brent *************************/
                    435: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                    436: { 
                    437:   int iter; 
                    438:   double a,b,d,etemp;
                    439:   double fu,fv,fw,fx;
                    440:   double ftemp;
                    441:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                    442:   double e=0.0; 
                    443:  
                    444:   a=(ax < cx ? ax : cx); 
                    445:   b=(ax > cx ? ax : cx); 
                    446:   x=w=v=bx; 
                    447:   fw=fv=fx=(*f)(x); 
                    448:   for (iter=1;iter<=ITMAX;iter++) { 
                    449:     xm=0.5*(a+b); 
                    450:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                    451:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                    452:     printf(".");fflush(stdout);
                    453:     fprintf(ficlog,".");fflush(ficlog);
                    454: #ifdef DEBUG
                    455:     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);
                    456:     fprintf(ficlog,"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);
                    457:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                    458: #endif
                    459:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                    460:       *xmin=x; 
                    461:       return fx; 
                    462:     } 
                    463:     ftemp=fu;
                    464:     if (fabs(e) > tol1) { 
                    465:       r=(x-w)*(fx-fv); 
                    466:       q=(x-v)*(fx-fw); 
                    467:       p=(x-v)*q-(x-w)*r; 
                    468:       q=2.0*(q-r); 
                    469:       if (q > 0.0) p = -p; 
                    470:       q=fabs(q); 
                    471:       etemp=e; 
                    472:       e=d; 
                    473:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                    474:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                    475:       else { 
                    476:        d=p/q; 
                    477:        u=x+d; 
                    478:        if (u-a < tol2 || b-u < tol2) 
                    479:          d=SIGN(tol1,xm-x); 
                    480:       } 
                    481:     } else { 
                    482:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                    483:     } 
                    484:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                    485:     fu=(*f)(u); 
                    486:     if (fu <= fx) { 
                    487:       if (u >= x) a=x; else b=x; 
                    488:       SHFT(v,w,x,u) 
                    489:        SHFT(fv,fw,fx,fu) 
                    490:        } else { 
                    491:          if (u < x) a=u; else b=u; 
                    492:          if (fu <= fw || w == x) { 
                    493:            v=w; 
                    494:            w=u; 
                    495:            fv=fw; 
                    496:            fw=fu; 
                    497:          } else if (fu <= fv || v == x || v == w) { 
                    498:            v=u; 
                    499:            fv=fu; 
                    500:          } 
                    501:        } 
                    502:   } 
                    503:   nrerror("Too many iterations in brent"); 
                    504:   *xmin=x; 
                    505:   return fx; 
                    506: } 
                    507: 
                    508: /****************** mnbrak ***********************/
                    509: 
                    510: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                    511:            double (*func)(double)) 
                    512: { 
                    513:   double ulim,u,r,q, dum;
                    514:   double fu; 
                    515:  
                    516:   *fa=(*func)(*ax); 
                    517:   *fb=(*func)(*bx); 
                    518:   if (*fb > *fa) { 
                    519:     SHFT(dum,*ax,*bx,dum) 
                    520:       SHFT(dum,*fb,*fa,dum) 
                    521:       } 
                    522:   *cx=(*bx)+GOLD*(*bx-*ax); 
                    523:   *fc=(*func)(*cx); 
                    524:   while (*fb > *fc) { 
                    525:     r=(*bx-*ax)*(*fb-*fc); 
                    526:     q=(*bx-*cx)*(*fb-*fa); 
                    527:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
                    528:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
                    529:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
                    530:     if ((*bx-u)*(u-*cx) > 0.0) { 
                    531:       fu=(*func)(u); 
                    532:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
                    533:       fu=(*func)(u); 
                    534:       if (fu < *fc) { 
                    535:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                    536:          SHFT(*fb,*fc,fu,(*func)(u)) 
                    537:          } 
                    538:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
                    539:       u=ulim; 
                    540:       fu=(*func)(u); 
                    541:     } else { 
                    542:       u=(*cx)+GOLD*(*cx-*bx); 
                    543:       fu=(*func)(u); 
                    544:     } 
                    545:     SHFT(*ax,*bx,*cx,u) 
                    546:       SHFT(*fa,*fb,*fc,fu) 
                    547:       } 
                    548: } 
                    549: 
                    550: /*************** linmin ************************/
                    551: 
                    552: int ncom; 
                    553: double *pcom,*xicom;
                    554: double (*nrfunc)(double []); 
                    555:  
                    556: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                    557: { 
                    558:   double brent(double ax, double bx, double cx, 
                    559:               double (*f)(double), double tol, double *xmin); 
                    560:   double f1dim(double x); 
                    561:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                    562:              double *fc, double (*func)(double)); 
                    563:   int j; 
                    564:   double xx,xmin,bx,ax; 
                    565:   double fx,fb,fa;
                    566:  
                    567:   ncom=n; 
                    568:   pcom=vector(1,n); 
                    569:   xicom=vector(1,n); 
                    570:   nrfunc=func; 
                    571:   for (j=1;j<=n;j++) { 
                    572:     pcom[j]=p[j]; 
                    573:     xicom[j]=xi[j]; 
                    574:   } 
                    575:   ax=0.0; 
                    576:   xx=1.0; 
                    577:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
                    578:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
                    579: #ifdef DEBUG
                    580:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                    581:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                    582: #endif
                    583:   for (j=1;j<=n;j++) { 
                    584:     xi[j] *= xmin; 
                    585:     p[j] += xi[j]; 
                    586:   } 
                    587:   free_vector(xicom,1,n); 
                    588:   free_vector(pcom,1,n); 
                    589: } 
                    590: 
                    591: /*************** powell ************************/
                    592: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                    593:            double (*func)(double [])) 
                    594: { 
                    595:   void linmin(double p[], double xi[], int n, double *fret, 
                    596:              double (*func)(double [])); 
                    597:   int i,ibig,j; 
                    598:   double del,t,*pt,*ptt,*xit;
                    599:   double fp,fptt;
                    600:   double *xits;
                    601:   pt=vector(1,n); 
                    602:   ptt=vector(1,n); 
                    603:   xit=vector(1,n); 
                    604:   xits=vector(1,n); 
                    605:   *fret=(*func)(p); 
                    606:   for (j=1;j<=n;j++) pt[j]=p[j]; 
                    607:   for (*iter=1;;++(*iter)) { 
                    608:     fp=(*fret); 
                    609:     ibig=0; 
                    610:     del=0.0; 
                    611:     printf("\nPowell iter=%d -2*LL=%.12f",*iter,*fret);
                    612:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f",*iter,*fret);
                    613:     for (i=1;i<=n;i++) 
                    614:       printf(" %d %.12f",i, p[i]);
                    615:     fprintf(ficlog," %d %.12f",i, p[i]);
                    616:     printf("\n");
                    617:     fprintf(ficlog,"\n");
                    618:     for (i=1;i<=n;i++) { 
                    619:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                    620:       fptt=(*fret); 
                    621: #ifdef DEBUG
                    622:       printf("fret=%lf \n",*fret);
                    623:       fprintf(ficlog,"fret=%lf \n",*fret);
                    624: #endif
                    625:       printf("%d",i);fflush(stdout);
                    626:       fprintf(ficlog,"%d",i);fflush(ficlog);
                    627:       linmin(p,xit,n,fret,func); 
                    628:       if (fabs(fptt-(*fret)) > del) { 
                    629:        del=fabs(fptt-(*fret)); 
                    630:        ibig=i; 
                    631:       } 
                    632: #ifdef DEBUG
                    633:       printf("%d %.12e",i,(*fret));
                    634:       fprintf(ficlog,"%d %.12e",i,(*fret));
                    635:       for (j=1;j<=n;j++) {
                    636:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                    637:        printf(" x(%d)=%.12e",j,xit[j]);
                    638:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                    639:       }
                    640:       for(j=1;j<=n;j++) {
                    641:        printf(" p=%.12e",p[j]);
                    642:        fprintf(ficlog," p=%.12e",p[j]);
                    643:       }
                    644:       printf("\n");
                    645:       fprintf(ficlog,"\n");
                    646: #endif
                    647:     } 
                    648:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                    649: #ifdef DEBUG
                    650:       int k[2],l;
                    651:       k[0]=1;
                    652:       k[1]=-1;
                    653:       printf("Max: %.12e",(*func)(p));
                    654:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                    655:       for (j=1;j<=n;j++) {
                    656:        printf(" %.12e",p[j]);
                    657:        fprintf(ficlog," %.12e",p[j]);
                    658:       }
                    659:       printf("\n");
                    660:       fprintf(ficlog,"\n");
                    661:       for(l=0;l<=1;l++) {
                    662:        for (j=1;j<=n;j++) {
                    663:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                    664:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                    665:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                    666:        }
                    667:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                    668:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                    669:       }
                    670: #endif
                    671: 
                    672: 
                    673:       free_vector(xit,1,n); 
                    674:       free_vector(xits,1,n); 
                    675:       free_vector(ptt,1,n); 
                    676:       free_vector(pt,1,n); 
                    677:       return; 
                    678:     } 
                    679:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
                    680:     for (j=1;j<=n;j++) { 
                    681:       ptt[j]=2.0*p[j]-pt[j]; 
                    682:       xit[j]=p[j]-pt[j]; 
                    683:       pt[j]=p[j]; 
                    684:     } 
                    685:     fptt=(*func)(ptt); 
                    686:     if (fptt < fp) { 
                    687:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
                    688:       if (t < 0.0) { 
                    689:        linmin(p,xit,n,fret,func); 
                    690:        for (j=1;j<=n;j++) { 
                    691:          xi[j][ibig]=xi[j][n]; 
                    692:          xi[j][n]=xit[j]; 
                    693:        }
                    694: #ifdef DEBUG
                    695:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                    696:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                    697:        for(j=1;j<=n;j++){
                    698:          printf(" %.12e",xit[j]);
                    699:          fprintf(ficlog," %.12e",xit[j]);
                    700:        }
                    701:        printf("\n");
                    702:        fprintf(ficlog,"\n");
                    703: #endif
1.54      brouard   704:       }
1.53      brouard   705:     } 
                    706:   } 
                    707: } 
                    708: 
1.54      brouard   709: /**** Prevalence limit (stable prevalence)  ****************/
1.53      brouard   710: 
                    711: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                    712: {
                    713:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                    714:      matrix by transitions matrix until convergence is reached */
                    715: 
                    716:   int i, ii,j,k;
                    717:   double min, max, maxmin, maxmax,sumnew=0.;
                    718:   double **matprod2();
                    719:   double **out, cov[NCOVMAX], **pmij();
                    720:   double **newm;
                    721:   double agefin, delaymax=50 ; /* Max number of years to converge */
                    722: 
                    723:   for (ii=1;ii<=nlstate+ndeath;ii++)
                    724:     for (j=1;j<=nlstate+ndeath;j++){
                    725:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                    726:     }
                    727: 
                    728:    cov[1]=1.;
                    729:  
                    730:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                    731:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                    732:     newm=savm;
                    733:     /* Covariates have to be included here again */
                    734:      cov[2]=agefin;
                    735:   
                    736:       for (k=1; k<=cptcovn;k++) {
                    737:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
                    738:        /*      printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
                    739:       }
                    740:       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                    741:       for (k=1; k<=cptcovprod;k++)
                    742:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                    743: 
                    744:       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                    745:       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                    746:       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                    747:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                    748: 
                    749:     savm=oldm;
                    750:     oldm=newm;
                    751:     maxmax=0.;
                    752:     for(j=1;j<=nlstate;j++){
                    753:       min=1.;
                    754:       max=0.;
                    755:       for(i=1; i<=nlstate; i++) {
                    756:        sumnew=0;
                    757:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                    758:        prlim[i][j]= newm[i][j]/(1-sumnew);
                    759:        max=FMAX(max,prlim[i][j]);
                    760:        min=FMIN(min,prlim[i][j]);
                    761:       }
                    762:       maxmin=max-min;
                    763:       maxmax=FMAX(maxmax,maxmin);
                    764:     }
                    765:     if(maxmax < ftolpl){
                    766:       return prlim;
                    767:     }
                    768:   }
                    769: }
                    770: 
                    771: /*************** transition probabilities ***************/ 
                    772: 
                    773: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                    774: {
                    775:   double s1, s2;
                    776:   /*double t34;*/
                    777:   int i,j,j1, nc, ii, jj;
                    778: 
                    779:     for(i=1; i<= nlstate; i++){
                    780:     for(j=1; j<i;j++){
                    781:       for (nc=1, s2=0.;nc <=ncovmodel; nc++){
                    782:        /*s2 += param[i][j][nc]*cov[nc];*/
                    783:        s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
                    784:        /*printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2);*/
                    785:       }
                    786:       ps[i][j]=s2;
                    787:       /*printf("s1=%.17e, s2=%.17e\n",s1,s2);*/
                    788:     }
                    789:     for(j=i+1; j<=nlstate+ndeath;j++){
                    790:       for (nc=1, s2=0.;nc <=ncovmodel; nc++){
                    791:        s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
                    792:        /*printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2);*/
                    793:       }
                    794:       ps[i][j]=s2;
                    795:     }
                    796:   }
                    797:     /*ps[3][2]=1;*/
                    798: 
                    799:   for(i=1; i<= nlstate; i++){
                    800:      s1=0;
                    801:     for(j=1; j<i; j++)
                    802:       s1+=exp(ps[i][j]);
                    803:     for(j=i+1; j<=nlstate+ndeath; j++)
                    804:       s1+=exp(ps[i][j]);
                    805:     ps[i][i]=1./(s1+1.);
                    806:     for(j=1; j<i; j++)
                    807:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                    808:     for(j=i+1; j<=nlstate+ndeath; j++)
                    809:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                    810:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                    811:   } /* end i */
                    812: 
                    813:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                    814:     for(jj=1; jj<= nlstate+ndeath; jj++){
                    815:       ps[ii][jj]=0;
                    816:       ps[ii][ii]=1;
                    817:     }
                    818:   }
                    819: 
                    820: 
                    821:   /*   for(ii=1; ii<= nlstate+ndeath; ii++){
                    822:     for(jj=1; jj<= nlstate+ndeath; jj++){
                    823:      printf("%lf ",ps[ii][jj]);
                    824:    }
                    825:     printf("\n ");
                    826:     }
                    827:     printf("\n ");printf("%lf ",cov[2]);*/
                    828: /*
                    829:   for(i=1; i<= npar; i++) printf("%f ",x[i]);
                    830:   goto end;*/
                    831:     return ps;
                    832: }
                    833: 
                    834: /**************** Product of 2 matrices ******************/
                    835: 
                    836: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
                    837: {
                    838:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                    839:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                    840:   /* in, b, out are matrice of pointers which should have been initialized 
                    841:      before: only the contents of out is modified. The function returns
                    842:      a pointer to pointers identical to out */
                    843:   long i, j, k;
                    844:   for(i=nrl; i<= nrh; i++)
                    845:     for(k=ncolol; k<=ncoloh; k++)
                    846:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
                    847:        out[i][k] +=in[i][j]*b[j][k];
                    848: 
                    849:   return out;
                    850: }
                    851: 
                    852: 
                    853: /************* Higher Matrix Product ***************/
                    854: 
                    855: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                    856: {
                    857:   /* Computes the transition matrix starting at age 'age' over 'nhstepm*hstepm*stepm' month 
                    858:      duration (i.e. until
                    859:      age (in years)  age+nhstepm*stepm/12) by multiplying nhstepm*hstepm matrices. 
                    860:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                    861:      (typically every 2 years instead of every month which is too big).
                    862:      Model is determined by parameters x and covariates have to be 
                    863:      included manually here. 
                    864: 
                    865:      */
                    866: 
                    867:   int i, j, d, h, k;
                    868:   double **out, cov[NCOVMAX];
                    869:   double **newm;
                    870: 
                    871:   /* Hstepm could be zero and should return the unit matrix */
                    872:   for (i=1;i<=nlstate+ndeath;i++)
                    873:     for (j=1;j<=nlstate+ndeath;j++){
                    874:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                    875:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                    876:     }
                    877:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                    878:   for(h=1; h <=nhstepm; h++){
                    879:     for(d=1; d <=hstepm; d++){
                    880:       newm=savm;
                    881:       /* Covariates have to be included here again */
                    882:       cov[1]=1.;
                    883:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                    884:       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
                    885:       for (k=1; k<=cptcovage;k++)
                    886:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                    887:       for (k=1; k<=cptcovprod;k++)
                    888:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                    889: 
                    890: 
                    891:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                    892:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                    893:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                    894:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                    895:       savm=oldm;
                    896:       oldm=newm;
                    897:     }
                    898:     for(i=1; i<=nlstate+ndeath; i++)
                    899:       for(j=1;j<=nlstate+ndeath;j++) {
                    900:        po[i][j][h]=newm[i][j];
                    901:        /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
                    902:         */
                    903:       }
                    904:   } /* end h */
                    905:   return po;
                    906: }
                    907: 
                    908: 
                    909: /*************** log-likelihood *************/
                    910: double func( double *x)
                    911: {
                    912:   int i, ii, j, k, mi, d, kk;
                    913:   double l, ll[NLSTATEMAX], cov[NCOVMAX];
                    914:   double **out;
                    915:   double sw; /* Sum of weights */
                    916:   double lli; /* Individual log likelihood */
                    917:   long ipmx;
                    918:   /*extern weight */
                    919:   /* We are differentiating ll according to initial status */
                    920:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                    921:   /*for(i=1;i<imx;i++) 
                    922:     printf(" %d\n",s[4][i]);
                    923:   */
                    924:   cov[1]=1.;
                    925: 
                    926:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                    927:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                    928:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                    929:     for(mi=1; mi<= wav[i]-1; mi++){
                    930:       for (ii=1;ii<=nlstate+ndeath;ii++)
                    931:        for (j=1;j<=nlstate+ndeath;j++) oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                    932:       for(d=0; d<dh[mi][i]; d++){
                    933:        newm=savm;
                    934:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                    935:        for (kk=1; kk<=cptcovage;kk++) {
                    936:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                    937:        }
                    938:        
                    939:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                    940:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                    941:        savm=oldm;
                    942:        oldm=newm;
                    943:        
                    944:        
                    945:       } /* end mult */
                    946:       
                    947:       lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);
                    948:       /* printf(" %f ",out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/
                    949:       ipmx +=1;
                    950:       sw += weight[i];
                    951:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                    952:     } /* end of wave */
                    953:   } /* end of individual */
                    954: 
                    955:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                    956:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                    957:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                    958:   return -l;
                    959: }
                    960: 
                    961: 
                    962: /*********** Maximum Likelihood Estimation ***************/
                    963: 
                    964: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                    965: {
                    966:   int i,j, iter;
                    967:   double **xi,*delti;
                    968:   double fret;
                    969:   xi=matrix(1,npar,1,npar);
                    970:   for (i=1;i<=npar;i++)
                    971:     for (j=1;j<=npar;j++)
                    972:       xi[i][j]=(i==j ? 1.0 : 0.0);
                    973:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                    974:   powell(p,xi,npar,ftol,&iter,&fret,func);
                    975: 
                    976:    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
                    977:   fprintf(ficlog,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                    978:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                    979: 
                    980: }
                    981: 
                    982: /**** Computes Hessian and covariance matrix ***/
                    983: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                    984: {
                    985:   double  **a,**y,*x,pd;
                    986:   double **hess;
                    987:   int i, j,jk;
                    988:   int *indx;
                    989: 
                    990:   double hessii(double p[], double delta, int theta, double delti[]);
                    991:   double hessij(double p[], double delti[], int i, int j);
                    992:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                    993:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                    994: 
                    995:   hess=matrix(1,npar,1,npar);
                    996: 
                    997:   printf("\nCalculation of the hessian matrix. Wait...\n");
                    998:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                    999:   for (i=1;i<=npar;i++){
                   1000:     printf("%d",i);fflush(stdout);
                   1001:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   1002:     hess[i][i]=hessii(p,ftolhess,i,delti);
                   1003:     /*printf(" %f ",p[i]);*/
                   1004:     /*printf(" %lf ",hess[i][i]);*/
                   1005:   }
                   1006:   
                   1007:   for (i=1;i<=npar;i++) {
                   1008:     for (j=1;j<=npar;j++)  {
                   1009:       if (j>i) { 
                   1010:        printf(".%d%d",i,j);fflush(stdout);
                   1011:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   1012:        hess[i][j]=hessij(p,delti,i,j);
                   1013:        hess[j][i]=hess[i][j];    
                   1014:        /*printf(" %lf ",hess[i][j]);*/
                   1015:       }
                   1016:     }
                   1017:   }
                   1018:   printf("\n");
                   1019:   fprintf(ficlog,"\n");
                   1020: 
                   1021:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   1022:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   1023:   
                   1024:   a=matrix(1,npar,1,npar);
                   1025:   y=matrix(1,npar,1,npar);
                   1026:   x=vector(1,npar);
                   1027:   indx=ivector(1,npar);
                   1028:   for (i=1;i<=npar;i++)
                   1029:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   1030:   ludcmp(a,npar,indx,&pd);
                   1031: 
                   1032:   for (j=1;j<=npar;j++) {
                   1033:     for (i=1;i<=npar;i++) x[i]=0;
                   1034:     x[j]=1;
                   1035:     lubksb(a,npar,indx,x);
                   1036:     for (i=1;i<=npar;i++){ 
                   1037:       matcov[i][j]=x[i];
                   1038:     }
                   1039:   }
                   1040: 
                   1041:   printf("\n#Hessian matrix#\n");
                   1042:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   1043:   for (i=1;i<=npar;i++) { 
                   1044:     for (j=1;j<=npar;j++) { 
                   1045:       printf("%.3e ",hess[i][j]);
                   1046:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   1047:     }
                   1048:     printf("\n");
                   1049:     fprintf(ficlog,"\n");
                   1050:   }
                   1051: 
                   1052:   /* Recompute Inverse */
                   1053:   for (i=1;i<=npar;i++)
                   1054:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   1055:   ludcmp(a,npar,indx,&pd);
                   1056: 
                   1057:   /*  printf("\n#Hessian matrix recomputed#\n");
                   1058: 
                   1059:   for (j=1;j<=npar;j++) {
                   1060:     for (i=1;i<=npar;i++) x[i]=0;
                   1061:     x[j]=1;
                   1062:     lubksb(a,npar,indx,x);
                   1063:     for (i=1;i<=npar;i++){ 
                   1064:       y[i][j]=x[i];
                   1065:       printf("%.3e ",y[i][j]);
                   1066:       fprintf(ficlog,"%.3e ",y[i][j]);
                   1067:     }
                   1068:     printf("\n");
                   1069:     fprintf(ficlog,"\n");
                   1070:   }
                   1071:   */
                   1072: 
                   1073:   free_matrix(a,1,npar,1,npar);
                   1074:   free_matrix(y,1,npar,1,npar);
                   1075:   free_vector(x,1,npar);
                   1076:   free_ivector(indx,1,npar);
                   1077:   free_matrix(hess,1,npar,1,npar);
                   1078: 
                   1079: 
                   1080: }
                   1081: 
                   1082: /*************** hessian matrix ****************/
                   1083: double hessii( double x[], double delta, int theta, double delti[])
                   1084: {
                   1085:   int i;
                   1086:   int l=1, lmax=20;
                   1087:   double k1,k2;
                   1088:   double p2[NPARMAX+1];
                   1089:   double res;
                   1090:   double delt, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   1091:   double fx;
                   1092:   int k=0,kmax=10;
                   1093:   double l1;
                   1094: 
                   1095:   fx=func(x);
                   1096:   for (i=1;i<=npar;i++) p2[i]=x[i];
                   1097:   for(l=0 ; l <=lmax; l++){
                   1098:     l1=pow(10,l);
                   1099:     delts=delt;
                   1100:     for(k=1 ; k <kmax; k=k+1){
                   1101:       delt = delta*(l1*k);
                   1102:       p2[theta]=x[theta] +delt;
                   1103:       k1=func(p2)-fx;
                   1104:       p2[theta]=x[theta]-delt;
                   1105:       k2=func(p2)-fx;
                   1106:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   1107:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   1108:       
                   1109: #ifdef DEBUG
                   1110:       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);
                   1111:       fprintf(ficlog,"%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);
                   1112: #endif
                   1113:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   1114:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   1115:        k=kmax;
                   1116:       }
                   1117:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
                   1118:        k=kmax; l=lmax*10.;
                   1119:       }
                   1120:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   1121:        delts=delt;
                   1122:       }
                   1123:     }
                   1124:   }
                   1125:   delti[theta]=delts;
                   1126:   return res; 
                   1127:   
                   1128: }
                   1129: 
                   1130: double hessij( double x[], double delti[], int thetai,int thetaj)
                   1131: {
                   1132:   int i;
                   1133:   int l=1, l1, lmax=20;
                   1134:   double k1,k2,k3,k4,res,fx;
                   1135:   double p2[NPARMAX+1];
                   1136:   int k;
                   1137: 
                   1138:   fx=func(x);
                   1139:   for (k=1; k<=2; k++) {
                   1140:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   1141:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   1142:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   1143:     k1=func(p2)-fx;
                   1144:   
                   1145:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   1146:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   1147:     k2=func(p2)-fx;
                   1148:   
                   1149:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   1150:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   1151:     k3=func(p2)-fx;
                   1152:   
                   1153:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   1154:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   1155:     k4=func(p2)-fx;
                   1156:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   1157: #ifdef DEBUG
                   1158:     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);
                   1159:     fprintf(ficlog,"%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);
                   1160: #endif
                   1161:   }
                   1162:   return res;
                   1163: }
                   1164: 
                   1165: /************** Inverse of matrix **************/
                   1166: void ludcmp(double **a, int n, int *indx, double *d) 
                   1167: { 
                   1168:   int i,imax,j,k; 
                   1169:   double big,dum,sum,temp; 
                   1170:   double *vv; 
                   1171:  
                   1172:   vv=vector(1,n); 
                   1173:   *d=1.0; 
                   1174:   for (i=1;i<=n;i++) { 
                   1175:     big=0.0; 
                   1176:     for (j=1;j<=n;j++) 
                   1177:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   1178:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   1179:     vv[i]=1.0/big; 
                   1180:   } 
                   1181:   for (j=1;j<=n;j++) { 
                   1182:     for (i=1;i<j;i++) { 
                   1183:       sum=a[i][j]; 
                   1184:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   1185:       a[i][j]=sum; 
                   1186:     } 
                   1187:     big=0.0; 
                   1188:     for (i=j;i<=n;i++) { 
                   1189:       sum=a[i][j]; 
                   1190:       for (k=1;k<j;k++) 
                   1191:        sum -= a[i][k]*a[k][j]; 
                   1192:       a[i][j]=sum; 
                   1193:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   1194:        big=dum; 
                   1195:        imax=i; 
                   1196:       } 
                   1197:     } 
                   1198:     if (j != imax) { 
                   1199:       for (k=1;k<=n;k++) { 
                   1200:        dum=a[imax][k]; 
                   1201:        a[imax][k]=a[j][k]; 
                   1202:        a[j][k]=dum; 
                   1203:       } 
                   1204:       *d = -(*d); 
                   1205:       vv[imax]=vv[j]; 
                   1206:     } 
                   1207:     indx[j]=imax; 
                   1208:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   1209:     if (j != n) { 
                   1210:       dum=1.0/(a[j][j]); 
                   1211:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   1212:     } 
                   1213:   } 
                   1214:   free_vector(vv,1,n);  /* Doesn't work */
                   1215: ;
                   1216: } 
                   1217: 
                   1218: void lubksb(double **a, int n, int *indx, double b[]) 
                   1219: { 
                   1220:   int i,ii=0,ip,j; 
                   1221:   double sum; 
                   1222:  
                   1223:   for (i=1;i<=n;i++) { 
                   1224:     ip=indx[i]; 
                   1225:     sum=b[ip]; 
                   1226:     b[ip]=b[i]; 
                   1227:     if (ii) 
                   1228:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   1229:     else if (sum) ii=i; 
                   1230:     b[i]=sum; 
                   1231:   } 
                   1232:   for (i=n;i>=1;i--) { 
                   1233:     sum=b[i]; 
                   1234:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   1235:     b[i]=sum/a[i][i]; 
                   1236:   } 
                   1237: } 
                   1238: 
                   1239: /************ Frequencies ********************/
                   1240: void  freqsummary(char fileres[], int agemin, int agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2,double jprev1, double mprev1,double anprev1,double jprev2, double mprev2,double anprev2)
                   1241: {  /* Some frequencies */
                   1242:   
                   1243:   int i, m, jk, k1,i1, j1, bool, z1,z2,j;
                   1244:   int first;
                   1245:   double ***freq; /* Frequencies */
                   1246:   double *pp;
                   1247:   double pos, k2, dateintsum=0,k2cpt=0;
                   1248:   FILE *ficresp;
                   1249:   char fileresp[FILENAMELENGTH];
                   1250:   
                   1251:   pp=vector(1,nlstate);
                   1252:   probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   1253:   strcpy(fileresp,"p");
                   1254:   strcat(fileresp,fileres);
                   1255:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   1256:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   1257:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   1258:     exit(0);
                   1259:   }
                   1260:   freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,agemin,agemax+3);
                   1261:   j1=0;
                   1262:   
                   1263:   j=cptcoveff;
                   1264:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   1265: 
                   1266:   first=1;
                   1267: 
                   1268:   for(k1=1; k1<=j;k1++){
                   1269:     for(i1=1; i1<=ncodemax[k1];i1++){
                   1270:       j1++;
                   1271:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   1272:        scanf("%d", i);*/
                   1273:       for (i=-1; i<=nlstate+ndeath; i++)  
                   1274:        for (jk=-1; jk<=nlstate+ndeath; jk++)  
                   1275:          for(m=agemin; m <= agemax+3; m++)
                   1276:            freq[i][jk][m]=0;
                   1277:       
                   1278:       dateintsum=0;
                   1279:       k2cpt=0;
                   1280:       for (i=1; i<=imx; i++) {
                   1281:        bool=1;
                   1282:        if  (cptcovn>0) {
                   1283:          for (z1=1; z1<=cptcoveff; z1++) 
                   1284:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   1285:              bool=0;
                   1286:        }
1.58    ! lievre   1287:        if (bool==1){
1.53      brouard  1288:          for(m=firstpass; m<=lastpass; m++){
                   1289:            k2=anint[m][i]+(mint[m][i]/12.);
                   1290:            if ((k2>=dateprev1) && (k2<=dateprev2)) {
                   1291:              if(agev[m][i]==0) agev[m][i]=agemax+1;
                   1292:              if(agev[m][i]==1) agev[m][i]=agemax+2;
                   1293:              if (m<lastpass) {
                   1294:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   1295:                freq[s[m][i]][s[m+1][i]][(int) agemax+3] += weight[i];
                   1296:              }
                   1297:              
                   1298:              if ((agev[m][i]>1) && (agev[m][i]< (agemax+3))) {
                   1299:                dateintsum=dateintsum+k2;
                   1300:                k2cpt++;
                   1301:              }
                   1302:            }
                   1303:          }
                   1304:        }
                   1305:       }
                   1306:        
                   1307:       fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);
                   1308: 
                   1309:       if  (cptcovn>0) {
                   1310:        fprintf(ficresp, "\n#********** Variable "); 
                   1311:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   1312:        fprintf(ficresp, "**********\n#");
                   1313:       }
                   1314:       for(i=1; i<=nlstate;i++) 
                   1315:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   1316:       fprintf(ficresp, "\n");
                   1317:       
                   1318:       for(i=(int)agemin; i <= (int)agemax+3; i++){
                   1319:        if(i==(int)agemax+3){
                   1320:          fprintf(ficlog,"Total");
                   1321:        }else{
                   1322:          if(first==1){
                   1323:            first=0;
                   1324:            printf("See log file for details...\n");
                   1325:          }
                   1326:          fprintf(ficlog,"Age %d", i);
                   1327:        }
                   1328:        for(jk=1; jk <=nlstate ; jk++){
                   1329:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   1330:            pp[jk] += freq[jk][m][i]; 
                   1331:        }
                   1332:        for(jk=1; jk <=nlstate ; jk++){
                   1333:          for(m=-1, pos=0; m <=0 ; m++)
                   1334:            pos += freq[jk][m][i];
                   1335:          if(pp[jk]>=1.e-10){
                   1336:            if(first==1){
                   1337:            printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   1338:            }
                   1339:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   1340:          }else{
                   1341:            if(first==1)
                   1342:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   1343:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   1344:          }
                   1345:        }
                   1346: 
                   1347:        for(jk=1; jk <=nlstate ; jk++){
                   1348:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   1349:            pp[jk] += freq[jk][m][i];
                   1350:        }
                   1351: 
                   1352:        for(jk=1,pos=0; jk <=nlstate ; jk++)
                   1353:          pos += pp[jk];
                   1354:        for(jk=1; jk <=nlstate ; jk++){
                   1355:          if(pos>=1.e-5){
                   1356:            if(first==1)
                   1357:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   1358:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   1359:          }else{
                   1360:            if(first==1)
                   1361:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   1362:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   1363:          }
                   1364:          if( i <= (int) agemax){
                   1365:            if(pos>=1.e-5){
                   1366:              fprintf(ficresp," %d %.5f %.0f %.0f",i,pp[jk]/pos, pp[jk],pos);
                   1367:              probs[i][jk][j1]= pp[jk]/pos;
                   1368:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   1369:            }
                   1370:            else
                   1371:              fprintf(ficresp," %d NaNq %.0f %.0f",i,pp[jk],pos);
                   1372:          }
                   1373:        }
                   1374:        
                   1375:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   1376:          for(m=-1; m <=nlstate+ndeath; m++)
                   1377:            if(freq[jk][m][i] !=0 ) {
                   1378:            if(first==1)
                   1379:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   1380:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   1381:            }
                   1382:        if(i <= (int) agemax)
                   1383:          fprintf(ficresp,"\n");
                   1384:        if(first==1)
                   1385:          printf("Others in log...\n");
                   1386:        fprintf(ficlog,"\n");
                   1387:       }
                   1388:     }
                   1389:   }
                   1390:   dateintmean=dateintsum/k2cpt; 
                   1391:  
                   1392:   fclose(ficresp);
                   1393:   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath,(int) agemin,(int) agemax+3);
                   1394:   free_vector(pp,1,nlstate);
                   1395:   
                   1396:   /* End of Freq */
                   1397: }
                   1398: 
                   1399: /************ Prevalence ********************/
                   1400: void prevalence(int agemin, float agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, double calagedate)
                   1401: {  /* Some frequencies */
                   1402:  
                   1403:   int i, m, jk, k1, i1, j1, bool, z1,z2,j;
                   1404:   double ***freq; /* Frequencies */
                   1405:   double *pp;
                   1406:   double pos, k2;
                   1407: 
                   1408:   pp=vector(1,nlstate);
                   1409:   
                   1410:   freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,agemin,agemax+3);
                   1411:   j1=0;
                   1412:   
                   1413:   j=cptcoveff;
                   1414:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   1415:   
                   1416:   for(k1=1; k1<=j;k1++){
                   1417:     for(i1=1; i1<=ncodemax[k1];i1++){
                   1418:       j1++;
                   1419:       
                   1420:       for (i=-1; i<=nlstate+ndeath; i++)  
                   1421:        for (jk=-1; jk<=nlstate+ndeath; jk++)  
                   1422:          for(m=agemin; m <= agemax+3; m++)
                   1423:            freq[i][jk][m]=0;
                   1424:      
                   1425:       for (i=1; i<=imx; i++) {
                   1426:        bool=1;
                   1427:        if  (cptcovn>0) {
                   1428:          for (z1=1; z1<=cptcoveff; z1++) 
                   1429:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   1430:              bool=0;
                   1431:        } 
                   1432:        if (bool==1) { 
                   1433:          for(m=firstpass; m<=lastpass; m++){
                   1434:            k2=anint[m][i]+(mint[m][i]/12.);
                   1435:            if ((k2>=dateprev1) && (k2<=dateprev2)) {
                   1436:              if(agev[m][i]==0) agev[m][i]=agemax+1;
                   1437:              if(agev[m][i]==1) agev[m][i]=agemax+2;
                   1438:              if (m<lastpass) {
                   1439:                if (calagedate>0) 
                   1440:                  freq[s[m][i]][s[m+1][i]][(int)(agev[m][i]+1-((int)calagedate %12)/12.)] += weight[i];
                   1441:                else
                   1442:                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   1443:                freq[s[m][i]][s[m+1][i]][(int)(agemax+3)] += weight[i]; 
                   1444:              }
                   1445:            }
                   1446:          }
                   1447:        }
                   1448:       }
                   1449:       for(i=(int)agemin; i <= (int)agemax+3; i++){ 
                   1450:        for(jk=1; jk <=nlstate ; jk++){
                   1451:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   1452:            pp[jk] += freq[jk][m][i]; 
                   1453:        }
                   1454:        for(jk=1; jk <=nlstate ; jk++){
                   1455:          for(m=-1, pos=0; m <=0 ; m++)
                   1456:            pos += freq[jk][m][i];
                   1457:        }
                   1458:        
                   1459:        for(jk=1; jk <=nlstate ; jk++){
                   1460:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   1461:            pp[jk] += freq[jk][m][i];
                   1462:        }
                   1463:        
                   1464:        for(jk=1,pos=0; jk <=nlstate ; jk++) pos += pp[jk];
                   1465:        
                   1466:        for(jk=1; jk <=nlstate ; jk++){    
                   1467:          if( i <= (int) agemax){
                   1468:            if(pos>=1.e-5){
                   1469:              probs[i][jk][j1]= pp[jk]/pos;
                   1470:            }
                   1471:          }
                   1472:        }/* end jk */
                   1473:       }/* end i */
                   1474:     } /* end i1 */
                   1475:   } /* end k1 */
                   1476: 
                   1477:   
                   1478:   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath,(int) agemin,(int) agemax+3);
                   1479:   free_vector(pp,1,nlstate);
                   1480:   
                   1481: }  /* End of Freq */
                   1482: 
                   1483: /************* Waves Concatenation ***************/
                   1484: 
                   1485: void  concatwav(int wav[], int **dh, int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
                   1486: {
                   1487:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   1488:      Death is a valid wave (if date is known).
                   1489:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   1490:      dh[m][i] of dh[mw[mi][i][i] is the delay between two effective waves m=mw[mi][i]
                   1491:      and mw[mi+1][i]. dh depends on stepm.
                   1492:      */
                   1493: 
                   1494:   int i, mi, m;
                   1495:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   1496:      double sum=0., jmean=0.;*/
                   1497:   int first;
                   1498:   int j, k=0,jk, ju, jl;
                   1499:   double sum=0.;
                   1500:   first=0;
                   1501:   jmin=1e+5;
                   1502:   jmax=-1;
                   1503:   jmean=0.;
                   1504:   for(i=1; i<=imx; i++){
                   1505:     mi=0;
                   1506:     m=firstpass;
                   1507:     while(s[m][i] <= nlstate){
                   1508:       if(s[m][i]>=1)
                   1509:        mw[++mi][i]=m;
                   1510:       if(m >=lastpass)
                   1511:        break;
                   1512:       else
                   1513:        m++;
                   1514:     }/* end while */
                   1515:     if (s[m][i] > nlstate){
                   1516:       mi++;    /* Death is another wave */
                   1517:       /* if(mi==0)  never been interviewed correctly before death */
                   1518:         /* Only death is a correct wave */
                   1519:       mw[mi][i]=m;
                   1520:     }
                   1521: 
                   1522:     wav[i]=mi;
                   1523:     if(mi==0){
                   1524:       if(first==0){
                   1525:        printf("Warning, no any valid information for:%d line=%d and may be others, see log file\n",num[i],i);
                   1526:        first=1;
                   1527:       }
                   1528:       if(first==1){
                   1529:        fprintf(ficlog,"Warning, no any valid information for:%d line=%d\n",num[i],i);
                   1530:       }
                   1531:     } /* end mi==0 */
                   1532:   }
                   1533: 
                   1534:   for(i=1; i<=imx; i++){
                   1535:     for(mi=1; mi<wav[i];mi++){
                   1536:       if (stepm <=0)
                   1537:        dh[mi][i]=1;
                   1538:       else{
                   1539:        if (s[mw[mi+1][i]][i] > nlstate) {
                   1540:          if (agedc[i] < 2*AGESUP) {
                   1541:          j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   1542:          if(j==0) j=1;  /* Survives at least one month after exam */
                   1543:          k=k+1;
                   1544:          if (j >= jmax) jmax=j;
                   1545:          if (j <= jmin) jmin=j;
                   1546:          sum=sum+j;
                   1547:          /*if (j<0) printf("j=%d num=%d \n",j,i); */
                   1548:          }
                   1549:        }
                   1550:        else{
                   1551:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   1552:          k=k+1;
                   1553:          if (j >= jmax) jmax=j;
                   1554:          else if (j <= jmin)jmin=j;
                   1555:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   1556:          sum=sum+j;
                   1557:        }
                   1558:        jk= j/stepm;
                   1559:        jl= j -jk*stepm;
                   1560:        ju= j -(jk+1)*stepm;
                   1561:        if(jl <= -ju)
                   1562:          dh[mi][i]=jk;
                   1563:        else
                   1564:          dh[mi][i]=jk+1;
                   1565:        if(dh[mi][i]==0)
                   1566:          dh[mi][i]=1; /* At least one step */
                   1567:       }
                   1568:     }
                   1569:   }
                   1570:   jmean=sum/k;
                   1571:   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);
                   1572:   fprintf(ficlog,"Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);
                   1573:  }
                   1574: 
                   1575: /*********** Tricode ****************************/
                   1576: void tricode(int *Tvar, int **nbcode, int imx)
                   1577: {
1.58    ! lievre   1578:   
        !          1579:   int Ndum[20],ij=1, k, j, i, maxncov=19;
1.53      brouard  1580:   int cptcode=0;
                   1581:   cptcoveff=0; 
                   1582:  
1.58    ! lievre   1583:   for (k=0; k<maxncov; k++) Ndum[k]=0;
1.53      brouard  1584:   for (k=1; k<=7; k++) ncodemax[k]=0;
                   1585: 
                   1586:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
1.58    ! lievre   1587:     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum 
        !          1588:                               modality*/ 
        !          1589:       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
        !          1590:       Ndum[ij]++; /*store the modality */
1.53      brouard  1591:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.58    ! lievre   1592:       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable 
        !          1593:                                       Tvar[j]. If V=sex and male is 0 and 
        !          1594:                                       female is 1, then  cptcode=1.*/
1.53      brouard  1595:     }
                   1596: 
                   1597:     for (i=0; i<=cptcode; i++) {
1.58    ! lievre   1598:       if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */
1.53      brouard  1599:     }
1.58    ! lievre   1600: 
1.53      brouard  1601:     ij=1; 
                   1602:     for (i=1; i<=ncodemax[j]; i++) {
1.58    ! lievre   1603:       for (k=0; k<= maxncov; k++) {
1.53      brouard  1604:        if (Ndum[k] != 0) {
                   1605:          nbcode[Tvar[j]][ij]=k; 
1.58    ! lievre   1606:          /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.53      brouard  1607:          
                   1608:          ij++;
                   1609:        }
                   1610:        if (ij > ncodemax[j]) break; 
                   1611:       }  
                   1612:     } 
                   1613:   }  
                   1614: 
1.58    ! lievre   1615:  for (k=0; k< maxncov; k++) Ndum[k]=0;
1.53      brouard  1616: 
1.58    ! lievre   1617:  for (i=1; i<=ncovmodel-2; i++) { 
        !          1618:    /* Listing of all covariables in staement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
1.53      brouard  1619:    ij=Tvar[i];
1.58    ! lievre   1620:    Ndum[ij]++;
1.53      brouard  1621:  }
                   1622: 
                   1623:  ij=1;
1.58    ! lievre   1624:  for (i=1; i<= maxncov; i++) {
1.53      brouard  1625:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.58    ! lievre   1626:      Tvaraff[ij]=i; /*For printing */
1.53      brouard  1627:      ij++;
                   1628:    }
                   1629:  }
                   1630:  
1.58    ! lievre   1631:  cptcoveff=ij-1; /*Number of simple covariates*/
1.53      brouard  1632: }
                   1633: 
                   1634: /*********** Health Expectancies ****************/
                   1635: 
                   1636: void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij, int estepm,double delti[],double **matcov )
                   1637: 
                   1638: {
                   1639:   /* Health expectancies */
                   1640:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;
                   1641:   double age, agelim, hf;
                   1642:   double ***p3mat,***varhe;
                   1643:   double **dnewm,**doldm;
                   1644:   double *xp;
                   1645:   double **gp, **gm;
                   1646:   double ***gradg, ***trgradg;
                   1647:   int theta;
                   1648: 
                   1649:   varhe=ma3x(1,nlstate*2,1,nlstate*2,(int) bage, (int) fage);
                   1650:   xp=vector(1,npar);
                   1651:   dnewm=matrix(1,nlstate*2,1,npar);
                   1652:   doldm=matrix(1,nlstate*2,1,nlstate*2);
                   1653:   
                   1654:   fprintf(ficreseij,"# Health expectancies\n");
                   1655:   fprintf(ficreseij,"# Age");
                   1656:   for(i=1; i<=nlstate;i++)
                   1657:     for(j=1; j<=nlstate;j++)
                   1658:       fprintf(ficreseij," %1d-%1d (SE)",i,j);
                   1659:   fprintf(ficreseij,"\n");
                   1660: 
                   1661:   if(estepm < stepm){
                   1662:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   1663:   }
                   1664:   else  hstepm=estepm;   
                   1665:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   1666:    * This is mainly to measure the difference between two models: for example
                   1667:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   1668:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   1669:    * progression inbetween and thus overestimating or underestimating according
                   1670:    * to the curvature of the survival function. If, for the same date, we 
                   1671:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   1672:    * to compare the new estimate of Life expectancy with the same linear 
                   1673:    * hypothesis. A more precise result, taking into account a more precise
                   1674:    * curvature will be obtained if estepm is as small as stepm. */
                   1675: 
                   1676:   /* For example we decided to compute the life expectancy with the smallest unit */
                   1677:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   1678:      nhstepm is the number of hstepm from age to agelim 
                   1679:      nstepm is the number of stepm from age to agelin. 
                   1680:      Look at hpijx to understand the reason of that which relies in memory size
                   1681:      and note for a fixed period like estepm months */
                   1682:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   1683:      survival function given by stepm (the optimization length). Unfortunately it
                   1684:      means that if the survival funtion is printed only each two years of age and if
                   1685:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   1686:      results. So we changed our mind and took the option of the best precision.
                   1687:   */
                   1688:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   1689: 
                   1690:   agelim=AGESUP;
                   1691:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   1692:     /* nhstepm age range expressed in number of stepm */
                   1693:     nstepm=(int) rint((agelim-age)*YEARM/stepm); 
                   1694:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   1695:     /* if (stepm >= YEARM) hstepm=1;*/
                   1696:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   1697:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1698:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*2);
                   1699:     gp=matrix(0,nhstepm,1,nlstate*2);
                   1700:     gm=matrix(0,nhstepm,1,nlstate*2);
                   1701: 
                   1702:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   1703:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   1704:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);  
                   1705:  
                   1706: 
                   1707:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   1708: 
                   1709:     /* Computing Variances of health expectancies */
                   1710: 
                   1711:      for(theta=1; theta <=npar; theta++){
                   1712:       for(i=1; i<=npar; i++){ 
                   1713:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   1714:       }
                   1715:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   1716:   
                   1717:       cptj=0;
                   1718:       for(j=1; j<= nlstate; j++){
                   1719:        for(i=1; i<=nlstate; i++){
                   1720:          cptj=cptj+1;
                   1721:          for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){
                   1722:            gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;
                   1723:          }
                   1724:        }
                   1725:       }
                   1726:      
                   1727:      
                   1728:       for(i=1; i<=npar; i++) 
                   1729:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   1730:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   1731:       
                   1732:       cptj=0;
                   1733:       for(j=1; j<= nlstate; j++){
                   1734:        for(i=1;i<=nlstate;i++){
                   1735:          cptj=cptj+1;
                   1736:          for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){
                   1737:            gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;
                   1738:          }
                   1739:        }
                   1740:       }
                   1741:       for(j=1; j<= nlstate*2; j++)
                   1742:        for(h=0; h<=nhstepm-1; h++){
                   1743:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   1744:        }
                   1745:      } 
                   1746:    
                   1747: /* End theta */
                   1748: 
                   1749:      trgradg =ma3x(0,nhstepm,1,nlstate*2,1,npar);
                   1750: 
                   1751:      for(h=0; h<=nhstepm-1; h++)
                   1752:       for(j=1; j<=nlstate*2;j++)
                   1753:        for(theta=1; theta <=npar; theta++)
                   1754:          trgradg[h][j][theta]=gradg[h][theta][j];
                   1755:      
                   1756: 
                   1757:      for(i=1;i<=nlstate*2;i++)
                   1758:       for(j=1;j<=nlstate*2;j++)
                   1759:        varhe[i][j][(int)age] =0.;
                   1760: 
                   1761:      printf("%d|",(int)age);fflush(stdout);
                   1762:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   1763:      for(h=0;h<=nhstepm-1;h++){
                   1764:       for(k=0;k<=nhstepm-1;k++){
                   1765:        matprod2(dnewm,trgradg[h],1,nlstate*2,1,npar,1,npar,matcov);
                   1766:        matprod2(doldm,dnewm,1,nlstate*2,1,npar,1,nlstate*2,gradg[k]);
                   1767:        for(i=1;i<=nlstate*2;i++)
                   1768:          for(j=1;j<=nlstate*2;j++)
                   1769:            varhe[i][j][(int)age] += doldm[i][j]*hf*hf;
                   1770:       }
                   1771:     }
                   1772:     /* Computing expectancies */
                   1773:     for(i=1; i<=nlstate;i++)
                   1774:       for(j=1; j<=nlstate;j++)
                   1775:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   1776:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   1777:          
                   1778: /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
                   1779: 
                   1780:        }
                   1781: 
                   1782:     fprintf(ficreseij,"%3.0f",age );
                   1783:     cptj=0;
                   1784:     for(i=1; i<=nlstate;i++)
                   1785:       for(j=1; j<=nlstate;j++){
                   1786:        cptj++;
                   1787:        fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );
                   1788:       }
                   1789:     fprintf(ficreseij,"\n");
                   1790:    
                   1791:     free_matrix(gm,0,nhstepm,1,nlstate*2);
                   1792:     free_matrix(gp,0,nhstepm,1,nlstate*2);
                   1793:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*2);
                   1794:     free_ma3x(trgradg,0,nhstepm,1,nlstate*2,1,npar);
                   1795:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1796:   }
                   1797:   printf("\n");
                   1798:   fprintf(ficlog,"\n");
                   1799: 
                   1800:   free_vector(xp,1,npar);
                   1801:   free_matrix(dnewm,1,nlstate*2,1,npar);
                   1802:   free_matrix(doldm,1,nlstate*2,1,nlstate*2);
                   1803:   free_ma3x(varhe,1,nlstate*2,1,nlstate*2,(int) bage, (int)fage);
                   1804: }
                   1805: 
                   1806: /************ Variance ******************/
                   1807: void varevsij(char optionfilefiname[], 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, int estepm, int cptcov, int cptcod, int popbased, int mobilav)
                   1808: {
                   1809:   /* Variance of health expectancies */
                   1810:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   1811:   /* double **newm;*/
                   1812:   double **dnewm,**doldm;
                   1813:   double **dnewmp,**doldmp;
                   1814:   int i, j, nhstepm, hstepm, h, nstepm ;
                   1815:   int k, cptcode;
                   1816:   double *xp;
                   1817:   double **gp, **gm;  /* for var eij */
                   1818:   double ***gradg, ***trgradg; /*for var eij */
                   1819:   double **gradgp, **trgradgp; /* for var p point j */
                   1820:   double *gpp, *gmp; /* for var p point j */
                   1821:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   1822:   double ***p3mat;
                   1823:   double age,agelim, hf;
                   1824:   double ***mobaverage;
                   1825:   int theta;
                   1826:   char digit[4];
1.55      lievre   1827:   char digitp[25];
1.53      brouard  1828: 
                   1829:   char fileresprobmorprev[FILENAMELENGTH];
                   1830: 
1.55      lievre   1831:   if(popbased==1){
1.58    ! lievre   1832:     if(mobilav!=0)
1.55      lievre   1833:       strcpy(digitp,"-populbased-mobilav-");
                   1834:     else strcpy(digitp,"-populbased-nomobil-");
                   1835:   }
                   1836:   else 
1.53      brouard  1837:     strcpy(digitp,"-stablbased-");
1.56      lievre   1838: 
1.54      brouard  1839:   if (mobilav!=0) {
1.53      brouard  1840:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.54      brouard  1841:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   1842:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   1843:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   1844:     }
1.53      brouard  1845:   }
                   1846: 
                   1847:   strcpy(fileresprobmorprev,"prmorprev"); 
                   1848:   sprintf(digit,"%-d",ij);
                   1849:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   1850:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   1851:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   1852:   strcat(fileresprobmorprev,fileres);
                   1853:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   1854:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   1855:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   1856:   }
                   1857:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   1858:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   1859:   fprintf(ficresprobmorprev,"# probabilities of dying during a year and weighted mean w1*p1j+w2*p2j+... stand dev in()\n");
                   1860:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   1861:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   1862:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   1863:     for(i=1; i<=nlstate;i++)
                   1864:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   1865:   }  
                   1866:   fprintf(ficresprobmorprev,"\n");
                   1867:   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) {
                   1868:     printf("Problem with gnuplot file: %s\n", optionfilegnuplot);
                   1869:     fprintf(ficlog,"Problem with gnuplot file: %s\n", optionfilegnuplot);
                   1870:     exit(0);
                   1871:   }
                   1872:   else{
                   1873:     fprintf(ficgp,"\n# Routine varevsij");
                   1874:   }
                   1875:   if((fichtm=fopen(optionfilehtm,"a"))==NULL) {
                   1876:     printf("Problem with html file: %s\n", optionfilehtm);
                   1877:     fprintf(ficlog,"Problem with html file: %s\n", optionfilehtm);
                   1878:     exit(0);
                   1879:   }
                   1880:   else{
                   1881:     fprintf(fichtm,"\n<li><h4> Computing probabilities of dying as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");
                   1882:     fprintf(fichtm,"\n<br>%s (à revoir) <br>\n",digitp);
                   1883:   }
                   1884:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   1885: 
                   1886:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are the stable prevalence in health states i\n");
                   1887:   fprintf(ficresvij,"# Age");
                   1888:   for(i=1; i<=nlstate;i++)
                   1889:     for(j=1; j<=nlstate;j++)
                   1890:       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);
                   1891:   fprintf(ficresvij,"\n");
                   1892: 
                   1893:   xp=vector(1,npar);
                   1894:   dnewm=matrix(1,nlstate,1,npar);
                   1895:   doldm=matrix(1,nlstate,1,nlstate);
                   1896:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   1897:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   1898: 
                   1899:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   1900:   gpp=vector(nlstate+1,nlstate+ndeath);
                   1901:   gmp=vector(nlstate+1,nlstate+ndeath);
                   1902:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   1903:   
                   1904:   if(estepm < stepm){
                   1905:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   1906:   }
                   1907:   else  hstepm=estepm;   
                   1908:   /* For example we decided to compute the life expectancy with the smallest unit */
                   1909:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   1910:      nhstepm is the number of hstepm from age to agelim 
                   1911:      nstepm is the number of stepm from age to agelin. 
                   1912:      Look at hpijx to understand the reason of that which relies in memory size
                   1913:      and note for a fixed period like k years */
                   1914:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   1915:      survival function given by stepm (the optimization length). Unfortunately it
                   1916:      means that if the survival funtion is printed only each two years of age and if
                   1917:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   1918:      results. So we changed our mind and took the option of the best precision.
                   1919:   */
                   1920:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   1921:   agelim = AGESUP;
                   1922:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   1923:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   1924:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   1925:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1926:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   1927:     gp=matrix(0,nhstepm,1,nlstate);
                   1928:     gm=matrix(0,nhstepm,1,nlstate);
                   1929: 
                   1930: 
                   1931:     for(theta=1; theta <=npar; theta++){
                   1932:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   1933:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   1934:       }
                   1935:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   1936:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   1937: 
                   1938:       if (popbased==1) {
1.54      brouard  1939:        if(mobilav ==0){
1.53      brouard  1940:          for(i=1; i<=nlstate;i++)
                   1941:            prlim[i][i]=probs[(int)age][i][ij];
1.54      brouard  1942:        }else{ /* mobilav */ 
1.53      brouard  1943:          for(i=1; i<=nlstate;i++)
                   1944:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   1945:        }
                   1946:       }
                   1947:   
                   1948:       for(j=1; j<= nlstate; j++){
                   1949:        for(h=0; h<=nhstepm; h++){
                   1950:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   1951:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   1952:        }
                   1953:       }
                   1954:       /* This for computing forces of mortality (h=1)as a weighted average */
                   1955:       for(j=nlstate+1,gpp[j]=0.;j<=nlstate+ndeath;j++){
                   1956:        for(i=1; i<= nlstate; i++)
                   1957:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   1958:       }    
                   1959:       /* end force of mortality */
                   1960: 
                   1961:       for(i=1; i<=npar; i++) /* Computes gradient */
                   1962:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   1963:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   1964:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   1965:  
                   1966:       if (popbased==1) {
1.54      brouard  1967:        if(mobilav ==0){
1.53      brouard  1968:          for(i=1; i<=nlstate;i++)
                   1969:            prlim[i][i]=probs[(int)age][i][ij];
1.54      brouard  1970:        }else{ /* mobilav */ 
1.53      brouard  1971:          for(i=1; i<=nlstate;i++)
                   1972:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   1973:        }
                   1974:       }
                   1975: 
                   1976:       for(j=1; j<= nlstate; j++){
                   1977:        for(h=0; h<=nhstepm; h++){
                   1978:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   1979:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   1980:        }
                   1981:       }
                   1982:       /* This for computing force of mortality (h=1)as a weighted average */
                   1983:       for(j=nlstate+1,gmp[j]=0.;j<=nlstate+ndeath;j++){
                   1984:        for(i=1; i<= nlstate; i++)
                   1985:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   1986:       }    
                   1987:       /* end force of mortality */
                   1988: 
                   1989:       for(j=1; j<= nlstate; j++) /* vareij */
                   1990:        for(h=0; h<=nhstepm; h++){
                   1991:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   1992:        }
                   1993:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   1994:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   1995:       }
                   1996: 
                   1997:     } /* End theta */
                   1998: 
                   1999:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   2000: 
                   2001:     for(h=0; h<=nhstepm; h++) /* veij */
                   2002:       for(j=1; j<=nlstate;j++)
                   2003:        for(theta=1; theta <=npar; theta++)
                   2004:          trgradg[h][j][theta]=gradg[h][theta][j];
                   2005: 
                   2006:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   2007:       for(theta=1; theta <=npar; theta++)
                   2008:        trgradgp[j][theta]=gradgp[theta][j];
                   2009: 
                   2010:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   2011:     for(i=1;i<=nlstate;i++)
                   2012:       for(j=1;j<=nlstate;j++)
                   2013:        vareij[i][j][(int)age] =0.;
                   2014: 
                   2015:     for(h=0;h<=nhstepm;h++){
                   2016:       for(k=0;k<=nhstepm;k++){
                   2017:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   2018:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   2019:        for(i=1;i<=nlstate;i++)
                   2020:          for(j=1;j<=nlstate;j++)
                   2021:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   2022:       }
                   2023:     }
                   2024: 
                   2025:     /* pptj */
                   2026:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   2027:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   2028:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   2029:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   2030:        varppt[j][i]=doldmp[j][i];
                   2031:     /* end ppptj */
                   2032:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   2033:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   2034:  
                   2035:     if (popbased==1) {
1.54      brouard  2036:       if(mobilav ==0){
1.53      brouard  2037:        for(i=1; i<=nlstate;i++)
                   2038:          prlim[i][i]=probs[(int)age][i][ij];
1.54      brouard  2039:       }else{ /* mobilav */ 
1.53      brouard  2040:        for(i=1; i<=nlstate;i++)
                   2041:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   2042:       }
                   2043:     }
                   2044:     
                   2045:     /* This for computing force of mortality (h=1)as a weighted average */
                   2046:     for(j=nlstate+1,gmp[j]=0.;j<=nlstate+ndeath;j++){
                   2047:       for(i=1; i<= nlstate; i++)
                   2048:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   2049:     }    
                   2050:     /* end force of mortality */
                   2051: 
                   2052:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   2053:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   2054:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   2055:       for(i=1; i<=nlstate;i++){
                   2056:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   2057:       }
                   2058:     } 
                   2059:     fprintf(ficresprobmorprev,"\n");
                   2060: 
                   2061:     fprintf(ficresvij,"%.0f ",age );
                   2062:     for(i=1; i<=nlstate;i++)
                   2063:       for(j=1; j<=nlstate;j++){
                   2064:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   2065:       }
                   2066:     fprintf(ficresvij,"\n");
                   2067:     free_matrix(gp,0,nhstepm,1,nlstate);
                   2068:     free_matrix(gm,0,nhstepm,1,nlstate);
                   2069:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   2070:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   2071:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2072:   } /* End age */
                   2073:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   2074:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   2075:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   2076:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   2077:   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
                   2078:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   2079:   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   2080:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm);
                   2081:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm);
                   2082:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm);
                   2083:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",fileresprobmorprev,fileresprobmorprev);
                   2084:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,digitp,digit);
                   2085:   /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);
                   2086: */
                   2087:   fprintf(ficgp,"\nset out \"varmuptjgr%s%s.png\";replot;",digitp,digit);
                   2088: 
                   2089:   free_vector(xp,1,npar);
                   2090:   free_matrix(doldm,1,nlstate,1,nlstate);
                   2091:   free_matrix(dnewm,1,nlstate,1,npar);
                   2092:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   2093:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   2094:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
1.55      lievre   2095:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.53      brouard  2096:   fclose(ficresprobmorprev);
                   2097:   fclose(ficgp);
                   2098:   fclose(fichtm);
                   2099: }
                   2100: 
                   2101: /************ Variance of prevlim ******************/
                   2102: 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)
                   2103: {
                   2104:   /* Variance of prevalence limit */
                   2105:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   2106:   double **newm;
                   2107:   double **dnewm,**doldm;
                   2108:   int i, j, nhstepm, hstepm;
                   2109:   int k, cptcode;
                   2110:   double *xp;
                   2111:   double *gp, *gm;
                   2112:   double **gradg, **trgradg;
                   2113:   double age,agelim;
                   2114:   int theta;
                   2115:    
1.54      brouard  2116:   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");
1.53      brouard  2117:   fprintf(ficresvpl,"# Age");
                   2118:   for(i=1; i<=nlstate;i++)
                   2119:       fprintf(ficresvpl," %1d-%1d",i,i);
                   2120:   fprintf(ficresvpl,"\n");
                   2121: 
                   2122:   xp=vector(1,npar);
                   2123:   dnewm=matrix(1,nlstate,1,npar);
                   2124:   doldm=matrix(1,nlstate,1,nlstate);
                   2125:   
                   2126:   hstepm=1*YEARM; /* Every year of age */
                   2127:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   2128:   agelim = AGESUP;
                   2129:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   2130:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   2131:     if (stepm >= YEARM) hstepm=1;
                   2132:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   2133:     gradg=matrix(1,npar,1,nlstate);
                   2134:     gp=vector(1,nlstate);
                   2135:     gm=vector(1,nlstate);
                   2136: 
                   2137:     for(theta=1; theta <=npar; theta++){
                   2138:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   2139:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   2140:       }
                   2141:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   2142:       for(i=1;i<=nlstate;i++)
                   2143:        gp[i] = prlim[i][i];
                   2144:     
                   2145:       for(i=1; i<=npar; i++) /* Computes gradient */
                   2146:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   2147:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   2148:       for(i=1;i<=nlstate;i++)
                   2149:        gm[i] = prlim[i][i];
                   2150: 
                   2151:       for(i=1;i<=nlstate;i++)
                   2152:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   2153:     } /* End theta */
                   2154: 
                   2155:     trgradg =matrix(1,nlstate,1,npar);
                   2156: 
                   2157:     for(j=1; j<=nlstate;j++)
                   2158:       for(theta=1; theta <=npar; theta++)
                   2159:        trgradg[j][theta]=gradg[theta][j];
                   2160: 
                   2161:     for(i=1;i<=nlstate;i++)
                   2162:       varpl[i][(int)age] =0.;
                   2163:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   2164:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   2165:     for(i=1;i<=nlstate;i++)
                   2166:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   2167: 
                   2168:     fprintf(ficresvpl,"%.0f ",age );
                   2169:     for(i=1; i<=nlstate;i++)
                   2170:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   2171:     fprintf(ficresvpl,"\n");
                   2172:     free_vector(gp,1,nlstate);
                   2173:     free_vector(gm,1,nlstate);
                   2174:     free_matrix(gradg,1,npar,1,nlstate);
                   2175:     free_matrix(trgradg,1,nlstate,1,npar);
                   2176:   } /* End age */
                   2177: 
                   2178:   free_vector(xp,1,npar);
                   2179:   free_matrix(doldm,1,nlstate,1,npar);
                   2180:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   2181: 
                   2182: }
                   2183: 
                   2184: /************ Variance of one-step probabilities  ******************/
                   2185: void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax)
                   2186: {
                   2187:   int i, j=0,  i1, k1, l1, t, tj;
                   2188:   int k2, l2, j1,  z1;
                   2189:   int k=0,l, cptcode;
                   2190:   int first=1, first1;
                   2191:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   2192:   double **dnewm,**doldm;
                   2193:   double *xp;
                   2194:   double *gp, *gm;
                   2195:   double **gradg, **trgradg;
                   2196:   double **mu;
                   2197:   double age,agelim, cov[NCOVMAX];
                   2198:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   2199:   int theta;
                   2200:   char fileresprob[FILENAMELENGTH];
                   2201:   char fileresprobcov[FILENAMELENGTH];
                   2202:   char fileresprobcor[FILENAMELENGTH];
                   2203: 
                   2204:   double ***varpij;
                   2205: 
                   2206:   strcpy(fileresprob,"prob"); 
                   2207:   strcat(fileresprob,fileres);
                   2208:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   2209:     printf("Problem with resultfile: %s\n", fileresprob);
                   2210:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   2211:   }
                   2212:   strcpy(fileresprobcov,"probcov"); 
                   2213:   strcat(fileresprobcov,fileres);
                   2214:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   2215:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   2216:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   2217:   }
                   2218:   strcpy(fileresprobcor,"probcor"); 
                   2219:   strcat(fileresprobcor,fileres);
                   2220:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   2221:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   2222:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   2223:   }
                   2224:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   2225:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   2226:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   2227:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   2228:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   2229:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   2230:   
                   2231:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   2232:   fprintf(ficresprob,"# Age");
                   2233:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   2234:   fprintf(ficresprobcov,"# Age");
                   2235:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   2236:   fprintf(ficresprobcov,"# Age");
                   2237: 
                   2238: 
                   2239:   for(i=1; i<=nlstate;i++)
                   2240:     for(j=1; j<=(nlstate+ndeath);j++){
                   2241:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   2242:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   2243:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   2244:     }  
                   2245:   fprintf(ficresprob,"\n");
                   2246:   fprintf(ficresprobcov,"\n");
                   2247:   fprintf(ficresprobcor,"\n");
                   2248:   xp=vector(1,npar);
                   2249:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   2250:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   2251:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   2252:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   2253:   first=1;
                   2254:   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) {
                   2255:     printf("Problem with gnuplot file: %s\n", optionfilegnuplot);
                   2256:     fprintf(ficlog,"Problem with gnuplot file: %s\n", optionfilegnuplot);
                   2257:     exit(0);
                   2258:   }
                   2259:   else{
                   2260:     fprintf(ficgp,"\n# Routine varprob");
                   2261:   }
                   2262:   if((fichtm=fopen(optionfilehtm,"a"))==NULL) {
                   2263:     printf("Problem with html file: %s\n", optionfilehtm);
                   2264:     fprintf(ficlog,"Problem with html file: %s\n", optionfilehtm);
                   2265:     exit(0);
                   2266:   }
                   2267:   else{
                   2268:     fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   2269:     fprintf(fichtm,"\n");
                   2270: 
                   2271:     fprintf(fichtm,"\n<li><h4> Computing matrix of variance-covariance of step probabilities</h4></li>\n");
                   2272:     fprintf(fichtm,"\nWe have drawn ellipsoids of confidence around the p<inf>ij</inf>, p<inf>kl</inf> to understand the covariance between two incidences. They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   2273:     fprintf(fichtm,"\n<br> We have drawn x'cov<sup>-1</sup>x = 4 where x is the column vector (pij,pkl). It means that if pij and pkl where uncorrelated the (2X2) matrix would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 standard deviations wide on each axis. <br> When both incidences are correlated we diagonalised the inverse of the covariance matrix and made the appropriate rotation.<br> \n");
                   2274: 
                   2275:   }
                   2276: 
                   2277:  
                   2278:   cov[1]=1;
                   2279:   tj=cptcoveff;
                   2280:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   2281:   j1=0;
                   2282:   for(t=1; t<=tj;t++){
                   2283:     for(i1=1; i1<=ncodemax[t];i1++){ 
                   2284:       j1++;
                   2285:       
                   2286:       if  (cptcovn>0) {
                   2287:        fprintf(ficresprob, "\n#********** Variable "); 
                   2288:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2289:        fprintf(ficresprob, "**********\n#");
                   2290:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   2291:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2292:        fprintf(ficresprobcov, "**********\n#");
                   2293:        
                   2294:        fprintf(ficgp, "\n#********** Variable "); 
                   2295:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, "# V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2296:        fprintf(ficgp, "**********\n#");
                   2297:        
                   2298:        
                   2299:        fprintf(fichtm, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   2300:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2301:        fprintf(fichtm, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   2302:        
                   2303:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   2304:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2305:        fprintf(ficgp, "**********\n#");    
                   2306:       }
                   2307:       
                   2308:       for (age=bage; age<=fage; age ++){ 
                   2309:        cov[2]=age;
                   2310:        for (k=1; k<=cptcovn;k++) {
                   2311:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
                   2312:        }
                   2313:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   2314:        for (k=1; k<=cptcovprod;k++)
                   2315:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   2316:        
                   2317:        gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   2318:        trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   2319:        gp=vector(1,(nlstate)*(nlstate+ndeath));
                   2320:        gm=vector(1,(nlstate)*(nlstate+ndeath));
                   2321:     
                   2322:        for(theta=1; theta <=npar; theta++){
                   2323:          for(i=1; i<=npar; i++)
                   2324:            xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   2325:          
                   2326:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   2327:          
                   2328:          k=0;
                   2329:          for(i=1; i<= (nlstate); i++){
                   2330:            for(j=1; j<=(nlstate+ndeath);j++){
                   2331:              k=k+1;
                   2332:              gp[k]=pmmij[i][j];
                   2333:            }
                   2334:          }
                   2335:          
                   2336:          for(i=1; i<=npar; i++)
                   2337:            xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   2338:     
                   2339:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   2340:          k=0;
                   2341:          for(i=1; i<=(nlstate); i++){
                   2342:            for(j=1; j<=(nlstate+ndeath);j++){
                   2343:              k=k+1;
                   2344:              gm[k]=pmmij[i][j];
                   2345:            }
                   2346:          }
                   2347:      
                   2348:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   2349:            gradg[theta][i]=(gp[i]-gm[i])/2./delti[theta];  
                   2350:        }
                   2351: 
                   2352:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   2353:          for(theta=1; theta <=npar; theta++)
                   2354:            trgradg[j][theta]=gradg[theta][j];
                   2355:        
                   2356:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   2357:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   2358:        
                   2359:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2360:        
                   2361:        k=0;
                   2362:        for(i=1; i<=(nlstate); i++){
                   2363:          for(j=1; j<=(nlstate+ndeath);j++){
                   2364:            k=k+1;
                   2365:            mu[k][(int) age]=pmmij[i][j];
                   2366:          }
                   2367:        }
                   2368:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   2369:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   2370:            varpij[i][j][(int)age] = doldm[i][j];
                   2371: 
                   2372:        /*printf("\n%d ",(int)age);
                   2373:      for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   2374:        printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   2375:        fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   2376:      }*/
                   2377: 
                   2378:        fprintf(ficresprob,"\n%d ",(int)age);
                   2379:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   2380:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   2381: 
                   2382:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   2383:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   2384:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   2385:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   2386:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   2387:        }
                   2388:        i=0;
                   2389:        for (k=1; k<=(nlstate);k++){
                   2390:          for (l=1; l<=(nlstate+ndeath);l++){ 
                   2391:            i=i++;
                   2392:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   2393:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   2394:            for (j=1; j<=i;j++){
                   2395:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   2396:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   2397:            }
                   2398:          }
                   2399:        }/* end of loop for state */
                   2400:       } /* end of loop for age */
                   2401: 
                   2402:       /* Confidence intervalle of pij  */
                   2403:       /*
                   2404:       fprintf(ficgp,"\nset noparametric;unset label");
                   2405:       fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   2406:       fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   2407:       fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);
                   2408:       fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   2409:       fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   2410:       fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   2411:       */
                   2412: 
                   2413:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   2414:       first1=1;
                   2415:       for (k2=1; k2<=(nlstate);k2++){
                   2416:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   2417:          if(l2==k2) continue;
                   2418:          j=(k2-1)*(nlstate+ndeath)+l2;
                   2419:          for (k1=1; k1<=(nlstate);k1++){
                   2420:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   2421:              if(l1==k1) continue;
                   2422:              i=(k1-1)*(nlstate+ndeath)+l1;
                   2423:              if(i<=j) continue;
                   2424:              for (age=bage; age<=fage; age ++){ 
                   2425:                if ((int)age %5==0){
                   2426:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   2427:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   2428:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   2429:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   2430:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   2431:                  c12=cv12/sqrt(v1*v2);
                   2432:                  /* Computing eigen value of matrix of covariance */
                   2433:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   2434:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   2435:                  /* Eigen vectors */
                   2436:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   2437:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   2438:                  v21=(lc1-v1)/cv12*v11;
                   2439:                  v12=-v21;
                   2440:                  v22=v11;
                   2441:                  tnalp=v21/v11;
                   2442:                  if(first1==1){
                   2443:                    first1=0;
                   2444:                    printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
                   2445:                  }
                   2446:                  fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
                   2447:                  /*printf(fignu*/
                   2448:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   2449:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   2450:                  if(first==1){
                   2451:                    first=0;
                   2452:                    fprintf(ficgp,"\nset parametric;unset label");
                   2453:                    fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);
                   2454:                    fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   2455:                    fprintf(fichtm,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup> :<a href=\"varpijgr%s%d%1d%1d-%1d%1d.png\">varpijgr%s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,optionfilefiname, j1,k1,l1,k2,l2,optionfilefiname, j1,k1,l1,k2,l2);
                   2456:                    fprintf(fichtm,"\n<br><img src=\"varpijgr%s%d%1d%1d-%1d%1d.png\"> ",optionfilefiname, j1,k1,l1,k2,l2);
                   2457:                    fprintf(fichtm,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   2458:                    fprintf(ficgp,"\nset out \"varpijgr%s%d%1d%1d-%1d%1d.png\"",optionfilefiname, j1,k1,l1,k2,l2);
                   2459:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   2460:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   2461:                    fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
                   2462:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   2463:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   2464:                  }else{
                   2465:                    first=0;
                   2466:                    fprintf(fichtm," %d (%.3f),",(int) age, c12);
                   2467:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   2468:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   2469:                    fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
                   2470:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   2471:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   2472:                  }/* if first */
                   2473:                } /* age mod 5 */
                   2474:              } /* end loop age */
                   2475:              fprintf(ficgp,"\nset out \"varpijgr%s%d%1d%1d-%1d%1d.png\";replot;",optionfilefiname, j1,k1,l1,k2,l2);
                   2476:              first=1;
                   2477:            } /*l12 */
                   2478:          } /* k12 */
                   2479:        } /*l1 */
                   2480:       }/* k1 */
                   2481:     } /* loop covariates */
                   2482:     free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   2483:     free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   2484:     free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   2485:     free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   2486:     free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   2487:     free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   2488:   }
                   2489:   free_vector(xp,1,npar);
                   2490:   fclose(ficresprob);
                   2491:   fclose(ficresprobcov);
                   2492:   fclose(ficresprobcor);
                   2493:   fclose(ficgp);
                   2494:   fclose(fichtm);
                   2495: }
                   2496: 
                   2497: 
                   2498: /******************* Printing html file ***********/
                   2499: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   2500:                  int lastpass, int stepm, int weightopt, char model[],\
                   2501:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   2502:                  int popforecast, int estepm ,\
                   2503:                  double jprev1, double mprev1,double anprev1, \
                   2504:                  double jprev2, double mprev2,double anprev2){
                   2505:   int jj1, k1, i1, cpt;
                   2506:   /*char optionfilehtm[FILENAMELENGTH];*/
                   2507:   if((fichtm=fopen(optionfilehtm,"a"))==NULL)    {
                   2508:     printf("Problem with %s \n",optionfilehtm), exit(0);
                   2509:     fprintf(ficlog,"Problem with %s \n",optionfilehtm), exit(0);
                   2510:   }
                   2511: 
                   2512:    fprintf(fichtm,"<ul><li><h4>Result files (first order: no variance)</h4>\n
                   2513:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"p%s\">p%s</a> <br>\n
                   2514:  - Estimated transition probabilities over %d (stepm) months: <a href=\"pij%s\">pij%s</a><br>\n
                   2515:  - Stable prevalence in each health state: <a href=\"pl%s\">pl%s</a> <br>\n
                   2516:  - Life expectancies by age and initial health status (estepm=%2d months): 
                   2517:    <a href=\"e%s\">e%s</a> <br>\n</li>", \
                   2518:   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,fileres,fileres,stepm,fileres,fileres,fileres,fileres,estepm,fileres,fileres);
                   2519: 
                   2520: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   2521: 
                   2522:  m=cptcoveff;
                   2523:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   2524: 
                   2525:  jj1=0;
                   2526:  for(k1=1; k1<=m;k1++){
                   2527:    for(i1=1; i1<=ncodemax[k1];i1++){
                   2528:      jj1++;
                   2529:      if (cptcovn > 0) {
                   2530:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   2531:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   2532:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   2533:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   2534:      }
                   2535:      /* Pij */
                   2536:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months before: pe%s%d1.png<br>
                   2537: <img src=\"pe%s%d1.png\">",stepm,strtok(optionfile, "."),jj1,strtok(optionfile, "."),jj1);     
                   2538:      /* Quasi-incidences */
                   2539:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: pe%s%d2.png<br>
                   2540: <img src=\"pe%s%d2.png\">",stepm,strtok(optionfile, "."),jj1,strtok(optionfile, "."),jj1); 
                   2541:        /* Stable prevalence in each health state */
                   2542:        for(cpt=1; cpt<nlstate;cpt++){
                   2543:         fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br>
                   2544: <img src=\"p%s%d%d.png\">",strtok(optionfile, "."),cpt,jj1,strtok(optionfile, "."),cpt,jj1);
                   2545:        }
                   2546:      for(cpt=1; cpt<=nlstate;cpt++) {
                   2547:         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): exp%s%d%d.png <br>
                   2548: <img src=\"exp%s%d%d.png\">",cpt,strtok(optionfile, "."),cpt,jj1,strtok(optionfile, "."),cpt,jj1);
                   2549:      }
                   2550:      fprintf(fichtm,"\n<br>- Total life expectancy by age and
                   2551: health expectancies in states (1) and (2): e%s%d.png<br>
                   2552: <img src=\"e%s%d.png\">",strtok(optionfile, "."),jj1,strtok(optionfile, "."),jj1);
                   2553:    } /* end i1 */
                   2554:  }/* End k1 */
                   2555:  fprintf(fichtm,"</ul>");
                   2556: 
                   2557: 
                   2558:  fprintf(fichtm,"\n<br><li><h4> Result files (second order: variances)</h4>\n
                   2559:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n
                   2560:  - Variance of one-step probabilities: <a href=\"prob%s\">prob%s</a> <br>\n
                   2561:  - Variance-covariance of one-step probabilities: <a href=\"probcov%s\">probcov%s</a> <br>\n
                   2562:  - Correlation matrix of one-step probabilities: <a href=\"probcor%s\">probcor%s</a> <br>\n
                   2563:  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"v%s\">v%s</a><br>\n 
                   2564:  - Health expectancies with their variances (no covariance): <a href=\"t%s\">t%s</a> <br>\n
                   2565:  - Standard deviation of stable prevalences: <a href=\"vpl%s\">vpl%s</a> <br>\n",rfileres,rfileres,fileres,fileres,fileres,fileres,fileres,fileres, estepm, fileres,fileres,fileres,fileres,fileres,fileres);
                   2566: 
                   2567:  if(popforecast==1) fprintf(fichtm,"\n
                   2568:  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n
                   2569:  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n
                   2570:        <br>",fileres,fileres,fileres,fileres);
                   2571:  else 
                   2572:    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model);
                   2573: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   2574: 
                   2575:  m=cptcoveff;
                   2576:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   2577: 
                   2578:  jj1=0;
                   2579:  for(k1=1; k1<=m;k1++){
                   2580:    for(i1=1; i1<=ncodemax[k1];i1++){
                   2581:      jj1++;
                   2582:      if (cptcovn > 0) {
                   2583:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   2584:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   2585:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   2586:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   2587:      }
                   2588:      for(cpt=1; cpt<=nlstate;cpt++) {
                   2589:        fprintf(fichtm,"<br>- Observed and stationary prevalence (with confident
                   2590: interval) in state (%d): v%s%d%d.png <br>
                   2591: <img src=\"v%s%d%d.png\">",cpt,strtok(optionfile, "."),cpt,jj1,strtok(optionfile, "."),cpt,jj1);  
                   2592:      }
                   2593:    } /* end i1 */
                   2594:  }/* End k1 */
                   2595:  fprintf(fichtm,"</ul>");
                   2596: fclose(fichtm);
                   2597: }
                   2598: 
                   2599: /******************* Gnuplot file **************/
                   2600: void printinggnuplot(char fileres[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   2601: 
                   2602:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
                   2603:   int ng;
                   2604:   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) {
                   2605:     printf("Problem with file %s",optionfilegnuplot);
                   2606:     fprintf(ficlog,"Problem with file %s",optionfilegnuplot);
                   2607:   }
                   2608: 
1.54      brouard  2609:   /*#ifdef windows */
1.53      brouard  2610:     fprintf(ficgp,"cd \"%s\" \n",pathc);
1.54      brouard  2611:     /*#endif */
1.53      brouard  2612: m=pow(2,cptcoveff);
                   2613:   
                   2614:  /* 1eme*/
                   2615:   for (cpt=1; cpt<= nlstate ; cpt ++) {
                   2616:    for (k1=1; k1<= m ; k1 ++) {
                   2617:      fprintf(ficgp,"\nset out \"v%s%d%d.png\" \n",strtok(optionfile, "."),cpt,k1);
                   2618:      fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] \"vpl%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,fileres,k1-1,k1-1);
                   2619: 
                   2620:      for (i=1; i<= nlstate ; i ++) {
                   2621:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   2622:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2623:      }
1.54      brouard  2624:      fprintf(ficgp,"\" t\"Stable prevalence\" w l 0,\"vpl%s\" every :::%d::%d u 1:($2+2*$3) \"\%%lf",fileres,k1-1,k1-1);
1.53      brouard  2625:      for (i=1; i<= nlstate ; i ++) {
                   2626:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   2627:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2628:      } 
                   2629:      fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"vpl%s\" every :::%d::%d u 1:($2-2*$3) \"\%%lf",fileres,k1-1,k1-1); 
                   2630:      for (i=1; i<= nlstate ; i ++) {
                   2631:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   2632:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2633:      }  
                   2634:      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));
                   2635:    }
                   2636:   }
                   2637:   /*2 eme*/
                   2638:   
                   2639:   for (k1=1; k1<= m ; k1 ++) { 
                   2640:     fprintf(ficgp,"\nset out \"e%s%d.png\" \n",strtok(optionfile, "."),k1);
                   2641:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
                   2642:     
                   2643:     for (i=1; i<= nlstate+1 ; i ++) {
                   2644:       k=2*i;
                   2645:       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:2 \"\%%lf",fileres,k1-1,k1-1);
                   2646:       for (j=1; j<= nlstate+1 ; j ++) {
                   2647:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   2648:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2649:       }   
                   2650:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   2651:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
                   2652:       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",fileres,k1-1,k1-1);
                   2653:       for (j=1; j<= nlstate+1 ; j ++) {
                   2654:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   2655:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2656:       }   
                   2657:       fprintf(ficgp,"\" t\"\" w l 0,");
                   2658:       fprintf(ficgp,"\"t%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",fileres,k1-1,k1-1);
                   2659:       for (j=1; j<= nlstate+1 ; j ++) {
                   2660:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   2661:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   2662:       }   
                   2663:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
                   2664:       else fprintf(ficgp,"\" t\"\" w l 0,");
                   2665:     }
                   2666:   }
                   2667:   
                   2668:   /*3eme*/
                   2669:   
                   2670:   for (k1=1; k1<= m ; k1 ++) { 
                   2671:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   2672:       k=2+nlstate*(2*cpt-2);
                   2673:       fprintf(ficgp,"\nset out \"exp%s%d%d.png\" \n",strtok(optionfile, "."),cpt,k1);
                   2674:       fprintf(ficgp,"set ter png small\nset size 0.65,0.65\nplot [%.f:%.f] \"e%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,fileres,k1-1,k1-1,k,cpt);
                   2675:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   2676:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   2677:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   2678:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   2679:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   2680:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   2681:        
                   2682:       */
                   2683:       for (i=1; i< nlstate ; i ++) {
                   2684:        fprintf(ficgp," ,\"e%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",fileres,k1-1,k1-1,k+2*i,cpt,i+1);
                   2685:        
                   2686:       } 
                   2687:     }
                   2688:   }
                   2689:   
                   2690:   /* CV preval stat */
                   2691:   for (k1=1; k1<= m ; k1 ++) { 
                   2692:     for (cpt=1; cpt<nlstate ; cpt ++) {
                   2693:       k=3;
                   2694:       fprintf(ficgp,"\nset out \"p%s%d%d.png\" \n",strtok(optionfile, "."),cpt,k1);
                   2695:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] \"pij%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,fileres,k1,k+cpt+1,k+1);
                   2696:       
                   2697:       for (i=1; i< nlstate ; i ++)
                   2698:        fprintf(ficgp,"+$%d",k+i+1);
                   2699:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
                   2700:       
                   2701:       l=3+(nlstate+ndeath)*cpt;
                   2702:       fprintf(ficgp,",\"pij%s\" u ($1==%d ? ($3):1/0):($%d/($%d",fileres,k1,l+cpt+1,l+1);
                   2703:       for (i=1; i< nlstate ; i ++) {
                   2704:        l=3+(nlstate+ndeath)*cpt;
                   2705:        fprintf(ficgp,"+$%d",l+i+1);
                   2706:       }
                   2707:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
                   2708:     } 
                   2709:   }  
                   2710:   
                   2711:   /* proba elementaires */
                   2712:   for(i=1,jk=1; i <=nlstate; i++){
                   2713:     for(k=1; k <=(nlstate+ndeath); k++){
                   2714:       if (k != i) {
                   2715:        for(j=1; j <=ncovmodel; j++){
                   2716:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   2717:          jk++; 
                   2718:          fprintf(ficgp,"\n");
                   2719:        }
                   2720:       }
                   2721:     }
                   2722:    }
                   2723: 
                   2724:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   2725:      for(jk=1; jk <=m; jk++) {
                   2726:        fprintf(ficgp,"\nset out \"pe%s%d%d.png\" \n",strtok(optionfile, "."),jk,ng); 
                   2727:        if (ng==2)
                   2728:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   2729:        else
                   2730:         fprintf(ficgp,"\nset title \"Probability\"\n");
                   2731:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   2732:        i=1;
                   2733:        for(k2=1; k2<=nlstate; k2++) {
                   2734:         k3=i;
                   2735:         for(k=1; k<=(nlstate+ndeath); k++) {
                   2736:           if (k != k2){
                   2737:             if(ng==2)
                   2738:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   2739:             else
                   2740:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   2741:             ij=1;
                   2742:             for(j=3; j <=ncovmodel; j++) {
                   2743:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                   2744:                 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   2745:                 ij++;
                   2746:               }
                   2747:               else
                   2748:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   2749:             }
                   2750:             fprintf(ficgp,")/(1");
                   2751:             
                   2752:             for(k1=1; k1 <=nlstate; k1++){   
                   2753:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   2754:               ij=1;
                   2755:               for(j=3; j <=ncovmodel; j++){
                   2756:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                   2757:                   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   2758:                   ij++;
                   2759:                 }
                   2760:                 else
                   2761:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   2762:               }
                   2763:               fprintf(ficgp,")");
                   2764:             }
                   2765:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   2766:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   2767:             i=i+ncovmodel;
                   2768:           }
                   2769:         } /* end k */
                   2770:        } /* end k2 */
                   2771:      } /* end jk */
                   2772:    } /* end ng */
                   2773:    fclose(ficgp); 
                   2774: }  /* end gnuplot */
                   2775: 
                   2776: 
                   2777: /*************** Moving average **************/
1.54      brouard  2778: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
1.53      brouard  2779: 
                   2780:   int i, cpt, cptcod;
1.58    ! lievre   2781:   int modcovmax =1;
1.54      brouard  2782:   int mobilavrange, mob;
1.53      brouard  2783:   double age;
1.58    ! lievre   2784: 
        !          2785:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
        !          2786:                           a covariate has 2 modalities */
        !          2787:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
        !          2788: 
1.54      brouard  2789:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   2790:     if(mobilav==1) mobilavrange=5; /* default */
                   2791:     else mobilavrange=mobilav;
                   2792:     for (age=bage; age<=fage; age++)
                   2793:       for (i=1; i<=nlstate;i++)
1.58    ! lievre   2794:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
1.54      brouard  2795:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   2796:     /* We keep the original values on the extreme ages bage, fage and for 
                   2797:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   2798:        we use a 5 terms etc. until the borders are no more concerned. 
                   2799:     */ 
                   2800:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   2801:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   2802:        for (i=1; i<=nlstate;i++){
1.58    ! lievre   2803:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
1.54      brouard  2804:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   2805:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   2806:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   2807:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   2808:              }
                   2809:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   2810:          }
1.53      brouard  2811:        }
1.54      brouard  2812:       }/* end age */
                   2813:     }/* end mob */
                   2814:   }else return -1;
                   2815:   return 0;
                   2816: }/* End movingaverage */
1.53      brouard  2817: 
                   2818: 
                   2819: /************** Forecasting ******************/
                   2820: prevforecast(char fileres[], double anproj1,double mproj1,double jproj1,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anproj2,double p[], int i2){
                   2821:   
                   2822:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   2823:   int *popage;
                   2824:   double calagedate, agelim, kk1, kk2, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   2825:   double *popeffectif,*popcount;
                   2826:   double ***p3mat;
1.55      lievre   2827:   double ***mobaverage;
1.53      brouard  2828:   char fileresf[FILENAMELENGTH];
                   2829: 
                   2830:  agelim=AGESUP;
1.58    ! lievre   2831:  calagedate=(anproj1+mproj1/12.+jproj1/365.-dateintmean)*YEARM;
1.53      brouard  2832: 
                   2833:   prevalence(ageminpar, agemax, s, agev, nlstate, imx,Tvar,nbcode, ncodemax,mint,anint,dateprev1,dateprev2, calagedate);
                   2834:  
                   2835:  
                   2836:   strcpy(fileresf,"f"); 
                   2837:   strcat(fileresf,fileres);
                   2838:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   2839:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   2840:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   2841:   }
                   2842:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   2843:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   2844: 
                   2845:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   2846: 
1.54      brouard  2847:   if (mobilav!=0) {
1.53      brouard  2848:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.54      brouard  2849:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   2850:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   2851:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   2852:     }
1.53      brouard  2853:   }
                   2854: 
                   2855:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   2856:   if (stepm<=12) stepsize=1;
                   2857:   
                   2858:   agelim=AGESUP;
                   2859:   
                   2860:   hstepm=1;
                   2861:   hstepm=hstepm/stepm; 
                   2862:   yp1=modf(dateintmean,&yp);
                   2863:   anprojmean=yp;
                   2864:   yp2=modf((yp1*12),&yp);
                   2865:   mprojmean=yp;
                   2866:   yp1=modf((yp2*30.5),&yp);
                   2867:   jprojmean=yp;
                   2868:   if(jprojmean==0) jprojmean=1;
                   2869:   if(mprojmean==0) jprojmean=1;
                   2870:   
                   2871:   fprintf(ficresf,"# Estimated date of observed prevalence: %.lf/%.lf/%.lf ",jprojmean,mprojmean,anprojmean); 
                   2872:   
                   2873:   for(cptcov=1;cptcov<=i2;cptcov++){
                   2874:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   2875:       k=k+1;
                   2876:       fprintf(ficresf,"\n#******");
                   2877:       for(j=1;j<=cptcoveff;j++) {
                   2878:        fprintf(ficresf," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   2879:       }
                   2880:       fprintf(ficresf,"******\n");
                   2881:       fprintf(ficresf,"# StartingAge FinalAge");
                   2882:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficresf," P.%d",j);
                   2883:       
                   2884:       
                   2885:       for (cpt=0; cpt<=(anproj2-anproj1);cpt++) { 
                   2886:        fprintf(ficresf,"\n");
                   2887:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+cpt);   
                   2888: 
                   2889:        for (agedeb=(fage-((int)calagedate %12/12.)); agedeb>=(ageminpar-((int)calagedate %12)/12.); agedeb--){ 
                   2890:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   2891:          nhstepm = nhstepm/hstepm; 
                   2892:          
                   2893:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2894:          oldm=oldms;savm=savms;
                   2895:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   2896:        
                   2897:          for (h=0; h<=nhstepm; h++){
                   2898:            if (h==(int) (calagedate+YEARM*cpt)) {
                   2899:              fprintf(ficresf,"\n %.f %.f ",anproj1+cpt,agedeb+h*hstepm/YEARM*stepm);
                   2900:            } 
                   2901:            for(j=1; j<=nlstate+ndeath;j++) {
                   2902:              kk1=0.;kk2=0;
                   2903:              for(i=1; i<=nlstate;i++) {              
                   2904:                if (mobilav==1) 
                   2905:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   2906:                else {
                   2907:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   2908:                }
                   2909:                
                   2910:              }
                   2911:              if (h==(int)(calagedate+12*cpt)){
                   2912:                fprintf(ficresf," %.3f", kk1);
                   2913:                        
                   2914:              }
                   2915:            }
                   2916:          }
                   2917:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2918:        }
                   2919:       }
                   2920:     }
                   2921:   }
                   2922:        
1.54      brouard  2923:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.53      brouard  2924: 
                   2925:   fclose(ficresf);
                   2926: }
                   2927: /************** Forecasting ******************/
                   2928: populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
                   2929:   
                   2930:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   2931:   int *popage;
                   2932:   double calagedate, agelim, kk1, kk2, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   2933:   double *popeffectif,*popcount;
                   2934:   double ***p3mat,***tabpop,***tabpopprev;
1.55      lievre   2935:   double ***mobaverage;
1.53      brouard  2936:   char filerespop[FILENAMELENGTH];
                   2937: 
                   2938:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   2939:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   2940:   agelim=AGESUP;
                   2941:   calagedate=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   2942:   
                   2943:   prevalence(ageminpar, agemax, s, agev, nlstate, imx,Tvar,nbcode, ncodemax,mint,anint,dateprev1,dateprev2, calagedate);
                   2944:   
                   2945:   
                   2946:   strcpy(filerespop,"pop"); 
                   2947:   strcat(filerespop,fileres);
                   2948:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   2949:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   2950:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   2951:   }
                   2952:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   2953:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   2954: 
                   2955:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   2956: 
1.54      brouard  2957:   if (mobilav!=0) {
1.53      brouard  2958:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.54      brouard  2959:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   2960:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   2961:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   2962:     }
1.53      brouard  2963:   }
                   2964: 
                   2965:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   2966:   if (stepm<=12) stepsize=1;
                   2967:   
                   2968:   agelim=AGESUP;
                   2969:   
                   2970:   hstepm=1;
                   2971:   hstepm=hstepm/stepm; 
                   2972:   
                   2973:   if (popforecast==1) {
                   2974:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   2975:       printf("Problem with population file : %s\n",popfile);exit(0);
                   2976:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   2977:     } 
                   2978:     popage=ivector(0,AGESUP);
                   2979:     popeffectif=vector(0,AGESUP);
                   2980:     popcount=vector(0,AGESUP);
                   2981:     
                   2982:     i=1;   
                   2983:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   2984:    
                   2985:     imx=i;
                   2986:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   2987:   }
                   2988: 
                   2989:   for(cptcov=1;cptcov<=i2;cptcov++){
                   2990:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   2991:       k=k+1;
                   2992:       fprintf(ficrespop,"\n#******");
                   2993:       for(j=1;j<=cptcoveff;j++) {
                   2994:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   2995:       }
                   2996:       fprintf(ficrespop,"******\n");
                   2997:       fprintf(ficrespop,"# Age");
                   2998:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   2999:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   3000:       
                   3001:       for (cpt=0; cpt<=0;cpt++) { 
                   3002:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   3003:        
                   3004:        for (agedeb=(fage-((int)calagedate %12/12.)); agedeb>=(ageminpar-((int)calagedate %12)/12.); agedeb--){ 
                   3005:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   3006:          nhstepm = nhstepm/hstepm; 
                   3007:          
                   3008:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3009:          oldm=oldms;savm=savms;
                   3010:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   3011:        
                   3012:          for (h=0; h<=nhstepm; h++){
                   3013:            if (h==(int) (calagedate+YEARM*cpt)) {
                   3014:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   3015:            } 
                   3016:            for(j=1; j<=nlstate+ndeath;j++) {
                   3017:              kk1=0.;kk2=0;
                   3018:              for(i=1; i<=nlstate;i++) {              
                   3019:                if (mobilav==1) 
                   3020:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   3021:                else {
                   3022:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   3023:                }
                   3024:              }
                   3025:              if (h==(int)(calagedate+12*cpt)){
                   3026:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   3027:                  /*fprintf(ficrespop," %.3f", kk1);
                   3028:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   3029:              }
                   3030:            }
                   3031:            for(i=1; i<=nlstate;i++){
                   3032:              kk1=0.;
                   3033:                for(j=1; j<=nlstate;j++){
                   3034:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   3035:                }
                   3036:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedate+12*cpt)*hstepm/YEARM*stepm-1)];
                   3037:            }
                   3038: 
                   3039:            if (h==(int)(calagedate+12*cpt)) for(j=1; j<=nlstate;j++) 
                   3040:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   3041:          }
                   3042:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3043:        }
                   3044:       }
                   3045:  
                   3046:   /******/
                   3047: 
                   3048:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   3049:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   3050:        for (agedeb=(fage-((int)calagedate %12/12.)); agedeb>=(ageminpar-((int)calagedate %12)/12.); agedeb--){ 
                   3051:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   3052:          nhstepm = nhstepm/hstepm; 
                   3053:          
                   3054:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3055:          oldm=oldms;savm=savms;
                   3056:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   3057:          for (h=0; h<=nhstepm; h++){
                   3058:            if (h==(int) (calagedate+YEARM*cpt)) {
                   3059:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   3060:            } 
                   3061:            for(j=1; j<=nlstate+ndeath;j++) {
                   3062:              kk1=0.;kk2=0;
                   3063:              for(i=1; i<=nlstate;i++) {              
                   3064:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   3065:              }
                   3066:              if (h==(int)(calagedate+12*cpt)) fprintf(ficresf," %15.2f", kk1); 
                   3067:            }
                   3068:          }
                   3069:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3070:        }
                   3071:       }
                   3072:    } 
                   3073:   }
                   3074:  
1.54      brouard  3075:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.53      brouard  3076: 
                   3077:   if (popforecast==1) {
                   3078:     free_ivector(popage,0,AGESUP);
                   3079:     free_vector(popeffectif,0,AGESUP);
                   3080:     free_vector(popcount,0,AGESUP);
                   3081:   }
                   3082:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3083:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3084:   fclose(ficrespop);
                   3085: }
                   3086: 
                   3087: /***********************************************/
                   3088: /**************** Main Program *****************/
                   3089: /***********************************************/
                   3090: 
                   3091: int main(int argc, char *argv[])
                   3092: {
                   3093: 
                   3094:   int i,j, k, n=MAXN,iter,m,size,cptcode, cptcod;
                   3095:   double agedeb, agefin,hf;
                   3096:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   3097: 
                   3098:   double fret;
                   3099:   double **xi,tmp,delta;
                   3100: 
                   3101:   double dum; /* Dummy variable */
                   3102:   double ***p3mat;
                   3103:   double ***mobaverage;
                   3104:   int *indx;
                   3105:   char line[MAXLINE], linepar[MAXLINE];
                   3106:   char path[80],pathc[80],pathcd[80],pathtot[80],model[80];
                   3107:   int firstobs=1, lastobs=10;
                   3108:   int sdeb, sfin; /* Status at beginning and end */
                   3109:   int c,  h , cpt,l;
                   3110:   int ju,jl, mi;
                   3111:   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
                   3112:   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,**adl,*tab; 
                   3113:   int mobilav=0,popforecast=0;
                   3114:   int hstepm, nhstepm;
                   3115:   double jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,jpyram, mpyram,anpyram,jpyram1, mpyram1,anpyram1, calagedate;
                   3116: 
                   3117:   double bage, fage, age, agelim, agebase;
                   3118:   double ftolpl=FTOL;
                   3119:   double **prlim;
                   3120:   double *severity;
                   3121:   double ***param; /* Matrix of parameters */
                   3122:   double  *p;
                   3123:   double **matcov; /* Matrix of covariance */
                   3124:   double ***delti3; /* Scale */
                   3125:   double *delti; /* Scale */
                   3126:   double ***eij, ***vareij;
                   3127:   double **varpl; /* Variances of prevalence limits by age */
                   3128:   double *epj, vepp;
                   3129:   double kk1, kk2;
                   3130:   double dateprev1, dateprev2,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2;
                   3131:   
                   3132: 
                   3133:   char *alph[]={"a","a","b","c","d","e"}, str[4];
                   3134: 
                   3135: 
                   3136:   char z[1]="c", occ;
                   3137: #include <sys/time.h>
                   3138: #include <time.h>
                   3139:   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
                   3140:  
                   3141:   /* long total_usecs;
                   3142:   struct timeval start_time, end_time;
                   3143:   
                   3144:   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   3145:   getcwd(pathcd, size);
                   3146: 
                   3147:   printf("\n%s",version);
                   3148:   if(argc <=1){
                   3149:     printf("\nEnter the parameter file name: ");
                   3150:     scanf("%s",pathtot);
                   3151:   }
                   3152:   else{
                   3153:     strcpy(pathtot,argv[1]);
                   3154:   }
                   3155:   /*if(getcwd(pathcd, 80)!= NULL)printf ("Error pathcd\n");*/
                   3156:   /*cygwin_split_path(pathtot,path,optionfile);
                   3157:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   3158:   /* cutv(path,optionfile,pathtot,'\\');*/
                   3159: 
                   3160:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   3161:    printf("pathtot=%s, path=%s, optionfile=%s optionfilext=%s optionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   3162:   chdir(path);
                   3163:   replace(pathc,path);
                   3164: 
                   3165: /*-------- arguments in the command line --------*/
                   3166: 
                   3167:   /* Log file */
                   3168:   strcat(filelog, optionfilefiname);
                   3169:   strcat(filelog,".log");    /* */
                   3170:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   3171:     printf("Problem with logfile %s\n",filelog);
                   3172:     goto end;
                   3173:   }
                   3174:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   3175:   fprintf(ficlog,"\n%s",version);
                   3176:   fprintf(ficlog,"\nEnter the parameter file name: ");
                   3177:   fprintf(ficlog,"pathtot=%s, path=%s, optionfile=%s optionfilext=%s optionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   3178:   fflush(ficlog);
                   3179: 
                   3180:   /* */
                   3181:   strcpy(fileres,"r");
                   3182:   strcat(fileres, optionfilefiname);
                   3183:   strcat(fileres,".txt");    /* Other files have txt extension */
                   3184: 
                   3185:   /*---------arguments file --------*/
                   3186: 
                   3187:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
                   3188:     printf("Problem with optionfile %s\n",optionfile);
                   3189:     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
                   3190:     goto end;
                   3191:   }
                   3192: 
                   3193:   strcpy(filereso,"o");
                   3194:   strcat(filereso,fileres);
                   3195:   if((ficparo=fopen(filereso,"w"))==NULL) {
                   3196:     printf("Problem with Output resultfile: %s\n", filereso);
                   3197:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   3198:     goto end;
                   3199:   }
                   3200: 
                   3201:   /* Reads comments: lines beginning with '#' */
                   3202:   while((c=getc(ficpar))=='#' && c!= EOF){
                   3203:     ungetc(c,ficpar);
                   3204:     fgets(line, MAXLINE, ficpar);
                   3205:     puts(line);
                   3206:     fputs(line,ficparo);
                   3207:   }
                   3208:   ungetc(c,ficpar);
                   3209: 
                   3210:   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
                   3211:   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
                   3212:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
                   3213: while((c=getc(ficpar))=='#' && c!= EOF){
                   3214:     ungetc(c,ficpar);
                   3215:     fgets(line, MAXLINE, ficpar);
                   3216:     puts(line);
                   3217:     fputs(line,ficparo);
                   3218:   }
                   3219:   ungetc(c,ficpar);
                   3220:   
                   3221:    
                   3222:   covar=matrix(0,NCOVMAX,1,n); 
1.58    ! lievre   3223:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
1.53      brouard  3224:   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
                   3225: 
1.58    ! lievre   3226:   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
1.53      brouard  3227:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
                   3228:   
                   3229:   /* Read guess parameters */
                   3230:   /* Reads comments: lines beginning with '#' */
                   3231:   while((c=getc(ficpar))=='#' && c!= EOF){
                   3232:     ungetc(c,ficpar);
                   3233:     fgets(line, MAXLINE, ficpar);
                   3234:     puts(line);
                   3235:     fputs(line,ficparo);
                   3236:   }
                   3237:   ungetc(c,ficpar);
                   3238:   
                   3239:   param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   3240:     for(i=1; i <=nlstate; i++)
                   3241:     for(j=1; j <=nlstate+ndeath-1; j++){
                   3242:       fscanf(ficpar,"%1d%1d",&i1,&j1);
                   3243:       fprintf(ficparo,"%1d%1d",i1,j1);
                   3244:       if(mle==1)
                   3245:        printf("%1d%1d",i,j);
                   3246:       fprintf(ficlog,"%1d%1d",i,j);
                   3247:       for(k=1; k<=ncovmodel;k++){
                   3248:        fscanf(ficpar," %lf",&param[i][j][k]);
                   3249:        if(mle==1){
                   3250:          printf(" %lf",param[i][j][k]);
                   3251:          fprintf(ficlog," %lf",param[i][j][k]);
                   3252:        }
                   3253:        else
                   3254:          fprintf(ficlog," %lf",param[i][j][k]);
                   3255:        fprintf(ficparo," %lf",param[i][j][k]);
                   3256:       }
                   3257:       fscanf(ficpar,"\n");
                   3258:       if(mle==1)
                   3259:        printf("\n");
                   3260:       fprintf(ficlog,"\n");
                   3261:       fprintf(ficparo,"\n");
                   3262:     }
                   3263:   
1.58    ! lievre   3264:     npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
1.53      brouard  3265: 
                   3266:   p=param[1][1];
                   3267:   
                   3268:   /* Reads comments: lines beginning with '#' */
                   3269:   while((c=getc(ficpar))=='#' && c!= EOF){
                   3270:     ungetc(c,ficpar);
                   3271:     fgets(line, MAXLINE, ficpar);
                   3272:     puts(line);
                   3273:     fputs(line,ficparo);
                   3274:   }
                   3275:   ungetc(c,ficpar);
                   3276: 
                   3277:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   3278:   delti=vector(1,npar); /* Scale of each paramater (output from hesscov) */
                   3279:   for(i=1; i <=nlstate; i++){
                   3280:     for(j=1; j <=nlstate+ndeath-1; j++){
                   3281:       fscanf(ficpar,"%1d%1d",&i1,&j1);
                   3282:       printf("%1d%1d",i,j);
                   3283:       fprintf(ficparo,"%1d%1d",i1,j1);
                   3284:       for(k=1; k<=ncovmodel;k++){
                   3285:        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   3286:        printf(" %le",delti3[i][j][k]);
                   3287:        fprintf(ficparo," %le",delti3[i][j][k]);
                   3288:       }
                   3289:       fscanf(ficpar,"\n");
                   3290:       printf("\n");
                   3291:       fprintf(ficparo,"\n");
                   3292:     }
                   3293:   }
                   3294:   delti=delti3[1][1];
                   3295:   
                   3296:   /* Reads comments: lines beginning with '#' */
                   3297:   while((c=getc(ficpar))=='#' && c!= EOF){
                   3298:     ungetc(c,ficpar);
                   3299:     fgets(line, MAXLINE, ficpar);
                   3300:     puts(line);
                   3301:     fputs(line,ficparo);
                   3302:   }
                   3303:   ungetc(c,ficpar);
                   3304:   
                   3305:   matcov=matrix(1,npar,1,npar);
                   3306:   for(i=1; i <=npar; i++){
                   3307:     fscanf(ficpar,"%s",&str);
                   3308:     if(mle==1)
                   3309:       printf("%s",str);
                   3310:     fprintf(ficlog,"%s",str);
                   3311:     fprintf(ficparo,"%s",str);
                   3312:     for(j=1; j <=i; j++){
                   3313:       fscanf(ficpar," %le",&matcov[i][j]);
                   3314:       if(mle==1){
                   3315:        printf(" %.5le",matcov[i][j]);
                   3316:        fprintf(ficlog," %.5le",matcov[i][j]);
                   3317:       }
                   3318:       else
                   3319:        fprintf(ficlog," %.5le",matcov[i][j]);
                   3320:       fprintf(ficparo," %.5le",matcov[i][j]);
                   3321:     }
                   3322:     fscanf(ficpar,"\n");
                   3323:     if(mle==1)
                   3324:       printf("\n");
                   3325:     fprintf(ficlog,"\n");
                   3326:     fprintf(ficparo,"\n");
                   3327:   }
                   3328:   for(i=1; i <=npar; i++)
                   3329:     for(j=i+1;j<=npar;j++)
                   3330:       matcov[i][j]=matcov[j][i];
                   3331:    
                   3332:   if(mle==1)
                   3333:     printf("\n");
                   3334:   fprintf(ficlog,"\n");
                   3335: 
                   3336: 
                   3337:     /*-------- Rewriting paramater file ----------*/
                   3338:      strcpy(rfileres,"r");    /* "Rparameterfile */
                   3339:      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   3340:      strcat(rfileres,".");    /* */
                   3341:      strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   3342:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   3343:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   3344:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   3345:     }
                   3346:     fprintf(ficres,"#%s\n",version);
                   3347:     
                   3348:     /*-------- data file ----------*/
                   3349:     if((fic=fopen(datafile,"r"))==NULL)    {
                   3350:       printf("Problem with datafile: %s\n", datafile);goto end;
                   3351:       fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;
                   3352:     }
                   3353: 
                   3354:     n= lastobs;
                   3355:     severity = vector(1,maxwav);
                   3356:     outcome=imatrix(1,maxwav+1,1,n);
                   3357:     num=ivector(1,n);
                   3358:     moisnais=vector(1,n);
                   3359:     annais=vector(1,n);
                   3360:     moisdc=vector(1,n);
                   3361:     andc=vector(1,n);
                   3362:     agedc=vector(1,n);
                   3363:     cod=ivector(1,n);
                   3364:     weight=vector(1,n);
                   3365:     for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   3366:     mint=matrix(1,maxwav,1,n);
                   3367:     anint=matrix(1,maxwav,1,n);
                   3368:     s=imatrix(1,maxwav+1,1,n);
                   3369:     adl=imatrix(1,maxwav+1,1,n);    
                   3370:     tab=ivector(1,NCOVMAX);
                   3371:     ncodemax=ivector(1,8);
                   3372: 
                   3373:     i=1;
                   3374:     while (fgets(line, MAXLINE, fic) != NULL)    {
                   3375:       if ((i >= firstobs) && (i <=lastobs)) {
                   3376:        
                   3377:        for (j=maxwav;j>=1;j--){
                   3378:          cutv(stra, strb,line,' '); s[j][i]=atoi(strb); 
                   3379:          strcpy(line,stra);
                   3380:          cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
                   3381:          cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);
                   3382:        }
                   3383:        
                   3384:        cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);
                   3385:        cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);
                   3386: 
                   3387:        cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);
                   3388:        cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);
                   3389: 
                   3390:        cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);
                   3391:        for (j=ncovcol;j>=1;j--){
                   3392:          cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);
                   3393:        } 
                   3394:        num[i]=atol(stra);
                   3395:        
                   3396:        /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   3397:          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])); ij=ij+1;}*/
                   3398: 
                   3399:        i=i+1;
                   3400:       }
                   3401:     } 
                   3402:     /* printf("ii=%d", ij);
                   3403:        scanf("%d",i);*/
                   3404:   imx=i-1; /* Number of individuals */
                   3405: 
                   3406:   /* for (i=1; i<=imx; i++){
                   3407:     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
                   3408:     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
                   3409:     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
                   3410:     }*/
                   3411:    /*  for (i=1; i<=imx; i++){
                   3412:      if (s[4][i]==9)  s[4][i]=-1; 
                   3413:      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]));}*/
                   3414:   
                   3415:  
                   3416:   /* Calculation of the number of parameter from char model*/
                   3417:   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
                   3418:   Tprod=ivector(1,15); 
                   3419:   Tvaraff=ivector(1,15); 
                   3420:   Tvard=imatrix(1,15,1,2);
                   3421:   Tage=ivector(1,15);      
                   3422:    
1.58    ! lievre   3423:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.53      brouard  3424:     j=0, j1=0, k1=1, k2=1;
1.58    ! lievre   3425:     j=nbocc(model,'+'); /* j=Number of '+' */
        !          3426:     j1=nbocc(model,'*'); /* j1=Number of '*' */
        !          3427:     cptcovn=j+1; 
        !          3428:     cptcovprod=j1; /*Number of products */
1.53      brouard  3429:     
                   3430:     strcpy(modelsav,model); 
                   3431:     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
                   3432:       printf("Error. Non available option model=%s ",model);
                   3433:       fprintf(ficlog,"Error. Non available option model=%s ",model);
                   3434:       goto end;
                   3435:     }
                   3436:     
1.58    ! lievre   3437:     /* This loop fill the array Tvar from the string 'model'.*/
        !          3438: 
1.53      brouard  3439:     for(i=(j+1); i>=1;i--){
                   3440:       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */ 
                   3441:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyze it */
                   3442:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   3443:       /*scanf("%d",i);*/
                   3444:       if (strchr(strb,'*')) {  /* Model includes a product */
                   3445:        cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
                   3446:        if (strcmp(strc,"age")==0) { /* Vn*age */
                   3447:          cptcovprod--;
                   3448:          cutv(strb,stre,strd,'V');
                   3449:          Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
                   3450:          cptcovage++;
                   3451:            Tage[cptcovage]=i;
                   3452:            /*printf("stre=%s ", stre);*/
                   3453:        }
                   3454:        else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   3455:          cptcovprod--;
                   3456:          cutv(strb,stre,strc,'V');
                   3457:          Tvar[i]=atoi(stre);
                   3458:          cptcovage++;
                   3459:          Tage[cptcovage]=i;
                   3460:        }
                   3461:        else {  /* Age is not in the model */
                   3462:          cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
                   3463:          Tvar[i]=ncovcol+k1;
                   3464:          cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
                   3465:          Tprod[k1]=i;
                   3466:          Tvard[k1][1]=atoi(strc); /* m*/
                   3467:          Tvard[k1][2]=atoi(stre); /* n */
                   3468:          Tvar[cptcovn+k2]=Tvard[k1][1];
                   3469:          Tvar[cptcovn+k2+1]=Tvard[k1][2]; 
                   3470:          for (k=1; k<=lastobs;k++) 
                   3471:            covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
                   3472:          k1++;
                   3473:          k2=k2+2;
                   3474:        }
                   3475:       }
                   3476:       else { /* no more sum */
                   3477:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   3478:        /*  scanf("%d",i);*/
                   3479:       cutv(strd,strc,strb,'V');
                   3480:       Tvar[i]=atoi(strc);
                   3481:       }
                   3482:       strcpy(modelsav,stra);  
                   3483:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   3484:        scanf("%d",i);*/
                   3485:     } /* end of loop + */
                   3486:   } /* end model */
                   3487:   
1.58    ! lievre   3488:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
        !          3489:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
        !          3490: 
1.53      brouard  3491:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   3492:   printf("cptcovprod=%d ", cptcovprod);
                   3493:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
1.58    ! lievre   3494: 
        !          3495:   scanf("%d ",i);
        !          3496:   fclose(fic);*/
1.53      brouard  3497: 
                   3498:     /*  if(mle==1){*/
                   3499:     if (weightopt != 1) { /* Maximisation without weights*/
                   3500:       for(i=1;i<=n;i++) weight[i]=1.0;
                   3501:     }
                   3502:     /*-calculation of age at interview from date of interview and age at death -*/
                   3503:     agev=matrix(1,maxwav,1,imx);
                   3504: 
                   3505:     for (i=1; i<=imx; i++) {
                   3506:       for(m=2; (m<= maxwav); m++) {
                   3507:        if ((mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   3508:         anint[m][i]=9999;
                   3509:         s[m][i]=-1;
                   3510:        }
                   3511:      if(moisdc[i]==99 && andc[i]==9999 & s[m][i]>nlstate) s[m][i]=-1;
                   3512:       }
                   3513:     }
                   3514: 
                   3515:     for (i=1; i<=imx; i++)  {
                   3516:       agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   3517:       for(m=1; (m<= maxwav); m++){
                   3518:        if(s[m][i] >0){
                   3519:          if (s[m][i] >= nlstate+1) {
                   3520:            if(agedc[i]>0)
                   3521:              if(moisdc[i]!=99 && andc[i]!=9999)
                   3522:                agev[m][i]=agedc[i];
                   3523:            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
                   3524:           else {
                   3525:              if (andc[i]!=9999){
                   3526:              printf("Warning negative age at death: %d line:%d\n",num[i],i);
                   3527:              fprintf(ficlog,"Warning negative age at death: %d line:%d\n",num[i],i);
                   3528:              agev[m][i]=-1;
                   3529:              }
                   3530:            }
                   3531:          }
                   3532:          else if(s[m][i] !=9){ /* Should no more exist */
                   3533:            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   3534:            if(mint[m][i]==99 || anint[m][i]==9999)
                   3535:              agev[m][i]=1;
                   3536:            else if(agev[m][i] <agemin){ 
                   3537:              agemin=agev[m][i];
                   3538:              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
                   3539:            }
                   3540:            else if(agev[m][i] >agemax){
                   3541:              agemax=agev[m][i];
                   3542:             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
                   3543:            }
                   3544:            /*agev[m][i]=anint[m][i]-annais[i];*/
                   3545:            /*   agev[m][i] = age[i]+2*m;*/
                   3546:          }
                   3547:          else { /* =9 */
                   3548:            agev[m][i]=1;
                   3549:            s[m][i]=-1;
                   3550:          }
                   3551:        }
                   3552:        else /*= 0 Unknown */
                   3553:          agev[m][i]=1;
                   3554:       }
                   3555:     
                   3556:     }
                   3557:     for (i=1; i<=imx; i++)  {
                   3558:       for(m=1; (m<= maxwav); m++){
                   3559:        if (s[m][i] > (nlstate+ndeath)) {
                   3560:          printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);   
                   3561:          fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);   
                   3562:          goto end;
                   3563:        }
                   3564:       }
                   3565:     }
                   3566: 
1.58    ! lievre   3567:     printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
        !          3568:     fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax); 
1.53      brouard  3569: 
                   3570:     free_vector(severity,1,maxwav);
                   3571:     free_imatrix(outcome,1,maxwav+1,1,n);
                   3572:     free_vector(moisnais,1,n);
                   3573:     free_vector(annais,1,n);
                   3574:     /* free_matrix(mint,1,maxwav,1,n);
                   3575:        free_matrix(anint,1,maxwav,1,n);*/
                   3576:     free_vector(moisdc,1,n);
                   3577:     free_vector(andc,1,n);
                   3578: 
                   3579:    
                   3580:     wav=ivector(1,imx);
                   3581:     dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   3582:     mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   3583:    
                   3584:     /* Concatenates waves */
                   3585:       concatwav(wav, dh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
                   3586: 
1.58    ! lievre   3587:       /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
1.53      brouard  3588: 
                   3589:       Tcode=ivector(1,100);
                   3590:       nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   3591:       ncodemax[1]=1;
                   3592:       if (cptcovn > 0) tricode(Tvar,nbcode,imx);
                   3593:       
1.58    ! lievre   3594:       codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of 
        !          3595:                                     the estimations*/
1.53      brouard  3596:    h=0;
                   3597:    m=pow(2,cptcoveff);
                   3598:  
                   3599:    for(k=1;k<=cptcoveff; k++){
                   3600:      for(i=1; i <=(m/pow(2,k));i++){
                   3601:        for(j=1; j <= ncodemax[k]; j++){
                   3602:         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
                   3603:           h++;
                   3604:           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
                   3605:           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
                   3606:         } 
                   3607:        }
                   3608:      }
                   3609:    } 
                   3610:    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   3611:       codtab[1][2]=1;codtab[2][2]=2; */
                   3612:    /* for(i=1; i <=m ;i++){ 
                   3613:       for(k=1; k <=cptcovn; k++){
                   3614:       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
                   3615:       }
                   3616:       printf("\n");
                   3617:       }
                   3618:       scanf("%d",i);*/
                   3619:     
                   3620:    /* Calculates basic frequencies. Computes observed prevalence at single age
                   3621:        and prints on file fileres'p'. */
                   3622: 
                   3623:     
                   3624:    
                   3625:     pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3626:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3627:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3628:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3629:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   3630:      
                   3631:     /* For Powell, parameters are in a vector p[] starting at p[1]
                   3632:        so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   3633:     p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   3634: 
                   3635:     if(mle==1){
                   3636:     mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   3637:     }
                   3638:     
                   3639:     /*--------- results files --------------*/
                   3640:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
                   3641:   
                   3642: 
                   3643:    jk=1;
                   3644:    fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   3645:    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   3646:    fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   3647:    for(i=1,jk=1; i <=nlstate; i++){
                   3648:      for(k=1; k <=(nlstate+ndeath); k++){
                   3649:        if (k != i) 
                   3650:         {
                   3651:           printf("%d%d ",i,k);
                   3652:           fprintf(ficlog,"%d%d ",i,k);
                   3653:           fprintf(ficres,"%1d%1d ",i,k);
                   3654:           for(j=1; j <=ncovmodel; j++){
                   3655:             printf("%f ",p[jk]);
                   3656:             fprintf(ficlog,"%f ",p[jk]);
                   3657:             fprintf(ficres,"%f ",p[jk]);
                   3658:             jk++; 
                   3659:           }
                   3660:           printf("\n");
                   3661:           fprintf(ficlog,"\n");
                   3662:           fprintf(ficres,"\n");
                   3663:         }
                   3664:      }
                   3665:    }
                   3666:    if(mle==1){
                   3667:      /* Computing hessian and covariance matrix */
                   3668:      ftolhess=ftol; /* Usually correct */
                   3669:      hesscov(matcov, p, npar, delti, ftolhess, func);
                   3670:    }
                   3671:    fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   3672:    printf("# Scales (for hessian or gradient estimation)\n");
                   3673:    fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   3674:    for(i=1,jk=1; i <=nlstate; i++){
                   3675:      for(j=1; j <=nlstate+ndeath; j++){
                   3676:        if (j!=i) {
                   3677:         fprintf(ficres,"%1d%1d",i,j);
                   3678:         printf("%1d%1d",i,j);
                   3679:         fprintf(ficlog,"%1d%1d",i,j);
                   3680:         for(k=1; k<=ncovmodel;k++){
                   3681:           printf(" %.5e",delti[jk]);
                   3682:           fprintf(ficlog," %.5e",delti[jk]);
                   3683:           fprintf(ficres," %.5e",delti[jk]);
                   3684:           jk++;
                   3685:         }
                   3686:         printf("\n");
                   3687:         fprintf(ficlog,"\n");
                   3688:         fprintf(ficres,"\n");
                   3689:        }
                   3690:      }
                   3691:    }
                   3692:    
                   3693:    k=1;
                   3694:    fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                   3695:    if(mle==1)
                   3696:      printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                   3697:    fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                   3698:    for(i=1;i<=npar;i++){
                   3699:      /*  if (k>nlstate) k=1;
                   3700:         i1=(i-1)/(ncovmodel*nlstate)+1; 
                   3701:         fprintf(ficres,"%s%d%d",alph[k],i1,tab[i]);
                   3702:         printf("%s%d%d",alph[k],i1,tab[i]);*/
                   3703:      fprintf(ficres,"%3d",i);
                   3704:      if(mle==1)
                   3705:        printf("%3d",i);
                   3706:      fprintf(ficlog,"%3d",i);
                   3707:      for(j=1; j<=i;j++){
                   3708:        fprintf(ficres," %.5e",matcov[i][j]);
                   3709:        if(mle==1)
                   3710:         printf(" %.5e",matcov[i][j]);
                   3711:        fprintf(ficlog," %.5e",matcov[i][j]);
                   3712:      }
                   3713:      fprintf(ficres,"\n");
                   3714:      if(mle==1)
                   3715:        printf("\n");
                   3716:      fprintf(ficlog,"\n");
                   3717:      k++;
                   3718:    }
                   3719:    
                   3720:    while((c=getc(ficpar))=='#' && c!= EOF){
                   3721:      ungetc(c,ficpar);
                   3722:      fgets(line, MAXLINE, ficpar);
                   3723:      puts(line);
                   3724:      fputs(line,ficparo);
                   3725:    }
                   3726:    ungetc(c,ficpar);
                   3727:    estepm=0;
                   3728:    fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   3729:    if (estepm==0 || estepm < stepm) estepm=stepm;
                   3730:    if (fage <= 2) {
                   3731:      bage = ageminpar;
                   3732:      fage = agemaxpar;
                   3733:    }
                   3734:    
                   3735:    fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   3736:    fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   3737:    fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   3738:    
                   3739:    while((c=getc(ficpar))=='#' && c!= EOF){
                   3740:      ungetc(c,ficpar);
                   3741:      fgets(line, MAXLINE, ficpar);
                   3742:      puts(line);
                   3743:      fputs(line,ficparo);
                   3744:    }
                   3745:    ungetc(c,ficpar);
                   3746:   
                   3747:    fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
1.57      lievre   3748:    fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   3749:    fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
1.53      brouard  3750:    
                   3751:    while((c=getc(ficpar))=='#' && c!= EOF){
                   3752:      ungetc(c,ficpar);
                   3753:      fgets(line, MAXLINE, ficpar);
                   3754:      puts(line);
                   3755:      fputs(line,ficparo);
                   3756:    }
                   3757:    ungetc(c,ficpar);
                   3758:  
                   3759: 
                   3760:    dateprev1=anprev1+mprev1/12.+jprev1/365.;
                   3761:    dateprev2=anprev2+mprev2/12.+jprev2/365.;
                   3762: 
                   3763:   fscanf(ficpar,"pop_based=%d\n",&popbased);
                   3764:   fprintf(ficparo,"pop_based=%d\n",popbased);   
                   3765:   fprintf(ficres,"pop_based=%d\n",popbased);   
                   3766:   
                   3767:   while((c=getc(ficpar))=='#' && c!= EOF){
                   3768:     ungetc(c,ficpar);
                   3769:     fgets(line, MAXLINE, ficpar);
                   3770:     puts(line);
                   3771:     fputs(line,ficparo);
                   3772:   }
                   3773:   ungetc(c,ficpar);
                   3774: 
                   3775:   fscanf(ficpar,"starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf\n",&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2);
                   3776: fprintf(ficparo,"starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf\n",jproj1,mproj1,anproj1,jproj2,mproj2,anproj2);
                   3777: fprintf(ficres,"starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf\n",jproj1,mproj1,anproj1,jproj2,mproj2,anproj2);
                   3778: 
                   3779: 
                   3780: while((c=getc(ficpar))=='#' && c!= EOF){
                   3781:     ungetc(c,ficpar);
                   3782:     fgets(line, MAXLINE, ficpar);
                   3783:     puts(line);
                   3784:     fputs(line,ficparo);
                   3785:   }
                   3786:   ungetc(c,ficpar);
                   3787: 
                   3788:   fscanf(ficpar,"popforecast=%d popfile=%s popfiledate=%lf/%lf/%lf last-popfiledate=%lf/%lf/%lf\n",&popforecast,popfile,&jpyram,&mpyram,&anpyram,&jpyram1,&mpyram1,&anpyram1);
                   3789:   fprintf(ficparo,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);
                   3790:   fprintf(ficres,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);
                   3791: 
1.58    ! lievre   3792:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvar,nbcode, ncodemax,mint,anint,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);
        !          3793: 
1.53      brouard  3794: /*------------ gnuplot -------------*/
1.54      brouard  3795:  strcpy(optionfilegnuplot,optionfilefiname);
                   3796:  strcat(optionfilegnuplot,".gp");
                   3797:  if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   3798:    printf("Problem with file %s",optionfilegnuplot);
                   3799:  }
                   3800:  else{
                   3801:    fprintf(ficgp,"\n# %s\n", version); 
                   3802:    fprintf(ficgp,"# %s\n", optionfilegnuplot); 
                   3803:    fprintf(ficgp,"set missing 'NaNq'\n");
                   3804: }
                   3805:  fclose(ficgp);
1.53      brouard  3806:  printinggnuplot(fileres, ageminpar,agemaxpar,fage, pathc,p);
                   3807: /*--------- index.htm --------*/
                   3808: 
                   3809:   strcpy(optionfilehtm,optionfile);
                   3810:   strcat(optionfilehtm,".htm");
                   3811:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
                   3812:     printf("Problem with %s \n",optionfilehtm), exit(0);
                   3813:   }
                   3814: 
                   3815:   fprintf(fichtm,"<body> <font size=\"2\">%s </font> <hr size=\"2\" color=\"#EC5E5E\"> \n
                   3816: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n
                   3817: \n
                   3818: Total number of observations=%d <br>\n
                   3819: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n
                   3820: <hr  size=\"2\" color=\"#EC5E5E\">
                   3821:  <ul><li><h4>Parameter files</h4>\n
                   3822:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n
                   3823:  - Log file of the run: <a href=\"%s\">%s</a><br>\n
                   3824:  - Gnuplot file name: <a href=\"%s\">%s</a></ul>\n",version,title,datafile,firstpass,lastpass,stepm, weightopt,model,imx,jmin,jmax,jmean,fileres,fileres,filelog,filelog,optionfilegnuplot,optionfilegnuplot);
                   3825:   fclose(fichtm);
                   3826: 
                   3827:  printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   3828:  
                   3829: /*------------ free_vector  -------------*/
                   3830:  chdir(path);
                   3831:  
                   3832:  free_ivector(wav,1,imx);
                   3833:  free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   3834:  free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   3835:  free_ivector(num,1,n);
                   3836:  free_vector(agedc,1,n);
                   3837:  /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   3838:  fclose(ficparo);
                   3839:  fclose(ficres);
                   3840: 
                   3841: 
1.54      brouard  3842:   /*--------------- Prevalence limit  (stable prevalence) --------------*/
1.53      brouard  3843:   
                   3844:   strcpy(filerespl,"pl");
                   3845:   strcat(filerespl,fileres);
                   3846:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.54      brouard  3847:     printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;
                   3848:     fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;
1.53      brouard  3849:   }
1.54      brouard  3850:   printf("Computing stable prevalence: result on file '%s' \n", filerespl);
                   3851:   fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);
                   3852:   fprintf(ficrespl,"#Stable prevalence \n");
1.53      brouard  3853:   fprintf(ficrespl,"#Age ");
                   3854:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   3855:   fprintf(ficrespl,"\n");
                   3856:   
                   3857:   prlim=matrix(1,nlstate,1,nlstate);
                   3858:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3859:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3860:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3861:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   3862:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   3863:   k=0;
                   3864:   agebase=ageminpar;
                   3865:   agelim=agemaxpar;
                   3866:   ftolpl=1.e-10;
                   3867:   i1=cptcoveff;
                   3868:   if (cptcovn < 1){i1=1;}
                   3869: 
                   3870:   for(cptcov=1;cptcov<=i1;cptcov++){
                   3871:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   3872:        k=k+1;
                   3873:        /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
                   3874:        fprintf(ficrespl,"\n#******");
                   3875:        printf("\n#******");
                   3876:        fprintf(ficlog,"\n#******");
                   3877:        for(j=1;j<=cptcoveff;j++) {
                   3878:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   3879:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   3880:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   3881:        }
                   3882:        fprintf(ficrespl,"******\n");
                   3883:        printf("******\n");
                   3884:        fprintf(ficlog,"******\n");
                   3885:        
                   3886:        for (age=agebase; age<=agelim; age++){
                   3887:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   3888:          fprintf(ficrespl,"%.0f",age );
                   3889:          for(i=1; i<=nlstate;i++)
                   3890:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   3891:          fprintf(ficrespl,"\n");
                   3892:        }
                   3893:       }
                   3894:     }
                   3895:   fclose(ficrespl);
                   3896: 
                   3897:   /*------------- h Pij x at various ages ------------*/
                   3898:   
                   3899:   strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   3900:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   3901:     printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
                   3902:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
                   3903:   }
                   3904:   printf("Computing pij: result on file '%s' \n", filerespij);
                   3905:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   3906:   
                   3907:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   3908:   /*if (stepm<=24) stepsize=2;*/
                   3909: 
                   3910:   agelim=AGESUP;
                   3911:   hstepm=stepsize*YEARM; /* Every year of age */
                   3912:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   3913: 
                   3914:   /* hstepm=1;   aff par mois*/
                   3915: 
                   3916:   k=0;
                   3917:   for(cptcov=1;cptcov<=i1;cptcov++){
                   3918:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   3919:       k=k+1;
                   3920:        fprintf(ficrespij,"\n#****** ");
                   3921:        for(j=1;j<=cptcoveff;j++) 
                   3922:          fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   3923:        fprintf(ficrespij,"******\n");
                   3924:        
                   3925:        for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   3926:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3927:          nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3928: 
                   3929:          /*      nhstepm=nhstepm*YEARM; aff par mois*/
                   3930: 
                   3931:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3932:          oldm=oldms;savm=savms;
                   3933:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   3934:          fprintf(ficrespij,"# Age");
                   3935:          for(i=1; i<=nlstate;i++)
                   3936:            for(j=1; j<=nlstate+ndeath;j++)
                   3937:              fprintf(ficrespij," %1d-%1d",i,j);
                   3938:          fprintf(ficrespij,"\n");
                   3939:           for (h=0; h<=nhstepm; h++){
                   3940:            fprintf(ficrespij,"%d %f %f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
                   3941:            for(i=1; i<=nlstate;i++)
                   3942:              for(j=1; j<=nlstate+ndeath;j++)
                   3943:                fprintf(ficrespij," %.5f", p3mat[i][j][h]);
                   3944:            fprintf(ficrespij,"\n");
                   3945:             }
                   3946:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3947:          fprintf(ficrespij,"\n");
                   3948:        }
                   3949:     }
                   3950:   }
                   3951: 
                   3952:   varprob(optionfilefiname, matcov, p, delti, nlstate, (int) bage, (int) fage,k,Tvar,nbcode, ncodemax);
                   3953: 
                   3954:   fclose(ficrespij);
                   3955: 
                   3956: 
                   3957:   /*---------- Forecasting ------------------*/
                   3958:   if((stepm == 1) && (strcmp(model,".")==0)){
                   3959:     prevforecast(fileres, anproj1,mproj1,jproj1, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anproj2,p, i1);
                   3960:     if (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);
                   3961:   } 
                   3962:   else{
                   3963:     erreur=108;
                   3964:     printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model);
                   3965:     fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model);
                   3966:   }
                   3967:   
                   3968: 
                   3969:   /*---------- Health expectancies and variances ------------*/
                   3970: 
                   3971:   strcpy(filerest,"t");
                   3972:   strcat(filerest,fileres);
                   3973:   if((ficrest=fopen(filerest,"w"))==NULL) {
                   3974:     printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   3975:     fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   3976:   }
                   3977:   printf("Computing Total LEs with variances: file '%s' \n", filerest); 
                   3978:   fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest); 
                   3979: 
                   3980: 
                   3981:   strcpy(filerese,"e");
                   3982:   strcat(filerese,fileres);
                   3983:   if((ficreseij=fopen(filerese,"w"))==NULL) {
                   3984:     printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   3985:     fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   3986:   }
                   3987:   printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   3988:   fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
                   3989: 
                   3990:   strcpy(fileresv,"v");
                   3991:   strcat(fileresv,fileres);
                   3992:   if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   3993:     printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   3994:     fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   3995:   }
                   3996:   printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   3997:   fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
1.58    ! lievre   3998: 
1.53      brouard  3999:   calagedate=-1;
1.58    ! lievre   4000: 
1.53      brouard  4001:   prevalence(ageminpar, agemax, s, agev, nlstate, imx,Tvar,nbcode, ncodemax,mint,anint,dateprev1,dateprev2, calagedate);
1.58    ! lievre   4002: 
1.54      brouard  4003:   if (mobilav!=0) {
1.53      brouard  4004:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.54      brouard  4005:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4006:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4007:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4008:     }
1.53      brouard  4009:   }
                   4010: 
                   4011:   k=0;
                   4012:   for(cptcov=1;cptcov<=i1;cptcov++){
                   4013:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   4014:       k=k+1; 
                   4015:       fprintf(ficrest,"\n#****** ");
                   4016:       for(j=1;j<=cptcoveff;j++) 
                   4017:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4018:       fprintf(ficrest,"******\n");
                   4019: 
                   4020:       fprintf(ficreseij,"\n#****** ");
                   4021:       for(j=1;j<=cptcoveff;j++) 
                   4022:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4023:       fprintf(ficreseij,"******\n");
                   4024: 
                   4025:       fprintf(ficresvij,"\n#****** ");
                   4026:       for(j=1;j<=cptcoveff;j++) 
                   4027:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4028:       fprintf(ficresvij,"******\n");
                   4029: 
                   4030:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   4031:       oldm=oldms;savm=savms;
                   4032:       evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov);  
                   4033:  
                   4034:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   4035:       oldm=oldms;savm=savms;
                   4036:       varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav);
                   4037:       if(popbased==1){
                   4038:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav);
                   4039:        }
                   4040: 
                   4041:  
                   4042:       fprintf(ficrest,"#Total LEs with variances: e.. (std) ");
                   4043:       for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   4044:       fprintf(ficrest,"\n");
                   4045: 
                   4046:       epj=vector(1,nlstate+1);
                   4047:       for(age=bage; age <=fage ;age++){
                   4048:        prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   4049:        if (popbased==1) {
1.54      brouard  4050:          if(mobilav ==0){
1.53      brouard  4051:            for(i=1; i<=nlstate;i++)
                   4052:              prlim[i][i]=probs[(int)age][i][k];
1.54      brouard  4053:          }else{ /* mobilav */ 
1.53      brouard  4054:            for(i=1; i<=nlstate;i++)
                   4055:              prlim[i][i]=mobaverage[(int)age][i][k];
                   4056:          }
                   4057:        }
                   4058:        
                   4059:        fprintf(ficrest," %4.0f",age);
                   4060:        for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   4061:          for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   4062:            epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   4063:            /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   4064:          }
                   4065:          epj[nlstate+1] +=epj[j];
                   4066:        }
                   4067: 
                   4068:        for(i=1, vepp=0.;i <=nlstate;i++)
                   4069:          for(j=1;j <=nlstate;j++)
                   4070:            vepp += vareij[i][j][(int)age];
                   4071:        fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   4072:        for(j=1;j <=nlstate;j++){
                   4073:          fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   4074:        }
                   4075:        fprintf(ficrest,"\n");
                   4076:       }
                   4077:     }
                   4078:   }
                   4079: free_matrix(mint,1,maxwav,1,n);
                   4080:     free_matrix(anint,1,maxwav,1,n); free_imatrix(s,1,maxwav+1,1,n);
                   4081:     free_vector(weight,1,n);
                   4082:   fclose(ficreseij);
                   4083:   fclose(ficresvij);
                   4084:   fclose(ficrest);
                   4085:   fclose(ficpar);
                   4086:   free_vector(epj,1,nlstate+1);
                   4087:   
1.54      brouard  4088:   /*------- Variance of stable prevalence------*/   
1.53      brouard  4089: 
                   4090:   strcpy(fileresvpl,"vpl");
                   4091:   strcat(fileresvpl,fileres);
                   4092:   if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.54      brouard  4093:     printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);
1.53      brouard  4094:     exit(0);
                   4095:   }
1.54      brouard  4096:   printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);
1.53      brouard  4097: 
                   4098:   k=0;
                   4099:   for(cptcov=1;cptcov<=i1;cptcov++){
                   4100:     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   4101:       k=k+1;
                   4102:       fprintf(ficresvpl,"\n#****** ");
                   4103:       for(j=1;j<=cptcoveff;j++) 
                   4104:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4105:       fprintf(ficresvpl,"******\n");
                   4106:       
                   4107:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   4108:       oldm=oldms;savm=savms;
                   4109:      varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k);
                   4110:     }
                   4111:  }
                   4112: 
                   4113:   fclose(ficresvpl);
                   4114: 
                   4115:   /*---------- End : free ----------------*/
                   4116:   free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   4117:   
                   4118:   free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   4119:   free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   4120:   
                   4121:   
                   4122:   free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   4123:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   4124:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   4125:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   4126:  
                   4127:   free_matrix(matcov,1,npar,1,npar);
                   4128:   free_vector(delti,1,npar);
                   4129:   free_matrix(agev,1,maxwav,1,imx);
                   4130:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.54      brouard  4131:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
1.53      brouard  4132: 
                   4133:   fprintf(fichtm,"\n</body>");
                   4134:   fclose(fichtm);
                   4135:   fclose(ficgp);
                   4136:   
                   4137: 
                   4138:   if(erreur >0){
                   4139:     printf("End of Imach with error or warning %d\n",erreur);
                   4140:     fprintf(ficlog,"End of Imach with error or warning %d\n",erreur);
                   4141:   }else{
                   4142:    printf("End of Imach\n");
                   4143:    fprintf(ficlog,"End of Imach\n");
                   4144:   }
                   4145:   printf("See log file on %s\n",filelog);
                   4146:   fclose(ficlog);
                   4147:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   4148:   
                   4149:   /* 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);*/
                   4150:   /*printf("Total time was %d uSec.\n", total_usecs);*/
                   4151:   /*------ End -----------*/
                   4152: 
                   4153: 
                   4154:  end:
                   4155: #ifdef windows
                   4156:   /* chdir(pathcd);*/
                   4157: #endif 
                   4158:  /*system("wgnuplot graph.plt");*/
                   4159:  /*system("../gp37mgw/wgnuplot graph.plt");*/
                   4160:  /*system("cd ../gp37mgw");*/
                   4161:  /* system("..\\gp37mgw\\wgnuplot graph.plt");*/
                   4162:  strcpy(plotcmd,GNUPLOTPROGRAM);
                   4163:  strcat(plotcmd," ");
                   4164:  strcat(plotcmd,optionfilegnuplot);
1.54      brouard  4165:  printf("Starting: %s\n",plotcmd);fflush(stdout);
1.53      brouard  4166:  system(plotcmd);
                   4167: 
1.54      brouard  4168:  /*#ifdef windows*/
1.53      brouard  4169:   while (z[0] != 'q') {
                   4170:     /* chdir(path); */
                   4171:     printf("\nType e to edit output files, g to graph again, c to start again, and q for exiting: ");
                   4172:     scanf("%s",z);
                   4173:     if (z[0] == 'c') system("./imach");
                   4174:     else if (z[0] == 'e') system(optionfilehtm);
                   4175:     else if (z[0] == 'g') system(plotcmd);
                   4176:     else if (z[0] == 'q') exit(0);
                   4177:   }
1.54      brouard  4178:   /*#endif */
1.53      brouard  4179: }
                   4180: 
                   4181: 

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