Diff for /imach/src/imach.c between versions 1.218 and 1.223

version 1.218, 2016/02/12 11:29:23 version 1.223, 2016/02/19 09:23:35
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
     Revision 1.223  2016/02/19 09:23:35  brouard
     Summary: temporary
   
     Revision 1.222  2016/02/17 08:14:50  brouard
     Summary: Probably last 0.98 stable version 0.98r6
   
     Revision 1.221  2016/02/15 23:35:36  brouard
     Summary: minor bug
   
     Revision 1.219  2016/02/15 00:48:12  brouard
     *** empty log message ***
   
   Revision 1.218  2016/02/12 11:29:23  brouard    Revision 1.218  2016/02/12 11:29:23  brouard
   Summary: 0.99 Back projections    Summary: 0.99 Back projections
   
Line 848  int npar=NPARMAX; Line 860  int npar=NPARMAX;
 int nlstate=2; /* Number of live states */  int nlstate=2; /* Number of live states */
 int ndeath=1; /* Number of dead states */  int ndeath=1; /* Number of dead states */
 int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */  int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
   int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
 int popbased=0;  int popbased=0;
   
 int *wav; /* Number of waves for this individuual 0 is possible */  int *wav; /* Number of waves for this individuual 0 is possible */
Line 976  int *ncodemaxwundef;  /* ncodemax[j]= Nu Line 989  int *ncodemaxwundef;  /* ncodemax[j]= Nu
                              undefined. Usually 3: -1, 0 and 1. */                               undefined. Usually 3: -1, 0 and 1. */
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 double **pmmij, ***probs; /* Global pointer */  double **pmmij, ***probs; /* Global pointer */
 double ***mobaverage; /* New global variable */  double ***mobaverage, ***mobaverages; /* New global variable */
 double *ageexmed,*agecens;  double *ageexmed,*agecens;
 double dateintmean=0;  double dateintmean=0;
   
Line 986  double *agedc; Line 999  double *agedc;
 double  **covar; /**< covar[j,i], value of jth covariate for individual i,  double  **covar; /**< covar[j,i], value of jth covariate for individual i,
                   * covar=matrix(0,NCOVMAX,1,n);                     * covar=matrix(0,NCOVMAX,1,n); 
                   * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */                    * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
   double ***cotvar; /* Time varying covariate */
   double ***cotqvar; /* Time varying quantitative covariate */
   double **coqvar; /* Fixed quantitative covariate */
 double  idx;   double  idx; 
 int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */  int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 int *Tage;  int *Tage;
 int *Ndum; /** Freq of modality (tricode */  int *Ndum; /** Freq of modality (tricode */
 /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */  /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 int **Tvard, *Tprod, cptcovprod, *Tvaraff;  int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
 double *lsurv, *lpop, *tpop;  double *lsurv, *lpop, *tpop;
   
 double ftol=FTOL; /**< Tolerance for computing Max Likelihood */  double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
Line 2286  Earliest age to start was %d-%d=%d, ncvl Line 2302  Earliest age to start was %d-%d=%d, ncvl
     *ncvyear= -( (int)age- (int)agefin);      *ncvyear= -( (int)age- (int)agefin);
     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/      /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
     if(maxmax < ftolpl){      if(maxmax < ftolpl){
       printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);        /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
       free_vector(min,1,nlstate);        free_vector(min,1,nlstate);
       free_vector(max,1,nlstate);        free_vector(max,1,nlstate);
       free_vector(meandiff,1,nlstate);        free_vector(meandiff,1,nlstate);
Line 2325  double **pmij(double **ps, double *cov, Line 2341  double **pmij(double **ps, double *cov,
   /*double t34;*/    /*double t34;*/
   int i,j, nc, ii, jj;    int i,j, nc, ii, jj;
   
         for(i=1; i<= nlstate; i++){    for(i=1; i<= nlstate; i++){
                 for(j=1; j<i;j++){      for(j=1; j<i;j++){
                         for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                                 /*lnpijopii += param[i][j][nc]*cov[nc];*/          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                                 lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                                 /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */          /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                         }        }
                         ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                         /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */        /*        printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                 }      }
                 for(j=i+1; j<=nlstate+ndeath;j++){      for(j=i+1; j<=nlstate+ndeath;j++){
                         for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                                 /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                                 lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                                 /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */          /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                         }        }
                         ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                 }      }
         }    }
       
         for(i=1; i<= nlstate; i++){    for(i=1; i<= nlstate; i++){
                 s1=0;      s1=0;
                 for(j=1; j<i; j++){      for(j=1; j<i; j++){
                         s1+=exp(ps[i][j]); /* In fact sums pij/pii */        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                         /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                 }      }
                 for(j=i+1; j<=nlstate+ndeath; j++){      for(j=i+1; j<=nlstate+ndeath; j++){
                         s1+=exp(ps[i][j]); /* In fact sums pij/pii */        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                         /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                 }      }
                 /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */      /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                 ps[i][i]=1./(s1+1.);      ps[i][i]=1./(s1+1.);
                 /* Computing other pijs */      /* Computing other pijs */
                 for(j=1; j<i; j++)      for(j=1; j<i; j++)
                         ps[i][j]= exp(ps[i][j])*ps[i][i];        ps[i][j]= exp(ps[i][j])*ps[i][i];
                 for(j=i+1; j<=nlstate+ndeath; j++)      for(j=i+1; j<=nlstate+ndeath; j++)
                         ps[i][j]= exp(ps[i][j])*ps[i][i];        ps[i][j]= exp(ps[i][j])*ps[i][i];
                 /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */      /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
         } /* end i */    } /* end i */
       
         for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){    for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                 for(jj=1; jj<= nlstate+ndeath; jj++){      for(jj=1; jj<= nlstate+ndeath; jj++){
                         ps[ii][jj]=0;        ps[ii][jj]=0;
                         ps[ii][ii]=1;        ps[ii][ii]=1;
                 }      }
         }    }
       
       
         /* for(ii=1; ii<= nlstate+ndeath; ii++){ */    /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
         /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */    /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
         /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */    /*    printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
         /*   } */    /*   } */
         /*   printf("\n "); */    /*   printf("\n "); */
         /* } */    /* } */
         /* printf("\n ");printf("%lf ",cov[2]);*/    /* printf("\n ");printf("%lf ",cov[2]);*/
         /*    /*
                 for(i=1; i<= npar; i++) printf("%f ",x[i]);      for(i=1; i<= npar; i++) printf("%f ",x[i]);
                 goto end;*/                  goto end;*/
         return ps;    return ps;
 }  }
   
 /*************** backward transition probabilities ***************/   /*************** backward transition probabilities ***************/ 
Line 2392  double **pmij(double **ps, double *cov, Line 2408  double **pmij(double **ps, double *cov,
 /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */  /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )   double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 {  {
         /* Computes the backward probability at age agefin and covariate ij    /* Computes the backward probability at age agefin and covariate ij
          * and returns in **ps as well as **bmij.     * and returns in **ps as well as **bmij.
          */     */
   int i, ii, j,k;    int i, ii, j,k;
     
         double **out, **pmij();    double **out, **pmij();
         double sumnew=0.;    double sumnew=0.;
   double agefin;    double agefin;
     
         double **dnewm, **dsavm, **doldm;    double **dnewm, **dsavm, **doldm;
         double **bbmij;    double **bbmij;
     
   doldm=ddoldms; /* global pointers */    doldm=ddoldms; /* global pointers */
         dnewm=ddnewms;    dnewm=ddnewms;
         dsavm=ddsavms;    dsavm=ddsavms;
     
         agefin=cov[2];    agefin=cov[2];
         /* bmij *//* age is cov[2], ij is included in cov, but we need for    /* bmij *//* age is cov[2], ij is included in cov, but we need for
                  the observed prevalence (with this covariate ij) */       the observed prevalence (with this covariate ij) */
         dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);    dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
         /* We do have the matrix Px in savm  and we need pij */    /* We do have the matrix Px in savm  and we need pij */
         for (j=1;j<=nlstate+ndeath;j++){    for (j=1;j<=nlstate+ndeath;j++){
                 sumnew=0.; /* w1 p11 + w2 p21 only on live states */      sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                 for (ii=1;ii<=nlstate;ii++){      for (ii=1;ii<=nlstate;ii++){
                         sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];        sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                 } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */      } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                 for (ii=1;ii<=nlstate+ndeath;ii++){      for (ii=1;ii<=nlstate+ndeath;ii++){
                         if(sumnew >= 1.e-10){        if(sumnew >= 1.e-10){
                                 /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */          /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                                 /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */          /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                                 /* }else if(agefin >= agemaxpar+stepm/YEARM){ */          /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                                 /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */          /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                                 /* }else */          /* }else */
                                         doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);          doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                         }else{        }else{
                                 printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);          printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);
                         }        }
                 } /*End ii */      } /*End ii */
         } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */    } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                 /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */    /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
         bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */    bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
         /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */    /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
         /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */    /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
         /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */    /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
         /* left Product of this matrix by diag matrix of prevalences (savm) */    /* left Product of this matrix by diag matrix of prevalences (savm) */
         for (j=1;j<=nlstate+ndeath;j++){    for (j=1;j<=nlstate+ndeath;j++){
                 for (ii=1;ii<=nlstate+ndeath;ii++){      for (ii=1;ii<=nlstate+ndeath;ii++){
                         dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);        dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                 }      }
         } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */    } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
         ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */    ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
         /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */    /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
         /* end bmij */    /* end bmij */
         return ps;     return ps; 
 }  }
 /*************** transition probabilities ***************/   /*************** transition probabilities ***************/ 
   
Line 2651  double ***hpxij(double ***po, int nhstep Line 2667  double ***hpxij(double ***po, int nhstep
   
 /************* Higher Back Matrix Product ***************/  /************* Higher Back Matrix Product ***************/
 /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */  /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
  double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )  double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
 {  {
   /* Computes the transition matrix starting at age 'age' over    /* Computes the transition matrix starting at age 'age' over
      'nhstepm*hstepm*stepm' months (i.e. until       'nhstepm*hstepm*stepm' months (i.e. until
Line 2663  double ***hpxij(double ***po, int nhstep Line 2679  double ***hpxij(double ***po, int nhstep
      Model is determined by parameters x and covariates have to be       Model is determined by parameters x and covariates have to be
      included manually here.       included manually here.
   
      */    */
   
   int i, j, d, h, k;    int i, j, d, h, k;
   double **out, cov[NCOVMAX+1];    double **out, cov[NCOVMAX+1];
   double **newm;    double **newm;
   double agexact;    double agexact;
   double agebegin, ageend;    double agebegin, ageend;
         double **oldm, **savm;    double **oldm, **savm;
   
         oldm=oldms;savm=savms;    oldm=oldms;savm=savms;
   /* Hstepm could be zero and should return the unit matrix */    /* Hstepm could be zero and should return the unit matrix */
   for (i=1;i<=nlstate+ndeath;i++)    for (i=1;i<=nlstate+ndeath;i++)
     for (j=1;j<=nlstate+ndeath;j++){      for (j=1;j<=nlstate+ndeath;j++){
Line 2689  double ***hpxij(double ***po, int nhstep Line 2705  double ***hpxij(double ***po, int nhstep
       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */        /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
       cov[2]=agexact;        cov[2]=agexact;
       if(nagesqr==1)        if(nagesqr==1)
                                 cov[3]= agexact*agexact;          cov[3]= agexact*agexact;
       for (k=1; k<=cptcovn;k++)        for (k=1; k<=cptcovn;k++)
                                 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                         /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */        for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                                 /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */          /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                                 cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                         /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */        for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
                                 cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                         /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                                                   
                                                   
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
       /* Careful transposed matrix */        /* Careful transposed matrix */
                         /* age is in cov[2] */        /* age is in cov[2] */
       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */        /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
                         /*                                               1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */        /*                                                 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\        out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
                                                                          1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);                     1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
       /* if((int)age == 70){ */        /* if((int)age == 70){ */
       /*        printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */        /*        printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
       /*        for(i=1; i<=nlstate+ndeath; i++) { */        /*        for(i=1; i<=nlstate+ndeath; i++) { */
Line 2729  double ***hpxij(double ***po, int nhstep Line 2745  double ***hpxij(double ***po, int nhstep
     }      }
     for(i=1; i<=nlstate+ndeath; i++)      for(i=1; i<=nlstate+ndeath; i++)
       for(j=1;j<=nlstate+ndeath;j++) {        for(j=1;j<=nlstate+ndeath;j++) {
                                 po[i][j][h]=newm[i][j];          po[i][j][h]=newm[i][j];
                                 /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/          /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
       }        }
     /*printf("h=%d ",h);*/      /*printf("h=%d ",h);*/
   } /* end h */    } /* end h */
         /*     printf("\n H=%d \n",h); */    /*     printf("\n H=%d \n",h); */
   return po;    return po;
 }  }
   
Line 2763  double ***hpxij(double ***po, int nhstep Line 2779  double ***hpxij(double ***po, int nhstep
 double func( double *x)  double func( double *x)
 {  {
   int i, ii, j, k, mi, d, kk;    int i, ii, j, k, mi, d, kk;
           int ioffset;
   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];    double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
   double **out;    double **out;
   double sw; /* Sum of weights */    double sw; /* Sum of weights */
   double lli; /* Individual log likelihood */    double lli; /* Individual log likelihood */
   int s1, s2;    int s1, s2;
     int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate */
   double bbh, survp;    double bbh, survp;
   long ipmx;    long ipmx;
   double agexact;    double agexact;
Line 2787  double func( double *x) Line 2805  double func( double *x)
   if(mle==1){    if(mle==1){
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       /* Computes the values of the ncovmodel covariates of the model        /* Computes the values of the ncovmodel covariates of the model
          depending if the covariates are fixed or variying (age dependent) and stores them in cov[]           depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
          Then computes with function pmij which return a matrix p[i][j] giving the elementary probability           Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
          to be observed in j being in i according to the model.           to be observed in j being in i according to the model.
        */         */
         ioffset=2+nagesqr;
       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */        for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
           cov[2+nagesqr+k]=covar[Tvar[k]][i];           cov[++ioffset]=covar[Tvar[k]][i];
       }        }
         for(iqv=1; iqv <= nqv; iqv++){ /* Varying quantitatives covariates */
           /* cov[2+nagesqr+cptcovn+iqv]=varq[mw[mi+1][i]][iqv][i]; */
         }
   
       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]         /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
          is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]            is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
          has been calculated etc */           has been calculated etc */
         /* For an individual i, wav[i] gives the number of effective waves */
         /* We compute the contribution to Likelihood of each effective transition
            mw[mi][i] is real wave of the mi th effectve wave */
         /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
           s2=s[mw[mi+1][i]][i];
           And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
           But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
           meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
         */
       for(mi=1; mi<= wav[i]-1; mi++){        for(mi=1; mi<= wav[i]-1; mi++){
           for(itv=1; itv <= ntv; itv++){ /* Varying dummy covariates */
             cov[++ioffset]=cotvar[mw[mi+1][i]][itv][i];
           }
           for(iqtv=1; iqtv <= nqtv; iqtv++){ /* Varying quantitatives covariates */
             /* cov[2+nagesqr+cptcovn+nqv+ntv+iqtv]=varq[mw[mi+1][i]][iqtv][i]; */
           }
           ioffset=2+nagesqr+cptcovn+nqv+ntv+nqtv;
         for (ii=1;ii<=nlstate+ndeath;ii++)          for (ii=1;ii<=nlstate+ndeath;ii++)
           for (j=1;j<=nlstate+ndeath;j++){            for (j=1;j<=nlstate+ndeath;j++){
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
Line 2808  double func( double *x) Line 2847  double func( double *x)
           agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;            agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
           cov[2]=agexact;            cov[2]=agexact;
           if(nagesqr==1)            if(nagesqr==1)
             cov[3]= agexact*agexact;              cov[3]= agexact*agexact;  /* Should be changed here */
           for (kk=1; kk<=cptcovage;kk++) {            for (kk=1; kk<=cptcovage;kk++) {
             cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
           }            }
Line 3668  void pstamp(FILE *fichier) Line 3707  void pstamp(FILE *fichier)
 }  }
   
 /************ Frequencies ********************/  /************ Frequencies ********************/
 void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \   void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\                                                                           int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],  \
                   int firstpass,  int lastpass, int stepm, int weightopt, char model[])                                                                           int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 {  /* Some frequencies */   {  /* Some frequencies */
       
   int i, m, jk, j1, bool, z1,j;           int i, m, jk, j1, bool, z1,j;
   int mi; /* Effective wave */           int iind=0, iage=0;
   int first;           int mi; /* Effective wave */
   double ***freq; /* Frequencies */           int first;
   double *pp, **prop;           double ***freq; /* Frequencies */
   double pos,posprop, k2, dateintsum=0,k2cpt=0;           double *pp, **prop, *posprop, *pospropt;
   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];           double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
   double agebegin, ageend;           char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                double agebegin, ageend;
   pp=vector(1,nlstate);      
   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE);            pp=vector(1,nlstate);
   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */           prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
   strcpy(fileresp,"P_");           posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
   strcat(fileresp,fileresu);           pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
   /*strcat(fileresphtm,fileresu);*/           /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
   if((ficresp=fopen(fileresp,"w"))==NULL) {           strcpy(fileresp,"P_");
     printf("Problem with prevalence resultfile: %s\n", fileresp);           strcat(fileresp,fileresu);
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);           /*strcat(fileresphtm,fileresu);*/
     exit(0);           if((ficresp=fopen(fileresp,"w"))==NULL) {
   }                   printf("Problem with prevalence resultfile: %s\n", fileresp);
                    fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                    exit(0);
            }
   
   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));           strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {           if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));                   printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));                   fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
     fflush(ficlog);                   fflush(ficlog);
     exit(70);                    exit(70); 
   }           }
   else{           else{
     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \                   fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 <hr size=\"2\" color=\"#EC5E5E\"> \n\  <hr size=\"2\" color=\"#EC5E5E\"> \n\
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
           fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);                                                   fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
   }           }
     fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);           fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
           
   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));           strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {           if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));                   printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));                   fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
     fflush(ficlog);                   fflush(ficlog);
     exit(70);                    exit(70); 
   }           }
   else{           else{
     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \                   fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 <hr size=\"2\" color=\"#EC5E5E\"> \n\  <hr size=\"2\" color=\"#EC5E5E\"> \n\
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
           fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);                                                   fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
   }           }
   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);           fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
   
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);           freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
   j1=0;           j1=0;
       
   j=cptcoveff;           j=cptcoveff;
   if (cptcovn<1) {j=1;ncodemax[1]=1;}           if (cptcovn<1) {j=1;ncodemax[1]=1;}
   
   first=1;           first=1;
   
   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */           /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);                          reference=low_education V1=0,V2=0
         scanf("%d", i);*/                          med_educ                V1=1 V2=0, 
       for (i=-5; i<=nlstate+ndeath; i++)                            high_educ               V1=0 V2=1
         for (jk=-5; jk<=nlstate+ndeath; jk++)                            Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
           for(m=iagemin; m <= iagemax+3; m++)           */
             freq[i][jk][m]=0;  
                  for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
       for (i=1; i<=nlstate; i++)                     posproptt=0.;
         for(m=iagemin; m <= iagemax+3; m++)                   /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
           prop[i][m]=0;                           scanf("%d", i);*/
                          for (i=-5; i<=nlstate+ndeath; i++)  
       dateintsum=0;                           for (jk=-5; jk<=nlstate+ndeath; jk++)  
       k2cpt=0;                                   for(m=iagemin; m <= iagemax+3; m++)
       for (i=1; i<=imx; i++) { /* For each individual i */                                           freq[i][jk][m]=0;
         bool=1;        
         if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */                   for (i=1; i<=nlstate; i++)  {
           for (z1=1; z1<=cptcoveff; z1++)                                  for(m=iagemin; m <= iagemax+3; m++)
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){                                   prop[i][m]=0;
                 /* Tests if the value of each of the covariates of i is equal to filter j1 */                           posprop[i]=0;
               bool=0;                           pospropt[i]=0;
               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n",                    }
         
                    dateintsum=0;
                    k2cpt=0;
   
                    for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                            bool=1;
                            if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                                    for (z1=1; z1<=cptcoveff; z1++) {      
                                            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                                                    /* Tests if the value of each of the covariates of i is equal to filter j1 */
                                                    bool=0;
                                                    /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n", 
                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),                  bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/                  j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/                                                   /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
             }                                            } 
         } /* cptcovn > 0 */                                   } /* end z1 */
                            } /* cptcovn > 0 */
         if (bool==1){  
           /* for(m=firstpass; m<=lastpass; m++){ */                           if (bool==1){
           for(mi=1; mi<wav[i];mi++){                                   /* for(m=firstpass; m<=lastpass; m++){ */
             m=mw[mi][i];                                   for(mi=1; mi<wav[iind];mi++){
             /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]                                           m=mw[mi][iind];
                and mw[mi+1][i]. dh depends on stepm. */                                           /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
             agebegin=agev[m][i]; /* Age at beginning of wave before transition*/                                                          and mw[mi+1][iind]. dh depends on stepm. */
             ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */                                           agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
             if(m >=firstpass && m <=lastpass){                                           ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
               k2=anint[m][i]+(mint[m][i]/12.);                                           if(m >=firstpass && m <=lastpass){
               /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/                                                   k2=anint[m][iind]+(mint[m][iind]/12.);
               if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */                                                   /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
               if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */                                                   if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
               if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */                                                   if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */                                                   if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
               if (m<lastpass) {                                                           prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                 /* if(s[m][i]==4 && s[m+1][i]==4) */                                                   if (m<lastpass) {
                 /*   printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */                                                           /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                 if(s[m][i]==-1)                                                           /*   printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind]); */
                   printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));                                                           if(s[m][iind]==-1)
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */                                                                   printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind],agebegin, ageend, (int)((agebegin+ageend)/2.));
                 /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */                                                           freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */                                                           /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
               }                                                           freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
             }                                                     }
             if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {                                           }  
               dateintsum=dateintsum+k2;                                           if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
               k2cpt++;                                                   dateintsum=dateintsum+k2;
               /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */                                                   k2cpt++;
             }                                                   /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
             /*}*/                                           }
           } /* end m */                                           /*}*/
         } /* end bool */                                   } /* end m */
       } /* end i = 1 to imx */                           } /* end bool */
                           } /* end iind = 1 to imx */
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/         /* prop[s][age] is feeded for any initial and valid live state as well as
       pstamp(ficresp);                                          freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
       if  (cptcovn>0) {  
         fprintf(ficresp, "\n#********** Variable ");   
         fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable ");                    /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
         fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable ");                    pstamp(ficresp);
         for (z1=1; z1<=cptcoveff; z1++){                   if  (cptcovn>0) {
           fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);                           fprintf(ficresp, "\n#********** Variable "); 
           fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);                           fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
           fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);                           fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
         }                           for (z1=1; z1<=cptcoveff; z1++){
           fprintf(ficresp, "**********\n#");                                   fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficresphtm, "**********</h3>\n");                                   fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficresphtmfr, "**********</h3>\n");                                   fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficlog, "\n#********** Variable ");                            }
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);                           fprintf(ficresp, "**********\n#");
         fprintf(ficlog, "**********\n");                           fprintf(ficresphtm, "**********</h3>\n");
       }                           fprintf(ficresphtmfr, "**********</h3>\n");
       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");                           fprintf(ficlog, "\n#********** Variable "); 
       for(i=1; i<=nlstate;i++) {                           for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);                           fprintf(ficlog, "**********\n");
         fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);                   }
       }                   fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
       fprintf(ficresp, "\n");                   for(i=1; i<=nlstate;i++) {
       fprintf(ficresphtm, "\n");                           fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                                  fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
       /* Header of frequency table by age */                   }
       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");                   fprintf(ficresp, "\n");
       fprintf(ficresphtmfr,"<th>Age</th> ");                   fprintf(ficresphtm, "\n");
       for(jk=-1; jk <=nlstate+ndeath; jk++){  
         for(m=-1; m <=nlstate+ndeath; m++){  
           if(jk!=0 && m!=0)  
             fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);  
         }  
       }  
       fprintf(ficresphtmfr, "\n");  
               
       /* For each age */                   /* Header of frequency table by age */
       for(i=iagemin; i <= iagemax+3; i++){                   fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
         fprintf(ficresphtm,"<tr>");                   fprintf(ficresphtmfr,"<th>Age</th> ");
         if(i==iagemax+1){                   for(jk=-1; jk <=nlstate+ndeath; jk++){
           fprintf(ficlog,"1");                           for(m=-1; m <=nlstate+ndeath; m++){
           fprintf(ficresphtmfr,"<tr><th>0</th> ");                                   if(jk!=0 && m!=0)
         }else if(i==iagemax+2){                                           fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
           fprintf(ficlog,"0");                           }
           fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");                   }
         }else if(i==iagemax+3){                   fprintf(ficresphtmfr, "\n");
           fprintf(ficlog,"Total");        
           fprintf(ficresphtmfr,"<tr><th>Total</th> ");                   /* For each age */
         }else{                   for(iage=iagemin; iage <= iagemax+3; iage++){
           if(first==1){                           fprintf(ficresphtm,"<tr>");
             first=0;                           if(iage==iagemax+1){
             printf("See log file for details...\n");                                   fprintf(ficlog,"1");
           }                                   fprintf(ficresphtmfr,"<tr><th>0</th> ");
           fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);                           }else if(iage==iagemax+2){
           fprintf(ficlog,"Age %d", i);                                   fprintf(ficlog,"0");
         }                                   fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
         for(jk=1; jk <=nlstate ; jk++){                           }else if(iage==iagemax+3){
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)                                   fprintf(ficlog,"Total");
             pp[jk] += freq[jk][m][i];                                    fprintf(ficresphtmfr,"<tr><th>Total</th> ");
         }                           }else{
         for(jk=1; jk <=nlstate ; jk++){                                   if(first==1){
           for(m=-1, pos=0; m <=0 ; m++)                                           first=0;
             pos += freq[jk][m][i];                                           printf("See log file for details...\n");
           if(pp[jk]>=1.e-10){                                   }
             if(first==1){                                   fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
               printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);                                   fprintf(ficlog,"Age %d", iage);
             }                           }
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);                           for(jk=1; jk <=nlstate ; jk++){
           }else{                                   for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
             if(first==1)                                           pp[jk] += freq[jk][m][iage]; 
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);                           }
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);                           for(jk=1; jk <=nlstate ; jk++){
           }                                   for(m=-1, pos=0; m <=0 ; m++)
         }                                           pos += freq[jk][m][iage];
                                    if(pp[jk]>=1.e-10){
         for(jk=1; jk <=nlstate ; jk++){                                           if(first==1){
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)                                                   printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
             pp[jk] += freq[jk][m][i];                                           }
         }                                                  fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){                                   }else{
           pos += pp[jk];                                           if(first==1)
           posprop += prop[jk][i];                                                   printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
         }                                           fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
         for(jk=1; jk <=nlstate ; jk++){                                   }
           if(pos>=1.e-5){                           }
             if(first==1)  
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);                           for(jk=1; jk <=nlstate ; jk++){ 
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);                                   /* posprop[jk]=0; */
           }else{                                   for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
             if(first==1)                                           pp[jk] += freq[jk][m][iage];
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);                           }      /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);  
           }                           for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
           if( i <= iagemax){                                   pos += pp[jk]; /* pos is the total number of transitions until this age */
             if(pos>=1.e-5){                                   posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);                                                                                                                                                                           from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
               fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);                                   pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
               /*probs[i][jk][j1]= pp[jk]/pos;*/                                                                                                                                                                           from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/                           }
             }                           for(jk=1; jk <=nlstate ; jk++){
             else{                                   if(pos>=1.e-5){
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);                                           if(first==1)
               fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);                                                   printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             }                                           fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
           }                                   }else{
         }                                           if(first==1)
                                                            printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
         for(jk=-1; jk <=nlstate+ndeath; jk++){                                           fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
           for(m=-1; m <=nlstate+ndeath; m++){                                   }
             if(freq[jk][m][i] !=0 ) { /* minimizing output */                                   if( iage <= iagemax){
               if(first==1){                                           if(pos>=1.e-5){
                 printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);                                                   fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
               }                                                   fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);                                                   /*probs[iage][jk][j1]= pp[jk]/pos;*/
             }                                                   /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
             if(jk!=0 && m!=0)                                           }
               fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);                                           else{
           }                                                   fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
         }                                                   fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
         fprintf(ficresphtmfr,"</tr>\n ");                                           }
         if(i <= iagemax){                                   }
           fprintf(ficresp,"\n");                                   pospropt[jk] +=posprop[jk];
           fprintf(ficresphtm,"</tr>\n");                           } /* end loop jk */
         }                           /* pospropt=0.; */
         if(first==1)                           for(jk=-1; jk <=nlstate+ndeath; jk++){
           printf("Others in log...\n");                                   for(m=-1; m <=nlstate+ndeath; m++){
         fprintf(ficlog,"\n");                                           if(freq[jk][m][iage] !=0 ) { /* minimizing output */
       } /* end loop i */                                                   if(first==1){
       fprintf(ficresphtm,"</table>\n");                                                           printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
       fprintf(ficresphtmfr,"</table>\n");                                                   }
       /*}*/                                                   fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
   } /* end j1 */                                           }
   dateintmean=dateintsum/k2cpt;                                            if(jk!=0 && m!=0)
                                                     fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
   fclose(ficresp);                                   }
   fclose(ficresphtm);                           } /* end loop jk */
   fclose(ficresphtmfr);                           posproptt=0.; 
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);                           for(jk=1; jk <=nlstate; jk++){
   free_vector(pp,1,nlstate);                                   posproptt += pospropt[jk];
   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);                           }
   /* End of Freq */                           fprintf(ficresphtmfr,"</tr>\n ");
 }                           if(iage <= iagemax){
                                    fprintf(ficresp,"\n");
                                    fprintf(ficresphtm,"</tr>\n");
                            }
                            if(first==1)
                                    printf("Others in log...\n");
                            fprintf(ficlog,"\n");
                    } /* end loop age iage */
                    fprintf(ficresphtm,"<tr><th>Tot</th>");
                    for(jk=1; jk <=nlstate ; jk++){
                            if(posproptt < 1.e-5){
                                    fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);  
                            }else{
                                    fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);   
                            }
                    }
                    fprintf(ficresphtm,"</tr>\n");
                    fprintf(ficresphtm,"</table>\n");
                    fprintf(ficresphtmfr,"</table>\n");
                    if(posproptt < 1.e-5){
                            fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                            fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                            fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                            invalidvarcomb[j1]=1;
                    }else{
                            fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                            invalidvarcomb[j1]=0;
                    }
                    fprintf(ficresphtmfr,"</table>\n");
            } /* end selected combination of covariate j1 */
            dateintmean=dateintsum/k2cpt; 
                    
            fclose(ficresp);
            fclose(ficresphtm);
            fclose(ficresphtmfr);
            free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
            free_vector(pospropt,1,nlstate);
            free_vector(posprop,1,nlstate);
            free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
            free_vector(pp,1,nlstate);
            /* End of Freq */
    }
   
 /************ Prevalence ********************/  /************ Prevalence ********************/
 void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)   void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)
 {     {  
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people     /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
      in each health status at the date of interview (if between dateprev1 and dateprev2).        in each health status at the date of interview (if between dateprev1 and dateprev2).
      We still use firstpass and lastpass as another selection.        We still use firstpass and lastpass as another selection.
   */     */
     
   int i, m, jk, j1, bool, z1,j;     int i, m, jk, j1, bool, z1,j;
   int mi; /* Effective wave */     int mi; /* Effective wave */
   int iage;     int iage;
   double agebegin, ageend;     double agebegin, ageend;
   
   double **prop;     double **prop;
   double posprop;      double posprop; 
   double  y2; /* in fractional years */     double  y2; /* in fractional years */
   int iagemin, iagemax;     int iagemin, iagemax;
   int first; /** to stop verbosity which is redirected to log file */     int first; /** to stop verbosity which is redirected to log file */
   
   iagemin= (int) agemin;     iagemin= (int) agemin;
   iagemax= (int) agemax;     iagemax= (int) agemax;
   /*pp=vector(1,nlstate);*/     /*pp=vector(1,nlstate);*/
   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE);      prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/     /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
   j1=0;     j1=0;
       
   /*j=cptcoveff;*/     /*j=cptcoveff;*/
   if (cptcovn<1) {j=1;ncodemax[1]=1;}     if (cptcovn<1) {j=1;ncodemax[1]=1;}
       
   first=1;     first=1;
   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){     for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
     for (i=1; i<=nlstate; i++)         for (i=1; i<=nlstate; i++)  
       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)         for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                                 prop[i][iage]=0.0;           prop[i][iage]=0.0;
           
     for (i=1; i<=imx; i++) { /* Each individual */       for (i=1; i<=imx; i++) { /* Each individual */
       bool=1;         bool=1;
       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */         if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                                 for (z1=1; z1<=cptcoveff; z1++)            for (z1=1; z1<=cptcoveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
                                         if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                                                 bool=0;               bool=0;
       }          } 
       if (bool==1) {          if (bool==1) { /* For this combination of covariates values, this individual fits */
                                 /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */           /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                                 for(mi=1; mi<wav[i];mi++){           for(mi=1; mi<wav[i];mi++){
                                         m=mw[mi][i];             m=mw[mi][i];
                                         agebegin=agev[m][i]; /* Age at beginning of wave before transition*/             agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                                         /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */             /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                                         if(m >=firstpass && m <=lastpass){             if(m >=firstpass && m <=lastpass){
                                                 y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */               y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                                                 if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */               if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                                                         if(agev[m][i]==0) agev[m][i]=iagemax+1;                 if(agev[m][i]==0) agev[m][i]=iagemax+1;
                                                         if(agev[m][i]==1) agev[m][i]=iagemax+2;                 if(agev[m][i]==1) agev[m][i]=iagemax+2;
                                                         if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){                 if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                                                                 printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m);                    printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m); 
                                                                 exit(1);                   exit(1);
                                                         }                 }
                                                         if (s[m][i]>0 && s[m][i]<=nlstate) {                  if (s[m][i]>0 && s[m][i]<=nlstate) { 
                                                                 /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/                   /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
                                                                 prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */                   prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                                                                 prop[s[m][i]][iagemax+3] += weight[i];                    prop[s[m][i]][iagemax+3] += weight[i]; 
                                                         } /* end valid statuses */                  } /* end valid statuses */ 
                                                 } /* end selection of dates */               } /* end selection of dates */
                                         } /* end selection of waves */             } /* end selection of waves */
                                 } /* end effective waves */           } /* end effective waves */
       } /* end bool */         } /* end bool */
     }       }
     for(i=iagemin; i <= iagemax+3; i++){         for(i=iagemin; i <= iagemax+3; i++){  
       for(jk=1,posprop=0; jk <=nlstate ; jk++) {          for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                                 posprop += prop[jk][i];            posprop += prop[jk][i]; 
       }          } 
               
       for(jk=1; jk <=nlstate ; jk++){                for(jk=1; jk <=nlstate ; jk++){      
                                 if( i <=  iagemax){            if( i <=  iagemax){ 
                                         if(posprop>=1.e-5){              if(posprop>=1.e-5){ 
                                                 probs[i][jk][j1]= prop[jk][i]/posprop;               probs[i][jk][j1]= prop[jk][i]/posprop;
                                         } else{             } else{
                                                 if(first==1){               if(first==1){
                                                         first=0;                 first=0;
                                                         printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);                 printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
                                                 }               }
                                         }             }
                                 }            } 
       }/* end jk */          }/* end jk */ 
     }/* end i */        }/* end i */ 
     /*} *//* end i1 */       /*} *//* end i1 */
   } /* end j1 */     } /* end j1 */
       
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/     /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
   /*free_vector(pp,1,nlstate);*/     /*free_vector(pp,1,nlstate);*/
   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);     free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 }  /* End of prevalence */   }  /* End of prevalence */
   
 /************* Waves Concatenation ***************/  /************* Waves Concatenation ***************/
   
Line 4061  void  concatwav(int wav[], int **dh, int Line 4149  void  concatwav(int wav[], int **dh, int
     m=firstpass;      m=firstpass;
     while(s[m][i] <= nlstate){  /* a live state */      while(s[m][i] <= nlstate){  /* a live state */
       if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */        if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
         mw[++mi][i]=m;                                  mw[++mi][i]=m;
       }        }
       if(m >=lastpass){        if(m >=lastpass){
         if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){                                  if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
           if(firsthree == 0){                                          if(firsthree == 0){
             printf("Information! Unknown health status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);                                                  printf("Information! Unknown health status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
             firsthree=1;                                                  firsthree=1;
           }                                          }
           fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);                                          fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
           mw[++mi][i]=m;                                          mw[++mi][i]=m;
         }                                  }
         if(s[m][i]==-2){ /* Vital status is really unknown */                                  if(s[m][i]==-2){ /* Vital status is really unknown */
           nbwarn++;                                          nbwarn++;
           if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */                                          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
             printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);                                                  printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
             fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);                                                  fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
           }                                          }
           break;                                          break;
         }                                  }
         break;                                  break;
       }        }
       else        else
         m++;                                  m++;
     }/* end while */      }/* end while */
           
     /* After last pass */      /* After last pass */
     if (s[m][i] > nlstate){  /* In a death state */      if (s[m][i] > nlstate){  /* In a death state */
       mi++;     /* Death is another wave */        mi++;     /* Death is another wave */
       /* if(mi==0)  never been interviewed correctly before death */        /* if(mi==0)  never been interviewed correctly before death */
          /* Only death is a correct wave */                          /* Only death is a correct wave */
       mw[mi][i]=m;        mw[mi][i]=m;
     }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */      }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
       /* m++; */        /* m++; */
Line 4099  void  concatwav(int wav[], int **dh, int Line 4187  void  concatwav(int wav[], int **dh, int
       /* mw[mi][i]=m; */        /* mw[mi][i]=m; */
       nberr++;        nberr++;
       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */        if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
         if(firstwo==0){                                  if(firstwo==0){
           printf("Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );                                          printf("Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
           firstwo=1;                                          firstwo=1;
         }                                  }
         fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );                                  fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
       }else{ /* end date of interview is known */        }else{ /* end date of interview is known */
         /* death is known but not confirmed by death status at any wave */                                  /* death is known but not confirmed by death status at any wave */
         if(firstfour==0){                                  if(firstfour==0){
           printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );                                          printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
           firstfour=1;                                          firstfour=1;
         }                                  }
         fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );                                  fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
       }        }
     }      }
     wav[i]=mi;      wav[i]=mi;
     if(mi==0){      if(mi==0){
       nbwarn++;        nbwarn++;
       if(first==0){        if(first==0){
         printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);                                  printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
         first=1;                                  first=1;
       }        }
       if(first==1){        if(first==1){
         fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);                                  fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
       }        }
     } /* end mi==0 */      } /* end mi==0 */
   } /* End individuals */    } /* End individuals */
   /* wav and mw are no more changed */    /* wav and mw are no more changed */
           
       
   for(i=1; i<=imx; i++){    for(i=1; i<=imx; i++){
     for(mi=1; mi<wav[i];mi++){      for(mi=1; mi<wav[i];mi++){
       if (stepm <=0)        if (stepm <=0)
         dh[mi][i]=1;                                  dh[mi][i]=1;
       else{        else{
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */                                  if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
           if (agedc[i] < 2*AGESUP) {                                          if (agedc[i] < 2*AGESUP) {
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);                                                   j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
             if(j==0) j=1;  /* Survives at least one month after exam */                                                  if(j==0) j=1;  /* Survives at least one month after exam */
             else if(j<0){                                                  else if(j<0){
               nberr++;                                                          nberr++;
               printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);                                                          printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
               j=1; /* Temporary Dangerous patch */                                                          j=1; /* Temporary Dangerous patch */
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);                                                          printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
               fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);                                                          fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
               fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);                                                          fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
             }                                                  }
             k=k+1;                                                  k=k+1;
             if (j >= jmax){                                                  if (j >= jmax){
               jmax=j;                                                          jmax=j;
               ijmax=i;                                                          ijmax=i;
             }                                                  }
             if (j <= jmin){                                                  if (j <= jmin){
               jmin=j;                                                          jmin=j;
               ijmin=i;                                                          ijmin=i;
             }                                                  }
             sum=sum+j;                                                  sum=sum+j;
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/                                                  /*if (j<0) printf("j=%d num=%d \n",j,i);*/
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/                                                  /*        printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
           }                                          }
         }                                  }
         else{                                  else{
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));                                          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */  /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */
                                           
           k=k+1;                                          k=k+1;
           if (j >= jmax) {                                          if (j >= jmax) {
             jmax=j;                                                  jmax=j;
             ijmax=i;                                                  ijmax=i;
           }                                          }
           else if (j <= jmin){                                          else if (j <= jmin){
             jmin=j;                                                  jmin=j;
             ijmin=i;                                                  ijmin=i;
           }                                          }
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */                                          /*          if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
           /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/                                          /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
           if(j<0){                                          if(j<0){
             nberr++;                                                  nberr++;
             printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);                                                  printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
             fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);                                                  fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
           }                                          }
           sum=sum+j;                                          sum=sum+j;
         }                                  }
         jk= j/stepm;                                  jk= j/stepm;
         jl= j -jk*stepm;                                  jl= j -jk*stepm;
         ju= j -(jk+1)*stepm;                                  ju= j -(jk+1)*stepm;
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */                                  if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
           if(jl==0){                                          if(jl==0){
             dh[mi][i]=jk;                                                  dh[mi][i]=jk;
             bh[mi][i]=0;                                                  bh[mi][i]=0;
           }else{ /* We want a negative bias in order to only have interpolation ie                                          }else{ /* We want a negative bias in order to only have interpolation ie
                   * to avoid the price of an extra matrix product in likelihood */                                                                          * to avoid the price of an extra matrix product in likelihood */
             dh[mi][i]=jk+1;                                                  dh[mi][i]=jk+1;
             bh[mi][i]=ju;                                                  bh[mi][i]=ju;
           }                                          }
         }else{                                  }else{
           if(jl <= -ju){                                          if(jl <= -ju){
             dh[mi][i]=jk;                                                  dh[mi][i]=jk;
             bh[mi][i]=jl;       /* bias is positive if real duration                                                  bh[mi][i]=jl;   /* bias is positive if real duration
                                  * is higher than the multiple of stepm and negative otherwise.                                                                                                           * is higher than the multiple of stepm and negative otherwise.
                                  */                                                                                                           */
           }                                          }
           else{                                          else{
             dh[mi][i]=jk+1;                                                  dh[mi][i]=jk+1;
             bh[mi][i]=ju;                                                  bh[mi][i]=ju;
           }                                          }
           if(dh[mi][i]==0){                                          if(dh[mi][i]==0){
             dh[mi][i]=1; /* At least one step */                                                  dh[mi][i]=1; /* At least one step */
             bh[mi][i]=ju; /* At least one step */                                                  bh[mi][i]=ju; /* At least one step */
             /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/                                                  /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/
           }                                          }
         } /* end if mle */                                  } /* end if mle */
       }        }
     } /* end wave */      } /* end wave */
   }    }
Line 4219  void  concatwav(int wav[], int **dh, int Line 4307  void  concatwav(int wav[], int **dh, int
  }   }
   
 /*********** Tricode ****************************/  /*********** Tricode ****************************/
 void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)   void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 {  {
   /**< Uses cptcovn+2*cptcovprod as the number of covariates */    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
   /*      Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1     /*      Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
    * Boring subroutine which should only output nbcode[Tvar[j]][k]     * Boring subroutine which should only output nbcode[Tvar[j]][k]
    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)     * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
    * nbcode[Tvar[j]][1]=      * nbcode[Tvar[5]][1]= nbcode[2][1]=0, nbcode[2][2]=1 (usually);
   */    */
   
   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
Line 4234  void tricode(int *Tvar, int **nbcode, in Line 4322  void tricode(int *Tvar, int **nbcode, in
   int modmincovj=0; /* Modality min of covariates j */    int modmincovj=0; /* Modality min of covariates j */
   
   
   cptcoveff=0;     /* cptcoveff=0;  */
           *cptcov=0;
     
   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
   
Line 4242  void tricode(int *Tvar, int **nbcode, in Line 4331  void tricode(int *Tvar, int **nbcode, in
   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */    for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
     for (k=-1; k < maxncov; k++) Ndum[k]=0;      for (k=-1; k < maxncov; k++) Ndum[k]=0;
     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the       for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
                                modality of this covariate Vj*/                                                                                                                                   modality of this covariate Vj*/ 
       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i        ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                                     * If product of Vn*Vm, still boolean *:                                                                                                                                                  * If product of Vn*Vm, still boolean *:
                                     * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables                                                                                                                                                  * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                                     * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */                                                                                                                                                  * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the        /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                                       modality of the nth covariate of individual i. */                                        modality of the nth covariate of individual i. */
       if (ij > modmaxcovj)        if (ij > modmaxcovj)
         modmaxcovj=ij;           modmaxcovj=ij; 
       else if (ij < modmincovj)         else if (ij < modmincovj) 
         modmincovj=ij;                                   modmincovj=ij; 
       if ((ij < -1) && (ij > NCOVMAX)){        if ((ij < -1) && (ij > NCOVMAX)){
         printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );                                  printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
         exit(1);                                  exit(1);
       }else        }else
       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/        Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */        /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
Line 4273  void tricode(int *Tvar, int **nbcode, in Line 4362  void tricode(int *Tvar, int **nbcode, in
       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);        printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);        fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */        if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
         if( k != -1){                                  if( k != -1){
           ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th                                          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                              covariate for which somebody answered excluding                                                                                                                    covariate for which somebody answered excluding 
                              undefined. Usually 2: 0 and 1. */                                                                                                                   undefined. Usually 2: 0 and 1. */
         }                                  }
         ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th                                  ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                              covariate for which somebody answered including                                                                                                                                   covariate for which somebody answered including 
                              undefined. Usually 3: -1, 0 and 1. */                                                                                                                                  undefined. Usually 3: -1, 0 and 1. */
       }        }
       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for        /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
          historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */                                   historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
     } /* Ndum[-1] number of undefined modalities */      } /* Ndum[-1] number of undefined modalities */
                   
     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */      /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.       /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;         If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
Line 4302  void tricode(int *Tvar, int **nbcode, in Line 4391  void tricode(int *Tvar, int **nbcode, in
     ij=0; /* ij is similar to i but can jump over null modalities */      ij=0; /* ij is similar to i but can jump over null modalities */
     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/      for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
         if (Ndum[i] == 0) { /* If nobody responded to this modality k */          if (Ndum[i] == 0) { /* If nobody responded to this modality k */
           break;                                  break;
         }                          }
         ij++;          ij++;
         nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/          nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
         cptcode = ij; /* New max modality for covar j */          cptcode = ij; /* New max modality for covar j */
Line 4324  void tricode(int *Tvar, int **nbcode, in Line 4413  void tricode(int *Tvar, int **nbcode, in
     /*   }  /\* end of loop on modality k *\/ */      /*   }  /\* end of loop on modality k *\/ */
   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/      } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
       
  for (k=-1; k< maxncov; k++) Ndum[k]=0;           for (k=-1; k< maxncov; k++) Ndum[k]=0; 
       
   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */     for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/                   /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */                   ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
    Ndum[ij]++; /* Might be supersed V1 + V1*age */                  Ndum[ij]++; /* Might be supersed V1 + V1*age */
  }           } 
           
  ij=0;          ij=0;
  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */          for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/                  /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
    if((Ndum[i]!=0) && (i<=ncovcol)){                  if((Ndum[i]!=0) && (i<=ncovcol)){
      ij++;                          ij++;
      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/                          /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
      Tvaraff[ij]=i; /*For printing (unclear) */                          Tvaraff[ij]=i; /*For printing (unclear) */
    }else{                  }else{
        /* Tvaraff[ij]=0; */                          /* Tvaraff[ij]=0; */
    }                  }
  }          }
  /* ij--; */          /* ij--; */
  cptcoveff=ij; /*Number of total covariates*/          /* cptcoveff=ij; /\*Number of total covariates*\/ */
           *cptcov=ij; /*Number of total covariates*/
           
 }  }
   
   
Line 4463  void cvevsij(double ***eij, double x[], Line 4553  void cvevsij(double ***eij, double x[],
   
 {  {
   /* Covariances of health expectancies eij and of total life expectancies according    /* Covariances of health expectancies eij and of total life expectancies according
    to initial status i, ei. .       to initial status i, ei. .
   */    */
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
   int nhstepma, nstepma; /* Decreasing with age */    int nhstepma, nstepma; /* Decreasing with age */
Line 4569  void cvevsij(double ***eij, double x[], Line 4659  void cvevsij(double ***eij, double x[],
        decrease memory allocation */         decrease memory allocation */
     for(theta=1; theta <=npar; theta++){      for(theta=1; theta <=npar; theta++){
       for(i=1; i<=npar; i++){         for(i=1; i<=npar; i++){ 
                                 xp[i] = x[i] + (i==theta ?delti[theta]:0);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
                                 xm[i] = x[i] - (i==theta ?delti[theta]:0);          xm[i] = x[i] - (i==theta ?delti[theta]:0);
       }        }
       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);          hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);          hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                                                   
       for(j=1; j<= nlstate; j++){        for(j=1; j<= nlstate; j++){
                                 for(i=1; i<=nlstate; i++){          for(i=1; i<=nlstate; i++){
                                         for(h=0; h<=nhstepm-1; h++){            for(h=0; h<=nhstepm-1; h++){
                                                 gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;              gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                                                 gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;              gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                                         }            }
                                 }          }
       }        }
                                                   
       for(ij=1; ij<= nlstate*nlstate; ij++)        for(ij=1; ij<= nlstate*nlstate; ij++)
                                 for(h=0; h<=nhstepm-1; h++){          for(h=0; h<=nhstepm-1; h++){
                                         gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                                 }          }
     }/* End theta */      }/* End theta */
           
           
     for(h=0; h<=nhstepm-1; h++)      for(h=0; h<=nhstepm-1; h++)
       for(j=1; j<=nlstate*nlstate;j++)        for(j=1; j<=nlstate*nlstate;j++)
                                 for(theta=1; theta <=npar; theta++)          for(theta=1; theta <=npar; theta++)
                                         trgradg[h][j][theta]=gradg[h][theta][j];            trgradg[h][j][theta]=gradg[h][theta][j];
           
                                   
                 for(ij=1;ij<=nlstate*nlstate;ij++)      for(ij=1;ij<=nlstate*nlstate;ij++)
       for(ji=1;ji<=nlstate*nlstate;ji++)        for(ji=1;ji<=nlstate*nlstate;ji++)
                                 varhe[ij][ji][(int)age] =0.;          varhe[ij][ji][(int)age] =0.;
                                   
                 printf("%d|",(int)age);fflush(stdout);      printf("%d|",(int)age);fflush(stdout);
                 fprintf(ficlog,"%d|",(int)age);fflush(ficlog);      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                 for(h=0;h<=nhstepm-1;h++){      for(h=0;h<=nhstepm-1;h++){
       for(k=0;k<=nhstepm-1;k++){        for(k=0;k<=nhstepm-1;k++){
                                 matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);          matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                                 matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                                 for(ij=1;ij<=nlstate*nlstate;ij++)          for(ij=1;ij<=nlstate*nlstate;ij++)
                                         for(ji=1;ji<=nlstate*nlstate;ji++)            for(ji=1;ji<=nlstate*nlstate;ji++)
                                                 varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
       }        }
     }      }
                                   
Line 4617  void cvevsij(double ***eij, double x[], Line 4707  void cvevsij(double ***eij, double x[],
     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);        hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
     for(i=1; i<=nlstate;i++)      for(i=1; i<=nlstate;i++)
       for(j=1; j<=nlstate;j++)        for(j=1; j<=nlstate;j++)
                                 for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                                         eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                                                                                   
                                         /* 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]);*/            /* 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]);*/
                                                                                   
                                 }          }
                                   
     fprintf(ficresstdeij,"%3.0f",age );      fprintf(ficresstdeij,"%3.0f",age );
     for(i=1; i<=nlstate;i++){      for(i=1; i<=nlstate;i++){
       eip=0.;        eip=0.;
       vip=0.;        vip=0.;
       for(j=1; j<=nlstate;j++){        for(j=1; j<=nlstate;j++){
                                 eip += eij[i][j][(int)age];          eip += eij[i][j][(int)age];
                                 for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                                         vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                                 fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
       }        }
       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
     }      }
Line 4641  void cvevsij(double ***eij, double x[], Line 4731  void cvevsij(double ***eij, double x[],
     fprintf(ficrescveij,"%3.0f",age );      fprintf(ficrescveij,"%3.0f",age );
     for(i=1; i<=nlstate;i++)      for(i=1; i<=nlstate;i++)
       for(j=1; j<=nlstate;j++){        for(j=1; j<=nlstate;j++){
                                 cptj= (j-1)*nlstate+i;          cptj= (j-1)*nlstate+i;
                                 for(i2=1; i2<=nlstate;i2++)          for(i2=1; i2<=nlstate;i2++)
                                         for(j2=1; j2<=nlstate;j2++){            for(j2=1; j2<=nlstate;j2++){
                                                 cptj2= (j2-1)*nlstate+i2;              cptj2= (j2-1)*nlstate+i2;
                                                 if(cptj2 <= cptj)              if(cptj2 <= cptj)
                                                         fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                                         }            }
       }        }
     fprintf(ficrescveij,"\n");      fprintf(ficrescveij,"\n");
                                   
Line 5104  void cvevsij(double ***eij, double x[], Line 5194  void cvevsij(double ***eij, double x[],
   
 /************ Variance of one-step probabilities  ******************/  /************ Variance of one-step probabilities  ******************/
 void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])  void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])
 {   {
   int i, j=0,  k1, l1, tj;     int i, j=0,  k1, l1, tj;
   int k2, l2, j1,  z1;     int k2, l2, j1,  z1;
   int k=0, l;     int k=0, l;
   int first=1, first1, first2;     int first=1, first1, first2;
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;     double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
   double **dnewm,**doldm;     double **dnewm,**doldm;
   double *xp;     double *xp;
   double *gp, *gm;     double *gp, *gm;
   double **gradg, **trgradg;     double **gradg, **trgradg;
   double **mu;     double **mu;
   double age, cov[NCOVMAX+1];     double age, cov[NCOVMAX+1];
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */     double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
   int theta;     int theta;
   char fileresprob[FILENAMELENGTH];     char fileresprob[FILENAMELENGTH];
   char fileresprobcov[FILENAMELENGTH];     char fileresprobcov[FILENAMELENGTH];
   char fileresprobcor[FILENAMELENGTH];     char fileresprobcor[FILENAMELENGTH];
   double ***varpij;     double ***varpij;
   
   strcpy(fileresprob,"PROB_");      strcpy(fileresprob,"PROB_"); 
   strcat(fileresprob,fileres);     strcat(fileresprob,fileres);
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {     if((ficresprob=fopen(fileresprob,"w"))==NULL) {
     printf("Problem with resultfile: %s\n", fileresprob);       printf("Problem with resultfile: %s\n", fileresprob);
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
   }     }
   strcpy(fileresprobcov,"PROBCOV_");      strcpy(fileresprobcov,"PROBCOV_"); 
   strcat(fileresprobcov,fileresu);     strcat(fileresprobcov,fileresu);
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {     if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
     printf("Problem with resultfile: %s\n", fileresprobcov);       printf("Problem with resultfile: %s\n", fileresprobcov);
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
   }     }
   strcpy(fileresprobcor,"PROBCOR_");      strcpy(fileresprobcor,"PROBCOR_"); 
   strcat(fileresprobcor,fileresu);     strcat(fileresprobcor,fileresu);
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {     if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
     printf("Problem with resultfile: %s\n", fileresprobcor);       printf("Problem with resultfile: %s\n", fileresprobcor);
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
   }     }
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);     printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);     fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);     printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);     fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);     printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);     fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   pstamp(ficresprob);     pstamp(ficresprob);
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");     fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
   fprintf(ficresprob,"# Age");     fprintf(ficresprob,"# Age");
   pstamp(ficresprobcov);     pstamp(ficresprobcov);
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");     fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
   fprintf(ficresprobcov,"# Age");     fprintf(ficresprobcov,"# Age");
   pstamp(ficresprobcor);     pstamp(ficresprobcor);
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");     fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
   fprintf(ficresprobcor,"# Age");     fprintf(ficresprobcor,"# Age");
   
   
   for(i=1; i<=nlstate;i++)  
     for(j=1; j<=(nlstate+ndeath);j++){  
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);  
       fprintf(ficresprobcov," p%1d-%1d ",i,j);  
       fprintf(ficresprobcor," p%1d-%1d ",i,j);  
     }    
  /* fprintf(ficresprob,"\n");  
   fprintf(ficresprobcov,"\n");  
   fprintf(ficresprobcor,"\n");  
  */  
   xp=vector(1,npar);  
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);  
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));  
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);  
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);  
   first=1;  
   fprintf(ficgp,"\n# Routine varprob");  
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");  
   fprintf(fichtm,"\n");  
   
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);     for(i=1; i<=nlstate;i++)
   fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);       for(j=1; j<=(nlstate+ndeath);j++){
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \         fprintf(ficresprob," p%1d-%1d (SE)",i,j);
          fprintf(ficresprobcov," p%1d-%1d ",i,j);
          fprintf(ficresprobcor," p%1d-%1d ",i,j);
        }  
      /* fprintf(ficresprob,"\n");
         fprintf(ficresprobcov,"\n");
         fprintf(ficresprobcor,"\n");
      */
      xp=vector(1,npar);
      dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
      doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
      mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
      varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
      first=1;
      fprintf(ficgp,"\n# Routine varprob");
      fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
      fprintf(fichtm,"\n");
   
      fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
      fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
      fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 and drawn. It helps understanding how is the covariance between two incidences.\  and drawn. It helps understanding how is the covariance between two incidences.\
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
   fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \     fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \  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>\  standard deviations wide on each axis. <br>\
Line 5191  standard deviations wide on each axis. < Line 5281  standard deviations wide on each axis. <
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
   
   cov[1]=1;     cov[1]=1;
   /* tj=cptcoveff; */     /* tj=cptcoveff; */
   tj = (int) pow(2,cptcoveff);     tj = (int) pow(2,cptcoveff);
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}     if (cptcovn<1) {tj=1;ncodemax[1]=1;}
   j1=0;     j1=0;
   for(j1=1; j1<=tj;j1++){     for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates */
     /*for(i1=1; i1<=ncodemax[t];i1++){ */       if  (cptcovn>0) {
     /*j1++;*/         fprintf(ficresprob, "\n#********** Variable "); 
       if  (cptcovn>0) {         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficresprob, "\n#********** Variable ");          fprintf(ficresprob, "**********\n#\n");
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);         fprintf(ficresprobcov, "\n#********** Variable "); 
         fprintf(ficresprob, "**********\n#\n");         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficresprobcov, "\n#********** Variable ");          fprintf(ficresprobcov, "**********\n#\n");
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);                          
         fprintf(ficresprobcov, "**********\n#\n");         fprintf(ficgp, "\n#********** Variable "); 
                  for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficgp, "\n#********** Variable ");          fprintf(ficgp, "**********\n#\n");
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);                          
         fprintf(ficgp, "**********\n#\n");                          
                  fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                  for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);                          
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");         fprintf(ficresprobcor, "\n#********** Variable ");    
                  for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
         fprintf(ficresprobcor, "\n#********** Variable ");             fprintf(ficresprobcor, "**********\n#");    
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);         if(invalidvarcomb[j1]){
         fprintf(ficresprobcor, "**********\n#");               fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
       }           fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                  continue;
       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));         }
       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);       }
       gp=vector(1,(nlstate)*(nlstate+ndeath));       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
       gm=vector(1,(nlstate)*(nlstate+ndeath));       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
       for (age=bage; age<=fage; age ++){        gp=vector(1,(nlstate)*(nlstate+ndeath));
         cov[2]=age;       gm=vector(1,(nlstate)*(nlstate+ndeath));
         if(nagesqr==1)       for (age=bage; age<=fage; age ++){ 
           cov[3]= age*age;         cov[2]=age;
         for (k=1; k<=cptcovn;k++) {         if(nagesqr==1)
           cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];           cov[3]= age*age;
           /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4         for (k=1; k<=cptcovn;k++) {
                                                          * 1  1 1 1 1           cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                                                          * 2  2 1 1 1           /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                                                          * 3  1 2 1 1                                                                      * 1  1 1 1 1
                                                          */                                                                      * 2  2 1 1 1
           /* nbcode[1][1]=0 nbcode[1][2]=1;*/                                                                      * 3  1 2 1 1
         }                                                                      */
         /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */           /* nbcode[1][1]=0 nbcode[1][2]=1;*/
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];         }
         for (k=1; k<=cptcovprod;k++)         /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                  for (k=1; k<=cptcovprod;k++)
                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
         for(theta=1; theta <=npar; theta++){                          
           for(i=1; i<=npar; i++)                          
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);         for(theta=1; theta <=npar; theta++){
                      for(i=1; i<=npar; i++)
           pmij(pmmij,cov,ncovmodel,xp,nlstate);             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                                             
           k=0;           pmij(pmmij,cov,ncovmodel,xp,nlstate);
           for(i=1; i<= (nlstate); i++){                                  
             for(j=1; j<=(nlstate+ndeath);j++){           k=0;
               k=k+1;           for(i=1; i<= (nlstate); i++){
               gp[k]=pmmij[i][j];             for(j=1; j<=(nlstate+ndeath);j++){
             }               k=k+1;
           }               gp[k]=pmmij[i][j];
                        }
           for(i=1; i<=npar; i++)           }
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);                                  
                for(i=1; i<=npar; i++)
           pmij(pmmij,cov,ncovmodel,xp,nlstate);             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
           k=0;                                  
           for(i=1; i<=(nlstate); i++){           pmij(pmmij,cov,ncovmodel,xp,nlstate);
             for(j=1; j<=(nlstate+ndeath);j++){           k=0;
               k=k+1;           for(i=1; i<=(nlstate); i++){
               gm[k]=pmmij[i][j];             for(j=1; j<=(nlstate+ndeath);j++){
             }               k=k+1;
           }               gm[k]=pmmij[i][j];
                   }
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)            }
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];                                    
         }           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
              gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)         }
           for(theta=1; theta <=npar; theta++)  
             trgradg[j][theta]=gradg[theta][j];  
           
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);   
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);  
   
         pmij(pmmij,cov,ncovmodel,x,nlstate);  
           
         k=0;  
         for(i=1; i<=(nlstate); i++){  
           for(j=1; j<=(nlstate+ndeath);j++){  
             k=k+1;  
             mu[k][(int) age]=pmmij[i][j];  
           }  
         }  
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)  
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)  
             varpij[i][j][(int)age] = doldm[i][j];  
   
         /*printf("\n%d ",(int)age);  
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){  
           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));  
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));  
           }*/  
   
         fprintf(ficresprob,"\n%d ",(int)age);  
         fprintf(ficresprobcov,"\n%d ",(int)age);  
         fprintf(ficresprobcor,"\n%d ",(int)age);  
   
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)  
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));  
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){  
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);  
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);  
         }  
         i=0;  
         for (k=1; k<=(nlstate);k++){  
           for (l=1; l<=(nlstate+ndeath);l++){   
             i++;  
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);  
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);  
             for (j=1; j<=i;j++){  
               /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */  
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);  
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));  
             }  
           }  
         }/* end of loop for state */  
       } /* end of loop for age */  
       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));  
       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));  
       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);  
       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);  
         
       /* Confidence intervalle of pij  */  
       /*  
         fprintf(ficgp,"\nunset parametric;unset label");  
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");  
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");  
         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);  
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);  
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);  
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);  
       */  
   
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/  
       first1=1;first2=2;  
       for (k2=1; k2<=(nlstate);k2++){  
         for (l2=1; l2<=(nlstate+ndeath);l2++){   
           if(l2==k2) continue;  
           j=(k2-1)*(nlstate+ndeath)+l2;  
           for (k1=1; k1<=(nlstate);k1++){  
             for (l1=1; l1<=(nlstate+ndeath);l1++){   
               if(l1==k1) continue;  
               i=(k1-1)*(nlstate+ndeath)+l1;  
               if(i<=j) continue;  
               for (age=bage; age<=fage; age ++){   
                 if ((int)age %5==0){  
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;  
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;  
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;  
                   mu1=mu[i][(int) age]/stepm*YEARM ;  
                   mu2=mu[j][(int) age]/stepm*YEARM;  
                   c12=cv12/sqrt(v1*v2);  
                   /* Computing eigen value of matrix of covariance */  
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  
                   if ((lc2 <0) || (lc1 <0) ){  
                     if(first2==1){  
                       first1=0;  
                     printf("Strange: j1=%d One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Probably WRONG RESULTS. See log file for details...\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);  
                     }  
                     fprintf(ficlog,"Strange: j1=%d One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Probably WRONG RESULTS.\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);fflush(ficlog);  
                     /* lc1=fabs(lc1); */ /* If we want to have them positive */  
                     /* lc2=fabs(lc2); */  
                   }  
   
                   /* Eigen vectors */         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));           for(theta=1; theta <=npar; theta++)
                   /*v21=sqrt(1.-v11*v11); *//* error */             trgradg[j][theta]=gradg[theta][j];
                   v21=(lc1-v1)/cv12*v11;                          
                   v12=-v21;         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   v22=v11;         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   tnalp=v21/v11;                          
                   if(first1==1){         pmij(pmmij,cov,ncovmodel,x,nlstate);
                     first1=0;                          
                     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);         k=0;
                   }         for(i=1; i<=(nlstate); i++){
                   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);           for(j=1; j<=(nlstate+ndeath);j++){
                   /*printf(fignu*/             k=k+1;
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */             mu[k][(int) age]=pmmij[i][j];
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */           }
                   if(first==1){         }
                     first=0;         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                     fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                     fprintf(ficgp,"\nset parametric;unset label");             varpij[i][j][(int)age] = doldm[i][j];
                     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);                          
                     fprintf(ficgp,"\nset ter svg size 640, 480");         /*printf("\n%d ",(int)age);
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
            }*/
                           
          fprintf(ficresprob,"\n%d ",(int)age);
          fprintf(ficresprobcov,"\n%d ",(int)age);
          fprintf(ficresprobcor,"\n%d ",(int)age);
                           
          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
          }
          i=0;
          for (k=1; k<=(nlstate);k++){
            for (l=1; l<=(nlstate+ndeath);l++){ 
              i++;
              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
              for (j=1; j<=i;j++){
                /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
              }
            }
          }/* end of loop for state */
        } /* end of loop for age */
        free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
        free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
        free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
        free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
       
        /* Confidence intervalle of pij  */
        /*
          fprintf(ficgp,"\nunset parametric;unset label");
          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
          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);
          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
        */
                   
        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
        first1=1;first2=2;
        for (k2=1; k2<=(nlstate);k2++){
          for (l2=1; l2<=(nlstate+ndeath);l2++){ 
            if(l2==k2) continue;
            j=(k2-1)*(nlstate+ndeath)+l2;
            for (k1=1; k1<=(nlstate);k1++){
              for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                if(l1==k1) continue;
                i=(k1-1)*(nlstate+ndeath)+l1;
                if(i<=j) continue;
                for (age=bage; age<=fage; age ++){ 
                  if ((int)age %5==0){
                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                    mu1=mu[i][(int) age]/stepm*YEARM ;
                    mu2=mu[j][(int) age]/stepm*YEARM;
                    c12=cv12/sqrt(v1*v2);
                    /* Computing eigen value of matrix of covariance */
                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                    if ((lc2 <0) || (lc1 <0) ){
                      if(first2==1){
                        first1=0;
                        printf("Strange: j1=%d One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Probably WRONG RESULTS. See log file for details...\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
                      }
                      fprintf(ficlog,"Strange: j1=%d One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Probably WRONG RESULTS.\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);fflush(ficlog);
                      /* lc1=fabs(lc1); */ /* If we want to have them positive */
                      /* lc2=fabs(lc2); */
                    }
                                                                   
                    /* Eigen vectors */
                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                    /*v21=sqrt(1.-v11*v11); *//* error */
                    v21=(lc1-v1)/cv12*v11;
                    v12=-v21;
                    v22=v11;
                    tnalp=v21/v11;
                    if(first1==1){
                      first1=0;
                      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);
                    }
                    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);
                    /*printf(fignu*/
                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                    if(first==1){
                      first=0;
                      fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                      fprintf(ficgp,"\nset parametric;unset label");
                      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);
                      fprintf(ficgp,"\nset ter svg size 640, 480");
                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
    :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                           \
 %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\  %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                             subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\                             subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                             subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);                             subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                     fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);                     fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                     fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);                     fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                     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",\                     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",      \
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   }else{                   }else{
                     first=0;                     first=0;
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                     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",\                     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", \
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   }/* if first */                   }/* if first */
                 } /* age mod 5 */                 } /* age mod 5 */
               } /* end loop age */               } /* end loop age */
               fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);               fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
               first=1;               first=1;
             } /*l12 */             } /*l12 */
           } /* k12 */           } /* k12 */
         } /*l1 */         } /*l1 */
       }/* k1 */       }/* k1 */
       /* } */ /* loop covariates */     }  /* loop on combination of covariates j1 */
   }     free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);     free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);     free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));     free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);     free_vector(xp,1,npar);
   free_vector(xp,1,npar);     fclose(ficresprob);
   fclose(ficresprob);     fclose(ficresprobcov);
   fclose(ficresprobcov);     fclose(ficresprobcor);
   fclose(ficresprobcor);     fflush(ficgp);
   fflush(ficgp);     fflush(fichtmcov);
   fflush(fichtmcov);   }
 }  
   
   
 /******************* Printing html file ***********/  /******************* Printing html file ***********/
Line 5478  void printinghtml(char fileresu[], char Line 5569  void printinghtml(char fileresu[], char
    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
    }     }
   
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");     fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
   
      m=pow(2,cptcoveff);
      if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   
  m=pow(2,cptcoveff);     jj1=0;
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}     for(k1=1; k1<=m;k1++){
   
  jj1=0;       /* for(i1=1; i1<=ncodemax[k1];i1++){ */
  for(k1=1; k1<=m;k1++){  
    /* for(i1=1; i1<=ncodemax[k1];i1++){ */  
      jj1++;       jj1++;
      if (cptcovn > 0) {       if (cptcovn > 0) {
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
Line 5494  fprintf(fichtm," \n<ul><li><b>Graphs</b> Line 5586  fprintf(fichtm," \n<ul><li><b>Graphs</b>
          printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);           printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
        }         }
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
          if(invalidvarcomb[k1]){
            fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
            printf("\nCombination (%d) ignored because no cases \n",k1); 
            continue;
          }
      }       }
      /* aij, bij */       /* aij, bij */
      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \       fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
Line 5503  fprintf(fichtm," \n<ul><li><b>Graphs</b> Line 5600  fprintf(fichtm," \n<ul><li><b>Graphs</b>
 <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);       <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
      /* Quasi-incidences */       /* Quasi-incidences */
      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\       fprintf(fichtm,"<br>\n- I<sub>ij</sub> 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,\   before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \   incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \  divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);   <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
Line 5515  divided by h: <sub>h</sub>P<sub>ij</sub> Line 5612  divided by h: <sub>h</sub>P<sub>ij</sub>
      /* State specific survival functions (period) */       /* State specific survival functions (period) */
      for(cpt=1; cpt<=nlstate;cpt++){       for(cpt=1; cpt<=nlstate;cpt++){
        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\         fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
  Or probability to survive in various states (1 to %d) being in state %d at different ages.\   Or probability to survive in various states (1 to %d) being in state %d at different ages.     \
  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);   <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
      }       }
      /* Period (stable) prevalence in each health state */       /* Period (stable) prevalence in each health state */
Line 5523  divided by h: <sub>h</sub>P<sub>ij</sub> Line 5620  divided by h: <sub>h</sub>P<sub>ij</sub>
        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \         fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
 <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);  <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
      }       }
     if(backcast==1){       if(backcast==1){
      /* Period (stable) back prevalence in each health state */         /* Period (stable) back prevalence in each health state */
      for(cpt=1; cpt<=nlstate;cpt++){         for(cpt=1; cpt<=nlstate;cpt++){
        fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \           fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
 <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);  <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
          }
      }       }
     }       if(prevfcast==1){
     if(prevfcast==1){         /* Projection of prevalence up to period (stable) prevalence in each health state */
       /* Projection of prevalence up to period (stable) prevalence in each health state */         for(cpt=1; cpt<=nlstate;cpt++){
       for(cpt=1; cpt<=nlstate;cpt++){           fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \  
 <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);  <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
       }         }
     }       }
            
      for(cpt=1; cpt<=nlstate;cpt++) {       for(cpt=1; cpt<=nlstate;cpt++) {
        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
 <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);  <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
      }       }
    /* } /\* end i1 *\/ */       /* } /\* end i1 *\/ */
  }/* End k1 */     }/* End k1 */
  fprintf(fichtm,"</ul>");     fprintf(fichtm,"</ul>");
   
  fprintf(fichtm,"\     fprintf(fichtm,"\
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \   - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
Line 5558  variances but at the covariance matrix. Line 5655  variances but at the covariance matrix.
 covariance matrix of the one-step probabilities. \  covariance matrix of the one-step probabilities. \
 See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);  See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
   
  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",     fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
          subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));             subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
          subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));             subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
   
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
          subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));             subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \   - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
    <a href=\"%s\">%s</a> <br>\n</li>",     <a href=\"%s\">%s</a> <br>\n</li>",
            estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));             estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \   - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \
    <a href=\"%s\">%s</a> <br>\n</li>",     <a href=\"%s\">%s</a> <br>\n</li>",
            estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));             estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",   - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
          estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));             estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",   - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",
          estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));             estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
          subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));             subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
   
 /*  if(popforecast==1) fprintf(fichtm,"\n */  /*  if(popforecast==1) fprintf(fichtm,"\n */
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
Line 5591  See page 'Matrix of variance-covariance Line 5688  See page 'Matrix of variance-covariance
 /*      <br>",fileres,fileres,fileres,fileres); */  /*      <br>",fileres,fileres,fileres,fileres); */
 /*  else  */  /*  else  */
 /*    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); */  /*    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); */
  fflush(fichtm);     fflush(fichtm);
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");     fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
   
  m=pow(2,cptcoveff);     m=pow(2,cptcoveff);
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}     if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   
  jj1=0;     jj1=0;
  for(k1=1; k1<=m;k1++){     for(k1=1; k1<=m;k1++){
    /* for(i1=1; i1<=ncodemax[k1];i1++){ */       /* for(i1=1; i1<=ncodemax[k1];i1++){ */
      jj1++;       jj1++;
      if (cptcovn > 0) {       if (cptcovn > 0) {
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
        for (cpt=1; cpt<=cptcoveff;cpt++)          for (cpt=1; cpt<=cptcoveff;cpt++) 
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   
          if(invalidvarcomb[k1]){
            fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
            continue;
          }
      }       }
      for(cpt=1; cpt<=nlstate;cpt++) {       for(cpt=1; cpt<=nlstate;cpt++) {
        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \         fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
Line 5618  true period expectancies (those weighted Line 5720  true period expectancies (those weighted
  drawn in addition to the population based expectancies computed using\   drawn in addition to the population based expectancies computed using\
  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\   observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
 <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);  <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
    /* } /\* end i1 *\/ */       /* } /\* end i1 *\/ */
  }/* End k1 */     }/* End k1 */
  fprintf(fichtm,"</ul>");     fprintf(fichtm,"</ul>");
  fflush(fichtm);     fflush(fichtm);
 }  }
   
 /******************* Gnuplot file **************/  /******************* Gnuplot file **************/
  void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){  void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
   
   char dirfileres[132],optfileres[132];    char dirfileres[132],optfileres[132];
     char gplotcondition[132];
   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;    int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
   int lv=0, vlv=0, kl=0;    int lv=0, vlv=0, kl=0;
   int ng=0;    int ng=0;
   int vpopbased;    int vpopbased;
     int ioffset; /* variable offset for columns */
   
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 /*     printf("Problem with file %s",optionfilegnuplot); */  /*     printf("Problem with file %s",optionfilegnuplot); */
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */  /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
Line 5639  true period expectancies (those weighted Line 5744  true period expectancies (those weighted
   
   /*#ifdef windows */    /*#ifdef windows */
   fprintf(ficgp,"cd \"%s\" \n",pathc);    fprintf(ficgp,"cd \"%s\" \n",pathc);
     /*#endif */    /*#endif */
   m=pow(2,cptcoveff);    m=pow(2,cptcoveff);
   
   /* Contribution to likelihood */    /* Contribution to likelihood */
   /* Plot the probability implied in the likelihood */    /* Plot the probability implied in the likelihood */
     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");    fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */    /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
     fprintf(ficgp,"\nset ter pngcairo size 640, 480");    fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 /* nice for mle=4 plot by number of matrix products.  /* nice for mle=4 plot by number of matrix products.
    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */     replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */  /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */    /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));    fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));    fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));    fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));    fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
     for (i=1; i<= nlstate ; i ++) {    for (i=1; i<= nlstate ; i ++) {
       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);      fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));      fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
       fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);      fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
       for (j=2; j<= nlstate+ndeath ; j ++) {      for (j=2; j<= nlstate+ndeath ; j ++) {
         fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);        fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
       }      }
       fprintf(ficgp,";\nset out; unset ylabel;\n");       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
     }    }
     /* unset log; plot  "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u  2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */                  /* unset log; plot  "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u  2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */                
     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */    /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */    /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
     fprintf(ficgp,"\nset out;unset log\n");    fprintf(ficgp,"\nset out;unset log\n");
     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */    /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
   
   strcpy(dirfileres,optionfilefiname);    strcpy(dirfileres,optionfilefiname);
   strcpy(optfileres,"vpl");    strcpy(optfileres,"vpl");
  /* 1eme*/    /* 1eme*/
   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */    for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */      for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
         lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
         /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
         /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
         /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
         vlv= nbcode[Tvaraff[lv]][lv];          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
         fprintf(ficgp," V%d=%d ",k,vlv);          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
           fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
       }        }
       fprintf(ficgp,"\n#\n");        fprintf(ficgp,"\n#\n");
         if(invalidvarcomb[k1]){
           fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
           continue;
         }
   
      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);        fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
      fprintf(ficgp,"set xlabel \"Age\" \n\        fprintf(ficgp,"set xlabel \"Age\" \n\
 set ylabel \"Probability\" \n\  set ylabel \"Probability\" \n   \
 set ter svg size 640, 480\n\  set ter svg size 640, 480\n     \
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
                           
      for (i=1; i<= nlstate ; i ++) {        for (i=1; i<= nlstate ; i ++) {
        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        else        fprintf(ficgp," %%*lf (%%*lf)");          else        fprintf(ficgp," %%*lf (%%*lf)");
      }        }
      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);        fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
      for (i=1; i<= nlstate ; i ++) {        for (i=1; i<= nlstate ; i ++) {
        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        else fprintf(ficgp," %%*lf (%%*lf)");          else fprintf(ficgp," %%*lf (%%*lf)");
      }         } 
      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);         fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
      for (i=1; i<= nlstate ; i ++) {        for (i=1; i<= nlstate ; i ++) {
        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        else fprintf(ficgp," %%*lf (%%*lf)");          else fprintf(ficgp," %%*lf (%%*lf)");
      }          }  
      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence\" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence\" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
                  if(backcast==1){        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                          fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt);          /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
                  }          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
      fprintf(ficgp,"\nset out \n");          if(cptcoveff ==0){
             fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",  2+(cpt-1),  cpt );
           }else{
             kl=0;
             for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
               lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
               /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
               /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
               /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
               vlv= nbcode[Tvaraff[k]][lv];
               kl++;
               /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
               /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
               /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
               /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
               if(k==cptcoveff){
                 fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                         6+(cpt-1),  cpt );
               }else{
                 fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                 kl++;
               }
             } /* end covariate */
           } /* end if no covariate */
         } /* end if backcast */
         fprintf(ficgp,"\nset out \n");
     } /* k1 */      } /* k1 */
   } /* cpt */    } /* cpt */
   /*2 eme*/    /*2 eme*/
   for (k1=1; k1<= m ; k1 ++) {     for (k1=1; k1<= m ; k1 ++) { 
       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");  
       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */  
         lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */  
         /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */  
         /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */  
         /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */  
         vlv= nbcode[Tvaraff[lv]][lv];  
         fprintf(ficgp," V%d=%d ",k,vlv);  
       }  
       fprintf(ficgp,"\n#\n");  
   
       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
         lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
         /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
         /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
         /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
         vlv= nbcode[Tvaraff[k]][lv];
         fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
       }
       fprintf(ficgp,"\n#\n");
       if(invalidvarcomb[k1]){
         fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
         continue;
       }
                           
     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);      fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/      for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
       if(vpopbased==0)        if(vpopbased==0)
Line 5761  plot [%.f:%.f] \"%s\" every :::%d::%d u Line 5901  plot [%.f:%.f] \"%s\" every :::%d::%d u
     } /* vpopbased */      } /* vpopbased */
     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */      fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
   } /* k1 */    } /* k1 */
           
           
   /*3eme*/    /*3eme*/
   for (k1=1; k1<= m ; k1 ++) {     for (k1=1; k1<= m ; k1 ++) { 
   
     for (cpt=1; cpt<= nlstate ; cpt ++) {      for (cpt=1; cpt<= nlstate ; cpt ++) {
       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
Line 5772  plot [%.f:%.f] \"%s\" every :::%d::%d u Line 5913  plot [%.f:%.f] \"%s\" every :::%d::%d u
         /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
         /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
         /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
         vlv= nbcode[Tvaraff[lv]][lv];          vlv= nbcode[Tvaraff[k]][lv];
         fprintf(ficgp," V%d=%d ",k,vlv);          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
       }        }
       fprintf(ficgp,"\n#\n");        fprintf(ficgp,"\n#\n");
         if(invalidvarcomb[k1]){
           fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
           continue;
         }
                           
       /*       k=2+nlstate*(2*cpt-2); */        /*       k=2+nlstate*(2*cpt-2); */
       k=2+(nlstate+1)*(cpt-1);        k=2+(nlstate+1)*(cpt-1);
       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);        fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
Line 5788  plot [%.f:%.f] \"%s\" every :::%d::%d u Line 5933  plot [%.f:%.f] \"%s\" every :::%d::%d u
         fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                                           
       */        */
       for (i=1; i< nlstate ; i ++) {        for (i=1; i< nlstate ; i ++) {
         fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);          fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
         /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/          /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/
                                           
       }         } 
       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
     }      }
   }    }
       
     /* 4eme */
   /* Survival functions (period) from state i in state j by initial state i */    /* Survival functions (period) from state i in state j by initial state i */
   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */    for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
   
     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */      for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
Line 5808  plot [%.f:%.f] \"%s\" every :::%d::%d u Line 5955  plot [%.f:%.f] \"%s\" every :::%d::%d u
         /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
         /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
         /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
         vlv= nbcode[Tvaraff[lv]][lv];          vlv= nbcode[Tvaraff[k]][lv];
         fprintf(ficgp," V%d=%d ",k,vlv);          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
       }        }
       fprintf(ficgp,"\n#\n");        fprintf(ficgp,"\n#\n");
         if(invalidvarcomb[k1]){
           fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
           continue;
         }
                           
       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 set ter svg size 640, 480\n\  set ter svg size 640, 480\n                                                                                                                                                                                     \
 unset log y\n\  unset log y\n                                                                                                                                                                                                                                           \
 plot [%.f:%.f]  ", ageminpar, agemaxpar);  plot [%.f:%.f]  ", ageminpar, agemaxpar);
       k=3;        k=3;
       for (i=1; i<= nlstate ; i ++){        for (i=1; i<= nlstate ; i ++){
Line 5834  plot [%.f:%.f]  ", ageminpar, agemaxpar) Line 5985  plot [%.f:%.f]  ", ageminpar, agemaxpar)
       fprintf(ficgp,"\nset out\n");        fprintf(ficgp,"\nset out\n");
     } /* end cpt state*/       } /* end cpt state*/ 
   } /* end covariate */      } /* end covariate */  
           
   /* 5eme */
   /* Survival functions (period) from state i in state j by final state j */    /* Survival functions (period) from state i in state j by final state j */
   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */    for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */      for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                           
       fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);        fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
         lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */                                  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
         /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */                                  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
         /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */                                  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
         /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */                                  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
         vlv= nbcode[Tvaraff[lv]][lv];                                  vlv= nbcode[Tvaraff[k]][lv];
         fprintf(ficgp," V%d=%d ",k,vlv);                                  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
       }        }
       fprintf(ficgp,"\n#\n");        fprintf(ficgp,"\n#\n");
         if(invalidvarcomb[k1]){
                                   fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                                   continue;
         }
                           
       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 set ter svg size 640, 480\n\  set ter svg size 640, 480\n                                                                                                                                                                                     \
 unset log y\n\  unset log y\n                                                                                                                                                                                                                                           \
 plot [%.f:%.f]  ", ageminpar, agemaxpar);  plot [%.f:%.f]  ", ageminpar, agemaxpar);
       k=3;        k=3;
       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
         if(j==1)                                  if(j==1)
           fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));                                          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
         else                                  else
           fprintf(ficgp,", '' ");                                          fprintf(ficgp,", '' ");
         l=(nlstate+ndeath)*(cpt-1) +j;                                  l=(nlstate+ndeath)*(cpt-1) +j;
         fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);                                  fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
         /* for (i=2; i<= nlstate+ndeath ; i ++) */                                  /* for (i=2; i<= nlstate+ndeath ; i ++) */
         /*   fprintf(ficgp,"+$%d",k+l+i-1); */                                  /*   fprintf(ficgp,"+$%d",k+l+i-1); */
         fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);                                  fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
       } /* nlstate */        } /* nlstate */
       fprintf(ficgp,", '' ");        fprintf(ficgp,", '' ");
       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
         l=(nlstate+ndeath)*(cpt-1) +j;                                  l=(nlstate+ndeath)*(cpt-1) +j;
         if(j < nlstate)                                  if(j < nlstate)
           fprintf(ficgp,"$%d +",k+l);                                          fprintf(ficgp,"$%d +",k+l);
         else                                  else
           fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);                                          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
       }        }
       fprintf(ficgp,"\nset out\n");        fprintf(ficgp,"\nset out\n");
     } /* end cpt state*/       } /* end cpt state*/ 
   } /* end covariate */      } /* end covariate */  
           
   /* 6eme */
   /* CV preval stable (period) for each covariate */    /* CV preval stable (period) for each covariate */
   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */    for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */      for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                           
       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);        fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
         lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */                                  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
         /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */                                  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
         /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */                                  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
         /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */                                  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
         vlv= nbcode[Tvaraff[lv]][lv];                                  vlv= nbcode[Tvaraff[k]][lv];
         fprintf(ficgp," V%d=%d ",k,vlv);                                  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
       }        }
       fprintf(ficgp,"\n#\n");        fprintf(ficgp,"\n#\n");
         if(invalidvarcomb[k1]){
                                   fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                                   continue;
         }
                           
       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 set ter svg size 640, 480\n\  set ter svg size 640, 480\n                                                                                                                                                                              \
 unset log y\n\  unset log y\n                                                                                                                                                                                                                                    \
 plot [%.f:%.f]  ", ageminpar, agemaxpar);  plot [%.f:%.f]  ", ageminpar, agemaxpar);
       k=3; /* Offset */        k=3; /* Offset */
       for (i=1; i<= nlstate ; i ++){        for (i=1; i<= nlstate ; i ++){
         if(i==1)                                  if(i==1)
           fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));                                          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
         else                                  else
           fprintf(ficgp,", '' ");                                          fprintf(ficgp,", '' ");
         l=(nlstate+ndeath)*(i-1)+1;                                  l=(nlstate+ndeath)*(i-1)+1;
         fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);                                  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
         for (j=2; j<= nlstate ; j ++)                                  for (j=2; j<= nlstate ; j ++)
           fprintf(ficgp,"+$%d",k+l+j-1);                                          fprintf(ficgp,"+$%d",k+l+j-1);
         fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);                                  fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
       } /* nlstate */        } /* nlstate */
       fprintf(ficgp,"\nset out\n");        fprintf(ficgp,"\nset out\n");
     } /* end cpt state*/       } /* end cpt state*/ 
   } /* end covariate */      } /* end covariate */  
           
           
   /* 7eme */
   if(backcast == 1){    if(backcast == 1){
     /* CV back preval stable (period) for each covariate */      /* CV back preval stable (period) for each covariate */
     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */      for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */        for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
         fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);                                  fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
         for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */                                  for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
           lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */                                          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
           /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */                                          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
           /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */                                          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
           /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
           vlv= nbcode[Tvaraff[lv]][lv];                                          vlv= nbcode[Tvaraff[k]][lv];
           fprintf(ficgp," V%d=%d ",k,vlv);                                          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
         }                                  }
         fprintf(ficgp,"\n#\n");                                  fprintf(ficgp,"\n#\n");
                                           if(invalidvarcomb[k1]){
         fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);                                          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
         fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\                                          continue;
 set ter svg size 640, 480\n                                             \                                  }
 unset log y\n                                                           \                                  
                                   fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                                   fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
   set ter svg size 640, 480\n                                                                                                                                                                                     \
   unset log y\n                                                                                                                                                                                                                                           \
 plot [%.f:%.f]  ", ageminpar, agemaxpar);  plot [%.f:%.f]  ", ageminpar, agemaxpar);
         k=3; /* Offset */                                  k=3; /* Offset */
         for (i=1; i<= nlstate ; i ++){                                  for (i=1; i<= nlstate ; i ++){
           if(i==1)                                          if(i==1)
             fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));                                                  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
           else                                          else
             fprintf(ficgp,", '' ");                                                  fprintf(ficgp,", '' ");
           /* l=(nlstate+ndeath)*(i-1)+1; */                                          /* l=(nlstate+ndeath)*(i-1)+1; */
           l=(nlstate+ndeath)*(cpt-1)+1;                                          l=(nlstate+ndeath)*(cpt-1)+1;
           /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */                                          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
           /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */                                          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
           fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */                                          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
           /* for (j=2; j<= nlstate ; j ++) */                                          /* for (j=2; j<= nlstate ; j ++) */
           /*    fprintf(ficgp,"+$%d",k+l+j-1); */                                          /*      fprintf(ficgp,"+$%d",k+l+j-1); */
           /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */                                          /*      /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
           fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);                                          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
         } /* nlstate */                                  } /* nlstate */
         fprintf(ficgp,"\nset out\n");                                  fprintf(ficgp,"\nset out\n");
       } /* end cpt state*/         } /* end cpt state*/ 
     } /* end covariate */        } /* end covariate */  
   } /* End if backcast */    } /* End if backcast */
       
     /* 8eme */
   if(prevfcast==1){    if(prevfcast==1){
     /* Projection from cross-sectional to stable (period) for each covariate */      /* Projection from cross-sectional to stable (period) for each covariate */
           
     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */      for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */        for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
         fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);                                  fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
         for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */                                  for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
           lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */                                          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
           /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */                                          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
           /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */                                          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
           /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */                                          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
           vlv= nbcode[Tvaraff[lv]][lv];                                          vlv= nbcode[Tvaraff[k]][lv];
           fprintf(ficgp," V%d=%d ",k,vlv);                                          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
         }                                  }
         fprintf(ficgp,"\n#\n");                                  fprintf(ficgp,"\n#\n");
                                           if(invalidvarcomb[k1]){
         fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");                                          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
         fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);                                          continue;
         fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\                                  }
 set ter svg size 640, 480\n\                                  
 unset log y\n\                                  fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                                   fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                                   fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
   set ter svg size 640, 480\n                                                                                                                                                                                     \
   unset log y\n                                                                                                                                                                                                                                           \
 plot [%.f:%.f]  ", ageminpar, agemaxpar);  plot [%.f:%.f]  ", ageminpar, agemaxpar);
         for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */                                  for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
           /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/                                          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
           /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */                                             /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
           /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/                                          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
           /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */                                             /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
           if(i==1){                                          if(i==1){
             fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));                                                  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
           }else{                                          }else{
             fprintf(ficgp,",\\\n '' ");                                                  fprintf(ficgp,",\\\n '' ");
           }                                          }
           if(cptcoveff ==0){ /* No covariate */                                          if(cptcoveff ==0){ /* No covariate */
             fprintf(ficgp," u 2:("); /* Age is in 2 */                                                  ioffset=2; /* Age is in 2 */
             /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/                                                  /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
             /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */                                                  /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
             if(i==nlstate+1)                                                  /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
               fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \                                                  /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                         2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );                                                  fprintf(ficgp," u %d:(", ioffset); 
             else                                                  if(i==nlstate+1)
               fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \                                                          fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",                    \
                       2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );                                                                                          ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
           }else{                                                  else
             fprintf(ficgp,"u 6:(("); /* Age is in 6 */                                                          fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",                    \
             /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/                                                                                          ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
             /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */                                             }else{ /* more than 2 covariates */
             kl=0;                                                  if(cptcoveff ==1){
             for (k=1; k<=cptcoveff; k++){    /* For each covariate  */                                                          ioffset=4; /* Age is in 4 */
               lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */                                                  }else{
               /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */                                                          ioffset=6; /* Age is in 6 */
               /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */                                                          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
               /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */                                                          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
               vlv= nbcode[Tvaraff[lv]][lv];                                                  }   
               kl++;                                                  fprintf(ficgp," u %d:(",ioffset); 
               /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */                                                  kl=0;
               /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */                                                   strcpy(gplotcondition,"(");
               /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */                                                   for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
               /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/                                                          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
               if(k==cptcoveff)                                                          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                 if(i==nlstate+1)                                                          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \                                                          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                           6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );                                                          vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                 else                                                          kl++;
                   fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \                                                          sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                           6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );                                                          kl++;
               else{                                                          if(k <cptcoveff && cptcoveff>1)
                 fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);                                                                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                 kl++;                                                  }
               }                                                  strcpy(gplotcondition+strlen(gplotcondition),")");
             } /* end covariate */                                                  /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
           } /* end if covariate */                                                  /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
         } /* nlstate */                                                  /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
         fprintf(ficgp,"\nset out\n");                                                  /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                                                   if(i==nlstate+1){
                                                           fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                                                                                           ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                                                   }else{
                                                           fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                                                                                           ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                                                   }
                                           } /* end if covariate */
                                   } /* nlstate */
                                   fprintf(ficgp,"\nset out\n");
       } /* end cpt state*/        } /* end cpt state*/
     } /* end covariate */      } /* end covariate */
   } /* End if prevfcast */    } /* End if prevfcast */
           
           
   /* proba elementaires */    /* proba elementaires */
   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");    fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
   for(i=1,jk=1; i <=nlstate; i++){    for(i=1,jk=1; i <=nlstate; i++){
     fprintf(ficgp,"# initial state %d\n",i);      fprintf(ficgp,"# initial state %d\n",i);
     for(k=1; k <=(nlstate+ndeath); k++){      for(k=1; k <=(nlstate+ndeath); k++){
       if (k != i) {        if (k != i) {
         fprintf(ficgp,"#   current state %d\n",k);                                  fprintf(ficgp,"#   current state %d\n",k);
         for(j=1; j <=ncovmodel; j++){                                  for(j=1; j <=ncovmodel; j++){
           fprintf(ficgp,"p%d=%f; ",jk,p[jk]);                                          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
           jk++;                                           jk++; 
         }                                  }
         fprintf(ficgp,"\n");                                  fprintf(ficgp,"\n");
       }        }
     }      }
    }    }
   fprintf(ficgp,"##############\n#\n");    fprintf(ficgp,"##############\n#\n");
           
   /*goto avoid;*/    /*goto avoid;*/
   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");    fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");    fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
Line 6064  plot [%.f:%.f]  ", ageminpar, agemaxpar) Line 6249  plot [%.f:%.f]  ", ageminpar, agemaxpar)
   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");    fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");    fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
   fprintf(ficgp,"#\n");    fprintf(ficgp,"#\n");
    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
      fprintf(ficgp,"# ng=%d\n",ng);      fprintf(ficgp,"# ng=%d\n",ng);
      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
      for(jk=1; jk <=m; jk++) {      for(jk=1; jk <=m; jk++) {
        fprintf(ficgp,"#    jk=%d\n",jk);        fprintf(ficgp,"#    jk=%d\n",jk);
        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
        fprintf(ficgp,"\nset ter svg size 640, 480 ");        fprintf(ficgp,"\nset ter svg size 640, 480 ");
        if (ng==1){        if (ng==1){
          fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */          fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
          fprintf(ficgp,"\nunset log y");          fprintf(ficgp,"\nunset log y");
        }else if (ng==2){        }else if (ng==2){
          fprintf(ficgp,"\nset ylabel \"Probability\"\n");          fprintf(ficgp,"\nset ylabel \"Probability\"\n");
          fprintf(ficgp,"\nset log y");          fprintf(ficgp,"\nset log y");
        }else if (ng==3){        }else if (ng==3){
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
          fprintf(ficgp,"\nset log y");          fprintf(ficgp,"\nset log y");
        }else        }else
          fprintf(ficgp,"\nunset title ");          fprintf(ficgp,"\nunset title ");
        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
        i=1;        i=1;
        for(k2=1; k2<=nlstate; k2++) {        for(k2=1; k2<=nlstate; k2++) {
          k3=i;          k3=i;
          for(k=1; k<=(nlstate+ndeath); k++) {          for(k=1; k<=(nlstate+ndeath); k++) {
            if (k != k2){            if (k != k2){
              switch( ng) {              switch( ng) {
              case 1:              case 1:
                if(nagesqr==0)                if(nagesqr==0)
                  fprintf(ficgp," p%d+p%d*x",i,i+1);                  fprintf(ficgp," p%d+p%d*x",i,i+1);
                else /* nagesqr =1 */                else /* nagesqr =1 */
                  fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);                  fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                break;                break;
              case 2: /* ng=2 */              case 2: /* ng=2 */
                if(nagesqr==0)                if(nagesqr==0)
                  fprintf(ficgp," exp(p%d+p%d*x",i,i+1);                  fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                else /* nagesqr =1 */                else /* nagesqr =1 */
                    fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);                  fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                break;                break;
              case 3:              case 3:
                if(nagesqr==0)                if(nagesqr==0)
                  fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);                  fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                else /* nagesqr =1 */                else /* nagesqr =1 */
                  fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);                  fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                break;                break;
              }              }
              ij=1;/* To be checked else nbcode[0][0] wrong */              ij=1;/* To be checked else nbcode[0][0] wrong */
              for(j=3; j <=ncovmodel-nagesqr; j++) {              for(j=3; j <=ncovmodel-nagesqr; j++) {
                /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */                /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                if(ij <=cptcovage) { /* Bug valgrind */                if(ij <=cptcovage) { /* Bug valgrind */
                  if((j-2)==Tage[ij]) { /* Bug valgrind */                  if((j-2)==Tage[ij]) { /* Bug valgrind */
                    fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);                    fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                    ij++;                    ij++;
                  }                  }
                }                }
                else                else
                  fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);                  fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
              }              }
            }else{            }else{
              i=i-ncovmodel;              i=i-ncovmodel;
              if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */              if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                fprintf(ficgp," (1.");                fprintf(ficgp," (1.");
            }            }
                         
            if(ng != 1){            if(ng != 1){
              fprintf(ficgp,")/(1");              fprintf(ficgp,")/(1");
                             
              for(k1=1; k1 <=nlstate; k1++){               for(k1=1; k1 <=nlstate; k1++){ 
                if(nagesqr==0)                if(nagesqr==0)
                  fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);                  fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                else /* nagesqr =1 */                else /* nagesqr =1 */
                  fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);                  fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
                                 
                ij=1;                ij=1;
                for(j=3; j <=ncovmodel-nagesqr; j++){                for(j=3; j <=ncovmodel-nagesqr; j++){
                  if(ij <=cptcovage) { /* Bug valgrind */                  if(ij <=cptcovage) { /* Bug valgrind */
                    if((j-2)==Tage[ij]) { /* Bug valgrind */                    if((j-2)==Tage[ij]) { /* Bug valgrind */
                      fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);                      fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                      /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */                      /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                      ij++;                      ij++;
                    }                    }
                  }                  }
                  else                  else
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                }                }
                fprintf(ficgp,")");                fprintf(ficgp,")");
              }              }
              fprintf(ficgp,")");              fprintf(ficgp,")");
              if(ng ==2)              if(ng ==2)
                fprintf(ficgp," t \"p%d%d\" ", k2,k);                fprintf(ficgp," t \"p%d%d\" ", k2,k);
              else /* ng= 3 */              else /* ng= 3 */
                fprintf(ficgp," t \"i%d%d\" ", k2,k);                fprintf(ficgp," t \"i%d%d\" ", k2,k);
            }else{ /* end ng <> 1 */            }else{ /* end ng <> 1 */
              if( k !=k2) /* logit p11 is hard to draw */              if( k !=k2) /* logit p11 is hard to draw */
                fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);                fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
            }            }
            if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)            if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
              fprintf(ficgp,",");              fprintf(ficgp,",");
            if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))            if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
              fprintf(ficgp,",");              fprintf(ficgp,",");
            i=i+ncovmodel;            i=i+ncovmodel;
          } /* end k */          } /* end k */
        } /* end k2 */        } /* end k2 */
        fprintf(ficgp,"\n set out\n");        fprintf(ficgp,"\n set out\n");
      } /* end jk */      } /* end jk */
    } /* end ng */    } /* end ng */
  /* avoid: */    /* avoid: */
    fflush(ficgp);     fflush(ficgp); 
 }  /* end gnuplot */  }  /* end gnuplot */
   
   
 /*************** Moving average **************/  /*************** Moving average **************/
                 /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */  /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){   int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
         
   int i, cpt, cptcod;     int i, cpt, cptcod;
   int modcovmax =1;     int modcovmax =1;
   int mobilavrange, mob;     int mobilavrange, mob;
   double age;     int iage=0;
   int iage=0;  
   double *sumnewp, *sumnewm;     double sum=0.;
   double *agemingood, *agemaxgood; /* Currently identical for all covariates */     double age;
        double *sumnewp, *sumnewm;
   sumnewp = vector(1,modcovmax);     double *agemingood, *agemaxgood; /* Currently identical for all covariates */
   sumnewm = vector(1,modcovmax);    
   agemingood = vector(1,modcovmax);         
   agemaxgood = vector(1,modcovmax);     /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
        /*              a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
     
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose      sumnewp = vector(1,ncovcombmax);
                            a covariate has 2 modalities, should be equal to ncovcombmax  */     sumnewm = vector(1,ncovcombmax);
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */     agemingood = vector(1,ncovcombmax);  
        agemaxgood = vector(1,ncovcombmax);
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){  
     if(mobilav==1) mobilavrange=5; /* default */     for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
     else mobilavrange=mobilav;       sumnewm[cptcod]=0.;
     for (age=bage; age<=fage; age++)       sumnewp[cptcod]=0.;
       for (i=1; i<=nlstate;i++)       agemingood[cptcod]=0;
         for (cptcod=1;cptcod<=modcovmax;cptcod++)       agemaxgood[cptcod]=0;
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];     }
     /* We keep the original values on the extreme ages bage, fage and for      if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2    
        we use a 5 terms etc. until the borders are no more concerned.      if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
     */        if(mobilav==1) mobilavrange=5; /* default */
     for (mob=3;mob <=mobilavrange;mob=mob+2){       else mobilavrange=mobilav;
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){       for (age=bage; age<=fage; age++)
         for (i=1; i<=nlstate;i++){         for (i=1; i<=nlstate;i++)
           for (cptcod=1;cptcod<=modcovmax;cptcod++){           for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
             for (cpt=1;cpt<=(mob-1)/2;cpt++){       /* We keep the original values on the extreme ages bage, fage and for 
               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];          fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];          we use a 5 terms etc. until the borders are no more concerned. 
             }       */ 
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;       for (mob=3;mob <=mobilavrange;mob=mob+2){
           }         for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
         }           for (i=1; i<=nlstate;i++){
       }/* end age */             for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
     }/* end mob */               mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
   }else               for (cpt=1;cpt<=(mob-1)/2;cpt++){
     return -1;                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
   for (cptcod=1;cptcod<=modcovmax;cptcod++){                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
     /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */               }
     agemingood[cptcod]=fage+(mob-1)/2;               mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
     for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */             }
       sumnewm[cptcod]=0.;           }
       for (i=1; i<=nlstate;i++){         }/* end age */
         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];       }/* end mob */
       }     }else
       if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */       return -1;
         agemingood[cptcod]=age;     for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
       }else{ /* bad */       /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
         for (i=1; i<=nlstate;i++){       if(invalidvarcomb[cptcod]){
           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];         printf("\nCombination (%d) ignored because no cases \n",cptcod); 
         } /* i */         continue;
       } /* end bad */       }
     }/* age */  
     /* From youngest, finding the oldest wrong */       agemingood[cptcod]=fage-(mob-1)/2;
     agemaxgood[cptcod]=bage+(mob-1)/2;       for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
     for (age=bage+(mob-1)/2; age<=fage; age++){         sumnewm[cptcod]=0.;
       sumnewm[cptcod]=0.;         for (i=1; i<=nlstate;i++){
       for (i=1; i<=nlstate;i++){           sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];         }
       }         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
       if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */           agemingood[cptcod]=age;
         agemaxgood[cptcod]=age;         }else{ /* bad */
       }else{ /* bad */           for (i=1; i<=nlstate;i++){
         for (i=1; i<=nlstate;i++){             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];           } /* i */
         } /* i */         } /* end bad */
       } /* end bad */       }/* age */
     }/* age */       sum=0.;
     for (age=bage; age<=fage; age++){       for (i=1; i<=nlstate;i++){
       printf("%d %d ", cptcod, (int)age);         sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
       sumnewp[cptcod]=0.;       }
       sumnewm[cptcod]=0.;       if(fabs(sum - 1.) > 1.e-3) { /* bad */
       for (i=1; i<=nlstate;i++){         printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
         sumnewp[cptcod]+=probs[(int)age][i][cptcod];         /* for (i=1; i<=nlstate;i++){ */
         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];         /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
         printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]);         /* } /\* i *\/ */
       }       } /* end bad */
       printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]);       /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
     }       /* From youngest, finding the oldest wrong */
     printf("\n");       agemaxgood[cptcod]=bage+(mob-1)/2;
     /* brutal averaging */       for (age=bage+(mob-1)/2; age<=fage; age++){
     for (i=1; i<=nlstate;i++){         sumnewm[cptcod]=0.;
       for (age=1; age<=bage; age++){         for (i=1; i<=nlstate;i++){
         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];           sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
         printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]);         }
       }          if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
       for (age=fage; age<=AGESUP; age++){           agemaxgood[cptcod]=age;
         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];         }else{ /* bad */
         printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]);           for (i=1; i<=nlstate;i++){
       }             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
     } /* end i status */           } /* i */
     for (i=nlstate+1; i<=nlstate+ndeath;i++){         } /* end bad */
       for (age=1; age<=AGESUP; age++){       }/* age */
         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/       sum=0.;
         mobaverage[(int)age][i][cptcod]=0.;       for (i=1; i<=nlstate;i++){
       }         sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
     }       }
   }/* end cptcod */       if(fabs(sum - 1.) > 1.e-3) { /* bad */
   free_vector(sumnewm,1, modcovmax);         printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
   free_vector(sumnewp,1, modcovmax);         /* for (i=1; i<=nlstate;i++){ */
   free_vector(agemaxgood,1, modcovmax);         /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
   free_vector(agemingood,1, modcovmax);         /* } /\* i *\/ */
   return 0;       } /* end bad */
 }/* End movingaverage */                  
        for (age=bage; age<=fage; age++){
          printf("%d %d ", cptcod, (int)age);
          sumnewp[cptcod]=0.;
          sumnewm[cptcod]=0.;
          for (i=1; i<=nlstate;i++){
            sumnewp[cptcod]+=probs[(int)age][i][cptcod];
            sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
            /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
          }
          /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
        }
        /* printf("\n"); */
        /* } */
        /* brutal averaging */
        for (i=1; i<=nlstate;i++){
          for (age=1; age<=bage; age++){
            mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
            /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
          }        
          for (age=fage; age<=AGESUP; age++){
            mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
            /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
          }
        } /* end i status */
        for (i=nlstate+1; i<=nlstate+ndeath;i++){
          for (age=1; age<=AGESUP; age++){
            /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
            mobaverage[(int)age][i][cptcod]=0.;
          }
        }
      }/* end cptcod */
      free_vector(sumnewm,1, ncovcombmax);
      free_vector(sumnewp,1, ncovcombmax);
      free_vector(agemaxgood,1, ncovcombmax);
      free_vector(agemingood,1, ncovcombmax);
      return 0;
    }/* End movingaverage */
     
   
 /************** Forecasting ******************/  /************** Forecasting ******************/
Line 6358  void prevforecast(char fileres[], double Line 6580  void prevforecast(char fileres[], double
       k=k+1;        k=k+1;
       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");        fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
       for(j=1;j<=cptcoveff;j++) {        for(j=1;j<=cptcoveff;j++) {
         fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);                                  fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
       }        }
       fprintf(ficresf," yearproj age");        fprintf(ficresf," yearproj age");
       for(j=1; j<=nlstate+ndeath;j++){         for(j=1; j<=nlstate+ndeath;j++){ 
         for(i=1; i<=nlstate;i++)                                                for(i=1; i<=nlstate;i++)              
           fprintf(ficresf," p%d%d",i,j);            fprintf(ficresf," p%d%d",i,j);
         fprintf(ficresf," p.%d",j);                                  fprintf(ficresf," wp.%d",j);
       }        }
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
         fprintf(ficresf,"\n");                                  fprintf(ficresf,"\n");
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);                                     fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
         for (agec=fage; agec>=(ageminpar-1); agec--){                                   for (agec=fage; agec>=(ageminpar-1); agec--){ 
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);                                           nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
           nhstepm = nhstepm/hstepm;                                           nhstepm = nhstepm/hstepm; 
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                                          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           oldm=oldms;savm=savms;                                          oldm=oldms;savm=savms;
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);                                          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
                                                   
           for (h=0; h<=nhstepm; h++){                                          for (h=0; h<=nhstepm; h++){
             if (h*hstepm/YEARM*stepm ==yearp) {                                                  if (h*hstepm/YEARM*stepm ==yearp) {
               fprintf(ficresf,"\n");                fprintf(ficresf,"\n");
               for(j=1;j<=cptcoveff;j++)                 for(j=1;j<=cptcoveff;j++) 
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);                                                          fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
             }                                                   } 
             for(j=1; j<=nlstate+ndeath;j++) {                                                  for(j=1; j<=nlstate+ndeath;j++) {
               ppij=0.;                                                          ppij=0.;
               for(i=1; i<=nlstate;i++) {                                                          for(i=1; i<=nlstate;i++) {
                 if (mobilav==1)                                                                   if (mobilav==1) 
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];                                                                          ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                 else {                                                                  else {
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];                                                                          ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                 }                                                                  }
                 if (h*hstepm/YEARM*stepm== yearp) {                                                                  if (h*hstepm/YEARM*stepm== yearp) {
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);                                                                          fprintf(ficresf," %.3f", p3mat[i][j][h]);
                 }                                                                  }
               } /* end i */                                                          } /* end i */
               if (h*hstepm/YEARM*stepm==yearp) {                                                          if (h*hstepm/YEARM*stepm==yearp) {
                 fprintf(ficresf," %.3f", ppij);                                                                  fprintf(ficresf," %.3f", ppij);
               }                                                          }
             }/* end j */                                                  }/* end j */
           } /* end h */                                          } /* end h */
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                                          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         } /* end agec */                                  } /* end agec */
       } /* end yearp */        } /* end yearp */
     } /* end cptcod */      } /* end cptcod */
   } /* end  cptcov */    } /* end  cptcov */
                  
   fclose(ficresf);    fclose(ficresf);
   printf("End of Computing forecasting \n");    printf("End of Computing forecasting \n");
   fprintf(ficlog,"End of Computing forecasting\n");    fprintf(ficlog,"End of Computing forecasting\n");
Line 6843  double gompertz(double x[]) Line 7065  double gompertz(double x[])
   double A,B,L=0.0,sump=0.,num=0.;    double A,B,L=0.0,sump=0.,num=0.;
   int i,n=0; /* n is the size of the sample */    int i,n=0; /* n is the size of the sample */
   
   for (i=0;i<=imx-1 ; i++) {    for (i=1;i<=imx ; i++) {
     sump=sump+weight[i];      sump=sump+weight[i];
     /*    sump=sump+1;*/      /*    sump=sump+1;*/
     num=num+1;      num=num+1;
Line 6968  int readdata(char datafile[], int firsto Line 7190  int readdata(char datafile[], int firsto
   /*-------- data file ----------*/    /*-------- data file ----------*/
   FILE *fic;    FILE *fic;
   char dummy[]="                         ";    char dummy[]="                         ";
   int i=0, j=0, n=0;    int i=0, j=0, n=0, iv=0;
     int lstra;
   int linei, month, year,iout;    int linei, month, year,iout;
   char line[MAXLINE], linetmp[MAXLINE];    char line[MAXLINE], linetmp[MAXLINE];
   char stra[MAXLINE], strb[MAXLINE];    char stra[MAXLINE], strb[MAXLINE];
   char *stratrunc;    char *stratrunc;
   int lstra;  
   
   
   if((fic=fopen(datafile,"r"))==NULL)    {    if((fic=fopen(datafile,"r"))==NULL)    {
Line 6999  int readdata(char datafile[], int firsto Line 7222  int readdata(char datafile[], int firsto
       continue;        continue;
     }      }
     trimbb(linetmp,line); /* Trims multiple blanks in line */      trimbb(linetmp,line); /* Trims multiple blanks in line */
     strcpy(line, linetmp);      strcpy(line, linetmp);
         
       /* Loops on waves */
     for (j=maxwav;j>=1;j--){      for (j=maxwav;j>=1;j--){
         for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
                                   cutv(stra, strb, line, ' '); 
                                   if(strb[0]=='.') { /* Missing value */
                                           lval=-1;
                                   }else{
                                           errno=0;
                                           /* what_kind_of_number(strb); */
                                           dval=strtod(strb,&endptr); 
                                           /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                                           /* if(strb != endptr && *endptr == '\0') */
                                           /*    dval=dlval; */
                                           /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                                           if( strb[0]=='\0' || (*endptr != '\0')){
                                                   printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
                                                   fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
                                                   return 1;
                                           }
                                           cotqvar[j][iv][i]=dval; 
                                   }
                                   strcpy(line,stra);
         }/* end loop ntqv */
                           
         for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
                                   cutv(stra, strb, line, ' '); 
                                   if(strb[0]=='.') { /* Missing value */
                                           lval=-1;
                                   }else{
                                           errno=0;
                                           lval=strtol(strb,&endptr,10); 
                                           /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                                           if( strb[0]=='\0' || (*endptr != '\0')){
                                                   printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th dummy covariate out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv, j,maxwav);
                                                   fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d dummy covariate out of %d measured wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv,j,maxwav);fflush(ficlog);
                                                   return 1;
                                           }
                                   }
                                   if(lval <-1 || lval >1){
                                           printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
    Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
    for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
    For example, for multinomial values like 1, 2 and 3,\n                                                                 \
    build V1=0 V2=0 for the reference value (1),\n                                                                                                 \
           V1=1 V2=0 for (2) \n                                                                                                                                                                            \
    and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
    output of IMaCh is often meaningless.\n                                                                                                                                \
    Exiting.\n",lval,linei, i,line,j);
                                           fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
    Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
    for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
    For example, for multinomial values like 1, 2 and 3,\n                                                                 \
    build V1=0 V2=0 for the reference value (1),\n                                                                                                 \
           V1=1 V2=0 for (2) \n                                                                                                                                                                            \
    and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
    output of IMaCh is often meaningless.\n                                \
    Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                                           return 1;
                                   }
                                   cotvar[j][iv][i]=(double)(lval);
                                   strcpy(line,stra);
         }/* end loop ntv */
   
         /* Statuses  at wave */
       cutv(stra, strb, line, ' ');         cutv(stra, strb, line, ' '); 
       if(strb[0]=='.') { /* Missing status */        if(strb[0]=='.') { /* Missing value */
         lval=-1;                                  lval=-1;
       }else{        }else{
         errno=0;                                  errno=0;
         lval=strtol(strb,&endptr,10);                                   lval=strtol(strb,&endptr,10); 
       /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/                                  /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
         if( strb[0]=='\0' || (*endptr != '\0')){                                  if( strb[0]=='\0' || (*endptr != '\0')){
           printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);                                          printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);
           fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);fflush(ficlog);                                          fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);fflush(ficlog);
           return 1;                                          return 1;
         }                                  }
       }        }
        
       s[j][i]=lval;        s[j][i]=lval;
         
         /* Date of Interview */
       strcpy(line,stra);        strcpy(line,stra);
       cutv(stra, strb,line,' ');        cutv(stra, strb,line,' ');
       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){        if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
       }        }
       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){        else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
         month=99;                                  month=99;
         year=9999;                                  year=9999;
       }else{        }else{
         printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);                                  printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
         fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);fflush(ficlog);                                  fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);fflush(ficlog);
         return 1;                                  return 1;
       }        }
       anint[j][i]= (double) year;         anint[j][i]= (double) year; 
       mint[j][i]= (double)month;         mint[j][i]= (double)month; 
       strcpy(line,stra);        strcpy(line,stra);
     } /* ENd Waves */      } /* End loop on waves */
       
       /* Date of death */
     cutv(stra, strb,line,' ');       cutv(stra, strb,line,' '); 
     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){      if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
     }      }
Line 7043  int readdata(char datafile[], int firsto Line 7331  int readdata(char datafile[], int firsto
       year=9999;        year=9999;
     }else{      }else{
       printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);        printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
         fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);                          fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
         return 1;                          return 1;
     }      }
     andc[i]=(double) year;       andc[i]=(double) year; 
     moisdc[i]=(double) month;       moisdc[i]=(double) month; 
     strcpy(line,stra);      strcpy(line,stra);
           
       /* Date of birth */
     cutv(stra, strb,line,' ');       cutv(stra, strb,line,' '); 
     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){      if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
     }      }
Line 7059  int readdata(char datafile[], int firsto Line 7348  int readdata(char datafile[], int firsto
     }else{      }else{
       printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);        printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
       fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);        fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
         return 1;                          return 1;
     }      }
     if (year==9999) {      if (year==9999) {
       printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given.  Exiting.\n",strb, linei,i,line);        printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given.  Exiting.\n",strb, linei,i,line);
       fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given. Exiting.\n",strb, linei,i,line);fflush(ficlog);        fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given. Exiting.\n",strb, linei,i,line);fflush(ficlog);
         return 1;                          return 1;
   
     }      }
     annais[i]=(double)(year);      annais[i]=(double)(year);
     moisnais[i]=(double)(month);       moisnais[i]=(double)(month); 
     strcpy(line,stra);      strcpy(line,stra);
       
       /* Sample weight */
     cutv(stra, strb,line,' ');       cutv(stra, strb,line,' '); 
     errno=0;      errno=0;
     dval=strtod(strb,&endptr);       dval=strtod(strb,&endptr); 
Line 7082  int readdata(char datafile[], int firsto Line 7372  int readdata(char datafile[], int firsto
     }      }
     weight[i]=dval;       weight[i]=dval; 
     strcpy(line,stra);      strcpy(line,stra);
   
       for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
         cutv(stra, strb, line, ' '); 
         if(strb[0]=='.') { /* Missing value */
                                   lval=-1;
         }else{
                                   errno=0;
                                   /* what_kind_of_number(strb); */
                                   dval=strtod(strb,&endptr);
                                   /* if(strb != endptr && *endptr == '\0') */
                                   /*   dval=dlval; */
                                   /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                                   if( strb[0]=='\0' || (*endptr != '\0')){
                                           printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);
                                           fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);fflush(ficlog);
                                           return 1;
                                   }
                                   coqvar[iv][i]=dval; 
         }
         strcpy(line,stra);
       }/* end loop nqv */
           
       /* Covariate values */
     for (j=ncovcol;j>=1;j--){      for (j=ncovcol;j>=1;j--){
       cutv(stra, strb,line,' ');         cutv(stra, strb,line,' '); 
       if(strb[0]=='.') { /* Missing status */        if(strb[0]=='.') { /* Missing covariate value */
         lval=-1;                                  lval=-1;
       }else{        }else{
         errno=0;                                  errno=0;
         lval=strtol(strb,&endptr,10);                                   lval=strtol(strb,&endptr,10); 
         if( strb[0]=='\0' || (*endptr != '\0')){                                  if( strb[0]=='\0' || (*endptr != '\0')){
           printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);                                          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);
           fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);fflush(ficlog);                                          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);fflush(ficlog);
           return 1;                                          return 1;
         }                                  }
       }        }
       if(lval <-1 || lval >1){        if(lval <-1 || lval >1){
         printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \                                  printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \   for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
  For example, for multinomial values like 1, 2 and 3,\n \   For example, for multinomial values like 1, 2 and 3,\n \
Line 7106  int readdata(char datafile[], int firsto Line 7418  int readdata(char datafile[], int firsto
  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
  output of IMaCh is often meaningless.\n \   output of IMaCh is often meaningless.\n \
  Exiting.\n",lval,linei, i,line,j);   Exiting.\n",lval,linei, i,line,j);
         fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \                                  fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \   for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
  For example, for multinomial values like 1, 2 and 3,\n \   For example, for multinomial values like 1, 2 and 3,\n \
Line 7115  int readdata(char datafile[], int firsto Line 7427  int readdata(char datafile[], int firsto
  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
  output of IMaCh is often meaningless.\n \   output of IMaCh is often meaningless.\n \
  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);   Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
         return 1;                                  return 1;
       }        }
       covar[j][i]=(double)(lval);        covar[j][i]=(double)(lval);
       strcpy(line,stra);        strcpy(line,stra);
Line 7139  int readdata(char datafile[], int firsto Line 7451  int readdata(char datafile[], int firsto
     
   return (0);    return (0);
   /* endread: */    /* endread: */
     printf("Exiting readdata: ");          printf("Exiting readdata: ");
     fclose(fic);          fclose(fic);
     return (1);          return (1);
   
   
   
 }  }
   
 void removespace(char *str) {  void removespace(char *str) {
   char *p1 = str, *p2 = str;    char *p1 = str, *p2 = str;
   do    do
Line 7276  int decodemodel ( char model[], int last Line 7586  int decodemodel ( char model[], int last
         Tvar[k]=0;          Tvar[k]=0;
       cptcovage=0;        cptcovage=0;
       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */        for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
         cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'                                   cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                                          modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */                                                                                                                                                                    modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
         if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */                                  if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
         /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/                                  /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
         /*scanf("%d",i);*/                                  /*scanf("%d",i);*/
         if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */                                  if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
           cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */                                          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
           if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */                                          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
             /* covar is not filled and then is empty */                                                  /* covar is not filled and then is empty */
             cptcovprod--;                                                  cptcovprod--;
             cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */                                                  cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
             Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */                                                  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
             cptcovage++; /* Sums the number of covariates which include age as a product */                                                  cptcovage++; /* Sums the number of covariates which include age as a product */
             Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */                                                  Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
             /*printf("stre=%s ", stre);*/                                                  /*printf("stre=%s ", stre);*/
           } else if (strcmp(strd,"age")==0) { /* or age*Vn */                                          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
             cptcovprod--;                                                  cptcovprod--;
             cutl(stre,strb,strc,'V');                                                  cutl(stre,strb,strc,'V');
             Tvar[k]=atoi(stre);                                                  Tvar[k]=atoi(stre);
             cptcovage++;                                                  cptcovage++;
             Tage[cptcovage]=k;                                                  Tage[cptcovage]=k;
           } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/                                          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
             /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */                                                  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
             cptcovn++;                                                  cptcovn++;
             cptcovprodnoage++;k1++;                                                  cptcovprodnoage++;k1++;
             cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/                                                  cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
             Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but                                                  Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                                    because this model-covariate is a construction we invent a new column                                                                                                                                           because this model-covariate is a construction we invent a new column
                                    ncovcol + k1                                                                                                                                           ncovcol + k1
                                    If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2                                                                                                                                           If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                                    Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */                                                                                                                                           Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
             cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */                                                  cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
             Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */                                                  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
             Tvard[k1][1] =atoi(strc); /* m 1 for V1*/                                                  Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
             Tvard[k1][2] =atoi(stre); /* n 4 for V4*/                                                  Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
             k2=k2+2;                                                  k2=k2+2;
             Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */                                                  Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
             Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */                                                  Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
             for (i=1; i<=lastobs;i++){                                                  for (i=1; i<=lastobs;i++){
               /* Computes the new covariate which is a product of                                                          /* Computes the new covariate which is a product of
                  covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */                                                                   covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
               covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];                                                          covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
             }                                                  }
           } /* End age is not in the model */                                          } /* End age is not in the model */
         } /* End if model includes a product */                                  } /* End if model includes a product */
         else { /* no more sum */                                  else { /* no more sum */
           /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/                                          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
           /*  scanf("%d",i);*/                                          /*  scanf("%d",i);*/
           cutl(strd,strc,strb,'V');                                          cutl(strd,strc,strb,'V');
           ks++; /**< Number of simple covariates */                                          ks++; /**< Number of simple covariates */
           cptcovn++;                                          cptcovn++;
           Tvar[k]=atoi(strd);                                          Tvar[k]=atoi(strd);
         }                                  }
         strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */                                   strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
         /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);                                  /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
           scanf("%d",i);*/                                          scanf("%d",i);*/
       } /* end of loop + on total covariates */        } /* end of loop + on total covariates */
     } /* end if strlen(modelsave == 0) age*age might exist */      } /* end if strlen(modelsave == 0) age*age might exist */
   } /* end if strlen(model == 0) */    } /* end if strlen(model == 0) */
Line 7656  void syscompilerinfo(int logged) Line 7966  void syscompilerinfo(int logged)
 #endif  #endif
         
   
  }  }
   
  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/    /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
   int i, j, k, i1 ;    int i, j, k, i1 ;
   /* double ftolpl = 1.e-10; */    /* double ftolpl = 1.e-10; */
Line 7679  void syscompilerinfo(int logged) Line 7989  void syscompilerinfo(int logged)
   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);    for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
   fprintf(ficrespl,"\n");    fprintf(ficrespl,"\n");
       
     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */    /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
   
     agebase=ageminpar;    agebase=ageminpar;
     agelim=agemaxpar;    agelim=agemaxpar;
   
     i1=pow(2,cptcoveff);    i1=pow(2,cptcoveff);
     if (cptcovn < 1){i1=1;}    if (cptcovn < 1){i1=1;}
   
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){    for(k=1; k<=i1;k++){
     /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */      /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
         k=k+1;      /* k=k+1; */
         /* to clean */      /* to clean */
         //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));      //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
         fprintf(ficrespl,"#******");      fprintf(ficrespl,"#******");
         printf("#******");      printf("#******");
         fprintf(ficlog,"#******");      fprintf(ficlog,"#******");
         for(j=1;j<=cptcoveff;j++) {      for(j=1;j<=cptcoveff;j++) {
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
         }      }
         fprintf(ficrespl,"******\n");      fprintf(ficrespl,"******\n");
         printf("******\n");      printf("******\n");
         fprintf(ficlog,"******\n");      fprintf(ficlog,"******\n");
                   if(invalidvarcomb[k]){
         fprintf(ficrespl,"#Age ");                                                  printf("\nCombination (%d) ignored because no cases \n",k); 
         for(j=1;j<=cptcoveff;j++) {                                                  fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
           fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);                                                  fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
         }                                                  continue;
         for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);                  }
         fprintf(ficrespl,"Total Years_to_converge\n");  
       fprintf(ficrespl,"#Age ");
       for(j=1;j<=cptcoveff;j++) {
         fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
       }
       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
       fprintf(ficrespl,"Total Years_to_converge\n");
                   
         for (age=agebase; age<=agelim; age++){      for (age=agebase; age<=agelim; age++){
         /* for (age=agebase; age<=agebase; age++){ */        /* for (age=agebase; age<=agebase; age++){ */
           prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
           fprintf(ficrespl,"%.0f ",age );        fprintf(ficrespl,"%.0f ",age );
           for(j=1;j<=cptcoveff;j++)        for(j=1;j<=cptcoveff;j++)
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);                                                          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
           tot=0.;        tot=0.;
           for(i=1; i<=nlstate;i++){        for(i=1; i<=nlstate;i++){
             tot +=  prlim[i][i];                                                          tot +=  prlim[i][i];
             fprintf(ficrespl," %.5f", prlim[i][i]);                                                          fprintf(ficrespl," %.5f", prlim[i][i]);
           }        }
           fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
         } /* Age */      } /* Age */
         /* was end of cptcod */      /* was end of cptcod */
     } /* cptcov */    } /* cptcov */
         return 0;    return 0;
 }  }
   
 int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){  int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
Line 7766  int back_prevalence_limit(double *p, dou Line 8083  int back_prevalence_limit(double *p, dou
       
   i1=pow(2,cptcoveff);    i1=pow(2,cptcoveff);
   if (cptcovn < 1){i1=1;}    if (cptcovn < 1){i1=1;}
     
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){          for(k=1; k<=i1;k++){ 
     /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */      /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
     k=k+1;      /* k=k+1; */
     /* to clean */      /* to clean */
     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));      //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
     fprintf(ficresplb,"#******");      fprintf(ficresplb,"#******");
Line 7784  int back_prevalence_limit(double *p, dou Line 8102  int back_prevalence_limit(double *p, dou
     fprintf(ficresplb,"******\n");      fprintf(ficresplb,"******\n");
     printf("******\n");      printf("******\n");
     fprintf(ficlog,"******\n");      fprintf(ficlog,"******\n");
                   if(invalidvarcomb[k]){
                                                   printf("\nCombination (%d) ignored because no cases \n",k); 
                                                   fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                                                   fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                                                   continue;
                   }
           
     fprintf(ficresplb,"#Age ");      fprintf(ficresplb,"#Age ");
     for(j=1;j<=cptcoveff;j++) {      for(j=1;j<=cptcoveff;j++) {
Line 7798  int back_prevalence_limit(double *p, dou Line 8122  int back_prevalence_limit(double *p, dou
       if(mobilavproj > 0){        if(mobilavproj > 0){
         /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
         /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
         bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);                                  bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
       }else if (mobilavproj == 0){        }else if (mobilavproj == 0){
         printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);                                  printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
         fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);                                  fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
         exit(1);                                  exit(1);
       }else{        }else{
         /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */                                  /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
         bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);                                  bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
       }        }
       fprintf(ficresplb,"%.0f ",age );        fprintf(ficresplb,"%.0f ",age );
       for(j=1;j<=cptcoveff;j++)        for(j=1;j<=cptcoveff;j++)
         fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);                                  fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
       tot=0.;        tot=0.;
       for(i=1; i<=nlstate;i++){        for(i=1; i<=nlstate;i++){
         tot +=  bprlim[i][i];                                  tot +=  bprlim[i][i];
         fprintf(ficresplb," %.5f", bprlim[i][i]);                                  fprintf(ficresplb," %.5f", bprlim[i][i]);
       }        }
       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
     } /* Age */      } /* Age */
Line 7937  int hPijx(double *p, int bage, int fage) Line 8261  int hPijx(double *p, int bage, int fage)
     for(j=1;j<=cptcoveff;j++)      for(j=1;j<=cptcoveff;j++)
       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
     fprintf(ficrespijb,"******\n");      fprintf(ficrespijb,"******\n");
       if(invalidvarcomb[k]){
         fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
         continue;
       }
           
     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */      /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */      for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
Line 8004  int main(int argc, char *argv[]) Line 8332  int main(int argc, char *argv[])
   double agedeb=0.;    double agedeb=0.;
   
   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;    double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
         double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */    double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
   
   double fret;    double fret;
   double dum=0.; /* Dummy variable */    double dum=0.; /* Dummy variable */
Line 8251  int main(int argc, char *argv[]) Line 8579  int main(int argc, char *argv[])
     }else      }else
       break;        break;
   }    }
   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \    if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                         &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){                          &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
     if (num_filled != 8) {      if (num_filled != 11) {
       printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");        printf("Not 11 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nqv=1 ntv=2 nqtv=1  nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
       printf("but line=%s\n",line);        printf("but line=%s\n",line);
     }      }
     printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);      printf("ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
   }    }
   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */    /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */    /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
Line 8295  int main(int argc, char *argv[]) Line 8623  int main(int argc, char *argv[])
   /* 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=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model); */    /* 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=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model); */
   /* numlinepar=numlinepar+3; /\* In general *\/ */    /* numlinepar=numlinepar+3; /\* In general *\/ */
   /* 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=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */    /* 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=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */
   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=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
   fprintf(ficlog,"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=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
   fflush(ficlog);    fflush(ficlog);
   /* if(model[0]=='#'|| model[0]== '\0'){ */    /* if(model[0]=='#'|| model[0]== '\0'){ */
   if(model[0]=='#'){    if(model[0]=='#'){
Line 8325  int main(int argc, char *argv[]) Line 8653  int main(int argc, char *argv[])
   
         
   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */    covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
     coqvar=matrix(1,nqv,1,n);  /**< used in readdata */
     cotvar=ma3x(1,maxwav,1,ntv,1,n);  /**< used in readdata */
     cotqvar=ma3x(1,maxwav,1,ntqv,1,n);  /**< used in readdata */
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5    /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
      v1+v2*age+v2*v3 makes cptcovn = 3       v1+v2*age+v2*v3 makes cptcovn = 3
Line 8354  int main(int argc, char *argv[]) Line 8685  int main(int argc, char *argv[])
     fclose (ficlog);      fclose (ficlog);
     goto end;      goto end;
     exit(0);      exit(0);
   }    }  else if(mle==-5) { /* Main Wizard */
   else if(mle==-3) { /* Main Wizard */  
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);      printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);      fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     matcov=matrix(1,npar,1,npar);      matcov=matrix(1,npar,1,npar);
     hess=matrix(1,npar,1,npar);      hess=matrix(1,npar,1,npar);
   }    }  else{ /* Begin of mle != -1 or -5 */
   else{  
     /* Read guessed parameters */      /* Read guessed parameters */
     /* Reads comments: lines beginning with '#' */      /* Reads comments: lines beginning with '#' */
     while((c=getc(ficpar))=='#' && c!= EOF){      while((c=getc(ficpar))=='#' && c!= EOF){
Line 8378  int main(int argc, char *argv[]) Line 8707  int main(int argc, char *argv[])
           
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     for(i=1; i <=nlstate; i++){      for(i=1; i <=nlstate; i++){
       j=0;                          j=0;
       for(jj=1; jj <=nlstate+ndeath; jj++){        for(jj=1; jj <=nlstate+ndeath; jj++){
         if(jj==i) continue;                                  if(jj==i) continue;
         j++;                                  j++;
         fscanf(ficpar,"%1d%1d",&i1,&j1);                                  fscanf(ficpar,"%1d%1d",&i1,&j1);
         if ((i1 != i) || (j1 != jj)){                                  if ((i1 != i) || (j1 != jj)){
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \                                          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 It might be a problem of design; if ncovcol and the model are correct\n \  It might be a problem of design; if ncovcol and the model are correct\n \
 run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
           exit(1);                                          exit(1);
         }                                  }
         fprintf(ficparo,"%1d%1d",i1,j1);                                  fprintf(ficparo,"%1d%1d",i1,j1);
         if(mle==1)                                  if(mle==1)
           printf("%1d%1d",i,jj);                                          printf("%1d%1d",i,jj);
         fprintf(ficlog,"%1d%1d",i,jj);                                  fprintf(ficlog,"%1d%1d",i,jj);
         for(k=1; k<=ncovmodel;k++){                                  for(k=1; k<=ncovmodel;k++){
           fscanf(ficpar," %lf",&param[i][j][k]);                                          fscanf(ficpar," %lf",&param[i][j][k]);
           if(mle==1){                                          if(mle==1){
             printf(" %lf",param[i][j][k]);                                                  printf(" %lf",param[i][j][k]);
             fprintf(ficlog," %lf",param[i][j][k]);                                                  fprintf(ficlog," %lf",param[i][j][k]);
           }                                          }
           else                                          else
             fprintf(ficlog," %lf",param[i][j][k]);                                                  fprintf(ficlog," %lf",param[i][j][k]);
           fprintf(ficparo," %lf",param[i][j][k]);                                          fprintf(ficparo," %lf",param[i][j][k]);
         }                                  }
         fscanf(ficpar,"\n");                                  fscanf(ficpar,"\n");
         numlinepar++;                                  numlinepar++;
         if(mle==1)                                  if(mle==1)
           printf("\n");                                          printf("\n");
         fprintf(ficlog,"\n");                                  fprintf(ficlog,"\n");
         fprintf(ficparo,"\n");                                  fprintf(ficparo,"\n");
       }        }
     }        }  
     fflush(ficlog);      fflush(ficlog);
Line 8429  run imach with mle=-1 to get a correct t Line 8758  run imach with mle=-1 to get a correct t
   
     for(i=1; i <=nlstate; i++){      for(i=1; i <=nlstate; i++){
       for(j=1; j <=nlstate+ndeath-1; j++){        for(j=1; j <=nlstate+ndeath-1; j++){
         fscanf(ficpar,"%1d%1d",&i1,&j1);                                  fscanf(ficpar,"%1d%1d",&i1,&j1);
         if ( (i1-i) * (j1-j) != 0){                                  if ( (i1-i) * (j1-j) != 0){
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);                                          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
           exit(1);                                          exit(1);
         }                                  }
         printf("%1d%1d",i,j);                                  printf("%1d%1d",i,j);
         fprintf(ficparo,"%1d%1d",i1,j1);                                  fprintf(ficparo,"%1d%1d",i1,j1);
         fprintf(ficlog,"%1d%1d",i1,j1);                                  fprintf(ficlog,"%1d%1d",i1,j1);
         for(k=1; k<=ncovmodel;k++){                                  for(k=1; k<=ncovmodel;k++){
           fscanf(ficpar,"%le",&delti3[i][j][k]);                                          fscanf(ficpar,"%le",&delti3[i][j][k]);
           printf(" %le",delti3[i][j][k]);                                          printf(" %le",delti3[i][j][k]);
           fprintf(ficparo," %le",delti3[i][j][k]);                                          fprintf(ficparo," %le",delti3[i][j][k]);
           fprintf(ficlog," %le",delti3[i][j][k]);                                          fprintf(ficlog," %le",delti3[i][j][k]);
         }                                  }
         fscanf(ficpar,"\n");                                  fscanf(ficpar,"\n");
         numlinepar++;                                  numlinepar++;
         printf("\n");                                  printf("\n");
         fprintf(ficparo,"\n");                                  fprintf(ficparo,"\n");
         fprintf(ficlog,"\n");                                  fprintf(ficlog,"\n");
       }        }
     }      }
     fflush(ficlog);      fflush(ficlog);
                   
     /* Reads covariance matrix */      /* Reads covariance matrix */
     delti=delti3[1][1];      delti=delti3[1][1];
                   
                   
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                     
     /* Reads comments: lines beginning with '#' */      /* Reads comments: lines beginning with '#' */
     while((c=getc(ficpar))=='#' && c!= EOF){      while((c=getc(ficpar))=='#' && c!= EOF){
       ungetc(c,ficpar);        ungetc(c,ficpar);
Line 8468  run imach with mle=-1 to get a correct t Line 8797  run imach with mle=-1 to get a correct t
       fputs(line,ficlog);        fputs(line,ficlog);
     }      }
     ungetc(c,ficpar);      ungetc(c,ficpar);
                     
     matcov=matrix(1,npar,1,npar);      matcov=matrix(1,npar,1,npar);
     hess=matrix(1,npar,1,npar);      hess=matrix(1,npar,1,npar);
     for(i=1; i <=npar; i++)      for(i=1; i <=npar; i++)
       for(j=1; j <=npar; j++) matcov[i][j]=0.;        for(j=1; j <=npar; j++) matcov[i][j]=0.;
                         
     /* Scans npar lines */      /* Scans npar lines */
     for(i=1; i <=npar; i++){      for(i=1; i <=npar; i++){
       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);        count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
       if(count != 3){        if(count != 3){
         printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\                                  printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\  This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);  Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
         fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\                                  fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\  This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);  Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
         exit(1);                                  exit(1);
       }else        }else{
         if(mle==1)                                  if(mle==1)
           printf("%1d%1d%1d",i1,j1,jk);                                          printf("%1d%1d%1d",i1,j1,jk);
                           }
       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);        fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);        fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
       for(j=1; j <=i; j++){        for(j=1; j <=i; j++){
         fscanf(ficpar," %le",&matcov[i][j]);                                  fscanf(ficpar," %le",&matcov[i][j]);
         if(mle==1){                                  if(mle==1){
           printf(" %.5le",matcov[i][j]);                                          printf(" %.5le",matcov[i][j]);
         }                                  }
         fprintf(ficlog," %.5le",matcov[i][j]);                                  fprintf(ficlog," %.5le",matcov[i][j]);
         fprintf(ficparo," %.5le",matcov[i][j]);                                  fprintf(ficparo," %.5le",matcov[i][j]);
       }        }
       fscanf(ficpar,"\n");        fscanf(ficpar,"\n");
       numlinepar++;        numlinepar++;
       if(mle==1)        if(mle==1)
         printf("\n");                                  printf("\n");
       fprintf(ficlog,"\n");        fprintf(ficlog,"\n");
       fprintf(ficparo,"\n");        fprintf(ficparo,"\n");
     }      }
     /* End of read covariance matrix npar lines */      /* End of read covariance matrix npar lines */
     for(i=1; i <=npar; i++)      for(i=1; i <=npar; i++)
       for(j=i+1;j<=npar;j++)        for(j=i+1;j<=npar;j++)
         matcov[i][j]=matcov[j][i];                                  matcov[i][j]=matcov[j][i];
           
     if(mle==1)      if(mle==1)
       printf("\n");        printf("\n");
Line 8536  Please run with mle=-1 to get a correct Line 8866  Please run with mle=-1 to get a correct
   annais=vector(1,n);    annais=vector(1,n);
   moisdc=vector(1,n);    moisdc=vector(1,n);
   andc=vector(1,n);    andc=vector(1,n);
     weight=vector(1,n);
   agedc=vector(1,n);    agedc=vector(1,n);
   cod=ivector(1,n);    cod=ivector(1,n);
   weight=vector(1,n);    for(i=1;i<=n;i++){
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */                  num[i]=0;
                   moisnais[i]=0;
                   annais[i]=0;
                   moisdc[i]=0;
                   andc[i]=0;
                   agedc[i]=0;
                   cod[i]=0;
                   weight[i]=1.0; /* Equal weights, 1 by default */
           }
   mint=matrix(1,maxwav,1,n);    mint=matrix(1,maxwav,1,n);
   anint=matrix(1,maxwav,1,n);    anint=matrix(1,maxwav,1,n);
   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */     s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
Line 8584  Please run with mle=-1 to get a correct Line 8923  Please run with mle=-1 to get a correct
 /* Main decodemodel */  /* Main decodemodel */
   
   
   if(decodemodel(model, lastobs) == 1)    if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
     goto end;      goto end;
   
   if((double)(lastobs-imx)/(double)imx > 1.10){    if((double)(lastobs-imx)/(double)imx > 1.10){
Line 8636  Please run with mle=-1 to get a correct Line 8975  Please run with mle=-1 to get a correct
   free_vector(andc,1,n);    free_vector(andc,1,n);
   
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
   
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);     nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
   ncodemax[1]=1;    ncodemax[1]=1;
   Ndum =ivector(-1,NCOVMAX);      Ndum =ivector(-1,NCOVMAX);  
   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */          cptcoveff=0;
     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */    if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
       tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
           }
           
           ncovcombmax=pow(2,cptcoveff);
           invalidvarcomb=ivector(1, ncovcombmax); 
           for(i=1;i<ncovcombmax;i++)
                   invalidvarcomb[i]=0;
   
   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in    /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/       V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */    /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
Line 8657  Please run with mle=-1 to get a correct Line 9003  Please run with mle=-1 to get a correct
    */     */
   
   h=0;    h=0;
   
   
   /*if (cptcovn > 0) */    /*if (cptcovn > 0) */
         
    
   m=pow(2,cptcoveff);    m=pow(2,cptcoveff);
     
           /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1            /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
Line 8702  Please run with mle=-1 to get a correct Line 9044  Please run with mle=-1 to get a correct
      *              bbbbbbbb       *              bbbbbbbb
      *              76543210            *              76543210     
      *   h-1        00000101 (6-1=5)       *   h-1        00000101 (6-1=5)
      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift       *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
      *           &       *           &
      *     1        00000001 (1)       *     1        00000001 (1)
      *              00000001        = 1 & ((h-1) >> (k-1))       *              00000000        = 1 & ((h-1) >> (k-1))
      *          +1= 00000010 =2        *          +1= 00000001 =1 
      *       *
      * h=14, k=3 => h'=h-1=13, k'=k-1=2       * h=14, k=3 => h'=h-1=13, k'=k-1=2
      *          h'      1101 =2^3+2^2+0x2^1+2^0       *          h'      1101 =2^3+2^2+0x2^1+2^0
Line 8728  Please run with mle=-1 to get a correct Line 9070  Please run with mle=-1 to get a correct
      *                  2211       *                  2211
      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1       *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
      *                  V3=2       *                  V3=2
                    * codtabm and decodtabm are identical
      */       */
   
   /* /\* for(h=1; h <=100 ;h++){  *\/ */  
   /*   /\* printf("h=%2d ", h); *\/ */  
   /*    /\* for(k=1; k <=10; k++){ *\/ */  
   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */  
   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */  
   /*    /\* } *\/ */  
   /*    /\* printf("\n"); *\/ */  
   /* } */  
   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */  
   /*   for(i=1; i <=pow(2,cptcoveff-k);i++){ /\* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 *\/  */  
   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */  
   /*    for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */  
   /*      h++; */  
   /*      if (h>m)  */  
   /*        h=1; */  
   /*      codtab[h][k]=j; */  
   /*      /\* codtab[12][3]=1; *\/ */  
   /*      /\*codtab[h][Tvar[k]]=j;*\/ */  
   /*      /\* printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]); *\/ */  
   /*    }  */  
   /*     } */  
   /*   } */  
   /* }  */  
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);   
      codtab[1][2]=1;codtab[2][2]=2; */  
   /* for(i=1; i <=m ;i++){  */  
   /*    for(k=1; k <=cptcovn; k++){ */  
   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */  
   /*    } */  
   /*    printf("\n"); */  
   /* } */  
   /*   scanf("%d",i);*/  
   
  free_ivector(Ndum,-1,NCOVMAX);   free_ivector(Ndum,-1,NCOVMAX);
   
Line 8836  Title=%s <br>Datafile=%s Firstpass=%d La Line 9147  Title=%s <br>Datafile=%s Firstpass=%d La
 #endif  #endif
                       
       
   /* Calculates basic frequencies. Computes observed prevalence at single age    /* Calculates basic frequencies. Computes observed prevalence at single age 
                    and for any valid combination of covariates
      and prints on file fileres'p'. */       and prints on file fileres'p'. */
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,    \
               firstpass, lastpass,  stepm,  weightopt, model);                                                          firstpass, lastpass,  stepm,  weightopt, model);
   
   fprintf(fichtm,"\n");    fprintf(fichtm,"\n");
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
Line 8847  Youngest age at first (selected) pass %. Line 9159  Youngest age at first (selected) pass %.
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\  Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
           imx,agemin,agemax,jmin,jmax,jmean);            imx,agemin,agemax,jmin,jmax,jmean);
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */          oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */          newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */          savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */          oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
   
   /* For Powell, parameters are in a vector p[] starting at p[1]    /* For Powell, parameters are in a vector p[] starting at p[1]
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
Line 8860  Interval (in months) between two waves: Line 9172  Interval (in months) between two waves:
   /* For mortality only */    /* For mortality only */
   if (mle==-3){    if (mle==-3){
     ximort=matrix(1,NDIM,1,NDIM);       ximort=matrix(1,NDIM,1,NDIM); 
                   for(i=1;i<=NDIM;i++)
                           for(j=1;j<=NDIM;j++)
                                   ximort[i][j]=0.;
     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */      /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
     cens=ivector(1,n);      cens=ivector(1,n);
     ageexmed=vector(1,n);      ageexmed=vector(1,n);
     agecens=vector(1,n);      agecens=vector(1,n);
     dcwave=ivector(1,n);      dcwave=ivector(1,n);
                    
     for (i=1; i<=imx; i++){      for (i=1; i<=imx; i++){
       dcwave[i]=-1;        dcwave[i]=-1;
       for (m=firstpass; m<=lastpass; m++)        for (m=firstpass; m<=lastpass; m++)
Line 9008  Interval (in months) between two waves: Line 9323  Interval (in months) between two waves:
   
     for(i=1; i <=NDIM; i++)      for(i=1; i <=NDIM; i++)
       for(j=i+1;j<=NDIM;j++)        for(j=i+1;j<=NDIM;j++)
         matcov[i][j]=matcov[j][i];                                  matcov[i][j]=matcov[j][i];
           
     printf("\nCovariance matrix\n ");      printf("\nCovariance matrix\n ");
     fprintf(ficlog,"\nCovariance matrix\n ");      fprintf(ficlog,"\nCovariance matrix\n ");
     for(i=1; i <=NDIM; i++) {      for(i=1; i <=NDIM; i++) {
       for(j=1;j<=NDIM;j++){         for(j=1;j<=NDIM;j++){ 
         printf("%f ",matcov[i][j]);                                  printf("%f ",matcov[i][j]);
         fprintf(ficlog,"%f ",matcov[i][j]);                                  fprintf(ficlog,"%f ",matcov[i][j]);
       }        }
       printf("\n ");  fprintf(ficlog,"\n ");        printf("\n ");  fprintf(ficlog,"\n ");
     }      }
Line 9056  Interval (in months) between two waves: Line 9371  Interval (in months) between two waves:
           
           
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   ageminpar=50;
                   agemaxpar=100;
     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){      if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
         printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\          printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\  This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
Line 9063  Please run with mle=-1 to get a correct Line 9380  Please run with mle=-1 to get a correct
         fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\          fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\  This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);  Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
     }else      }else{
                           printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                           fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);        printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   }
     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \      printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
                      stepm, weightopt,\                       stepm, weightopt,\
                      model,imx,p,matcov,agemortsup);                       model,imx,p,matcov,agemortsup);
Line 9072  Please run with mle=-1 to get a correct Line 9392  Please run with mle=-1 to get a correct
     free_vector(lsurv,1,AGESUP);      free_vector(lsurv,1,AGESUP);
     free_vector(lpop,1,AGESUP);      free_vector(lpop,1,AGESUP);
     free_vector(tpop,1,AGESUP);      free_vector(tpop,1,AGESUP);
 #ifdef GSL      free_matrix(ximort,1,NDIM,1,NDIM);
     free_ivector(cens,1,n);      free_ivector(cens,1,n);
     free_vector(agecens,1,n);      free_vector(agecens,1,n);
     free_ivector(dcwave,1,n);      free_ivector(dcwave,1,n);
     free_matrix(ximort,1,NDIM,1,NDIM);  #ifdef GSL
 #endif  #endif
   } /* Endof if mle==-3 mortality only */    } /* Endof if mle==-3 mortality only */
   /* Standard  */    /* Standard  */
Line 9113  Please run with mle=-1 to get a correct Line 9433  Please run with mle=-1 to get a correct
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     for(i=1,jk=1; i <=nlstate; i++){      for(i=1,jk=1; i <=nlstate; i++){
       for(k=1; k <=(nlstate+ndeath); k++){        for(k=1; k <=(nlstate+ndeath); k++){
         if (k != i) {                                  if (k != i) {
           printf("%d%d ",i,k);                                          printf("%d%d ",i,k);
           fprintf(ficlog,"%d%d ",i,k);                                          fprintf(ficlog,"%d%d ",i,k);
           fprintf(ficres,"%1d%1d ",i,k);                                          fprintf(ficres,"%1d%1d ",i,k);
           for(j=1; j <=ncovmodel; j++){                                          for(j=1; j <=ncovmodel; j++){
             printf("%12.7f ",p[jk]);                                                  printf("%12.7f ",p[jk]);
             fprintf(ficlog,"%12.7f ",p[jk]);                                                  fprintf(ficlog,"%12.7f ",p[jk]);
             fprintf(ficres,"%12.7f ",p[jk]);                                                  fprintf(ficres,"%12.7f ",p[jk]);
             jk++;                                                   jk++; 
           }                                          }
           printf("\n");                                          printf("\n");
           fprintf(ficlog,"\n");                                          fprintf(ficlog,"\n");
           fprintf(ficres,"\n");                                          fprintf(ficres,"\n");
         }                                  }
       }        }
     }      }
     if(mle != 0){      if(mle != 0){
Line 9136  Please run with mle=-1 to get a correct Line 9456  Please run with mle=-1 to get a correct
       printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");        printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
       fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n  It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");        fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n  It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
       for(i=1,jk=1; i <=nlstate; i++){        for(i=1,jk=1; i <=nlstate; i++){
         for(k=1; k <=(nlstate+ndeath); k++){                                  for(k=1; k <=(nlstate+ndeath); k++){
           if (k != i) {                                          if (k != i) {
             printf("%d%d ",i,k);                                                  printf("%d%d ",i,k);
             fprintf(ficlog,"%d%d ",i,k);                                                  fprintf(ficlog,"%d%d ",i,k);
             for(j=1; j <=ncovmodel; j++){                                                  for(j=1; j <=ncovmodel; j++){
               printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));                                                          printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
               fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));                                                          fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
               jk++;                                                           jk++; 
             }                                                  }
             printf("\n");                                                  printf("\n");
             fprintf(ficlog,"\n");                                                  fprintf(ficlog,"\n");
           }                                          }
         }                                  }
       }        }
     } /* end of hesscov and Wald tests */      } /* end of hesscov and Wald tests */
                   
     /*  */      /*  */
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
     printf("# Scales (for hessian or gradient estimation)\n");      printf("# Scales (for hessian or gradient estimation)\n");
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
     for(i=1,jk=1; i <=nlstate; i++){      for(i=1,jk=1; i <=nlstate; i++){
       for(j=1; j <=nlstate+ndeath; j++){        for(j=1; j <=nlstate+ndeath; j++){
         if (j!=i) {                                  if (j!=i) {
           fprintf(ficres,"%1d%1d",i,j);                                          fprintf(ficres,"%1d%1d",i,j);
           printf("%1d%1d",i,j);                                          printf("%1d%1d",i,j);
           fprintf(ficlog,"%1d%1d",i,j);                                          fprintf(ficlog,"%1d%1d",i,j);
           for(k=1; k<=ncovmodel;k++){                                          for(k=1; k<=ncovmodel;k++){
             printf(" %.5e",delti[jk]);                                                  printf(" %.5e",delti[jk]);
             fprintf(ficlog," %.5e",delti[jk]);                                                  fprintf(ficlog," %.5e",delti[jk]);
             fprintf(ficres," %.5e",delti[jk]);                                                  fprintf(ficres," %.5e",delti[jk]);
             jk++;                                                  jk++;
           }                                          }
           printf("\n");                                          printf("\n");
           fprintf(ficlog,"\n");                                          fprintf(ficlog,"\n");
           fprintf(ficres,"\n");                                          fprintf(ficres,"\n");
         }                                  }
       }        }
     }      }
           
Line 9195  Please run with mle=-1 to get a correct Line 9515  Please run with mle=-1 to get a correct
     for(itimes=1;itimes<=2;itimes++){      for(itimes=1;itimes<=2;itimes++){
       jj=0;        jj=0;
       for(i=1; i <=nlstate; i++){        for(i=1; i <=nlstate; i++){
         for(j=1; j <=nlstate+ndeath; j++){                                  for(j=1; j <=nlstate+ndeath; j++){
           if(j==i) continue;                                          if(j==i) continue;
           for(k=1; k<=ncovmodel;k++){                                          for(k=1; k<=ncovmodel;k++){
             jj++;                                                  jj++;
             ca[0]= k+'a'-1;ca[1]='\0';                                                  ca[0]= k+'a'-1;ca[1]='\0';
             if(itimes==1){                                                  if(itimes==1){
               if(mle>=1)                                                          if(mle>=1)
                 printf("#%1d%1d%d",i,j,k);                                                                  printf("#%1d%1d%d",i,j,k);
               fprintf(ficlog,"#%1d%1d%d",i,j,k);                                                          fprintf(ficlog,"#%1d%1d%d",i,j,k);
               fprintf(ficres,"#%1d%1d%d",i,j,k);                                                          fprintf(ficres,"#%1d%1d%d",i,j,k);
             }else{                                                  }else{
               if(mle>=1)                                                          if(mle>=1)
                 printf("%1d%1d%d",i,j,k);                                                                  printf("%1d%1d%d",i,j,k);
               fprintf(ficlog,"%1d%1d%d",i,j,k);                                                          fprintf(ficlog,"%1d%1d%d",i,j,k);
               fprintf(ficres,"%1d%1d%d",i,j,k);                                                          fprintf(ficres,"%1d%1d%d",i,j,k);
             }                                                  }
             ll=0;                                                  ll=0;
             for(li=1;li <=nlstate; li++){                                                  for(li=1;li <=nlstate; li++){
               for(lj=1;lj <=nlstate+ndeath; lj++){                                                          for(lj=1;lj <=nlstate+ndeath; lj++){
                 if(lj==li) continue;                                                                  if(lj==li) continue;
                 for(lk=1;lk<=ncovmodel;lk++){                                                                  for(lk=1;lk<=ncovmodel;lk++){
                   ll++;                                                                          ll++;
                   if(ll<=jj){                                                                          if(ll<=jj){
                     cb[0]= lk +'a'-1;cb[1]='\0';                                                                                  cb[0]= lk +'a'-1;cb[1]='\0';
                     if(ll<jj){                                                                                  if(ll<jj){
                       if(itimes==1){                                                                                          if(itimes==1){
                         if(mle>=1)                                                                                                  if(mle>=1)
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                                                                                                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                                                                                                  fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                                                                                                  fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                       }else{                                                                                          }else{
                         if(mle>=1)                                                                                                  if(mle>=1)
                           printf(" %.5e",matcov[jj][ll]);                                                                                                           printf(" %.5e",matcov[jj][ll]); 
                         fprintf(ficlog," %.5e",matcov[jj][ll]);                                                                                                   fprintf(ficlog," %.5e",matcov[jj][ll]); 
                         fprintf(ficres," %.5e",matcov[jj][ll]);                                                                                                   fprintf(ficres," %.5e",matcov[jj][ll]); 
                       }                                                                                          }
                     }else{                                                                                  }else{
                       if(itimes==1){                                                                                          if(itimes==1){
                         if(mle>=1)                                                                                                  if(mle>=1)
                           printf(" Var(%s%1d%1d)",ca,i,j);                                                                                                          printf(" Var(%s%1d%1d)",ca,i,j);
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);                                                                                                  fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);                                                                                                  fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                       }else{                                                                                          }else{
                         if(mle>=1)                                                                                                  if(mle>=1)
                           printf(" %.7e",matcov[jj][ll]);                                                                                                           printf(" %.7e",matcov[jj][ll]); 
                         fprintf(ficlog," %.7e",matcov[jj][ll]);                                                                                                   fprintf(ficlog," %.7e",matcov[jj][ll]); 
                         fprintf(ficres," %.7e",matcov[jj][ll]);                                                                                                   fprintf(ficres," %.7e",matcov[jj][ll]); 
                       }                                                                                          }
                     }                                                                                  }
                   }                                                                          }
                 } /* end lk */                                                                  } /* end lk */
               } /* end lj */                                                          } /* end lj */
             } /* end li */                                                  } /* end li */
             if(mle>=1)                                                  if(mle>=1)
               printf("\n");                                                          printf("\n");
             fprintf(ficlog,"\n");                                                  fprintf(ficlog,"\n");
             fprintf(ficres,"\n");                                                  fprintf(ficres,"\n");
             numlinepar++;                                                  numlinepar++;
           } /* end k*/                                          } /* end k*/
         } /*end j */                                  } /*end j */
       } /* end i */        } /* end i */
     } /* end itimes */      } /* end itimes */
           
     fflush(ficlog);      fflush(ficlog);
     fflush(ficres);      fflush(ficres);
       while(fgets(line, MAXLINE, ficpar)) {                  while(fgets(line, MAXLINE, ficpar)) {
     /* If line starts with a # it is a comment */                          /* If line starts with a # it is a comment */
     if (line[0] == '#') {                          if (line[0] == '#') {
       numlinepar++;                                  numlinepar++;
       fputs(line,stdout);                                  fputs(line,stdout);
       fputs(line,ficparo);                                  fputs(line,ficparo);
       fputs(line,ficlog);                                  fputs(line,ficlog);
       continue;                                  continue;
     }else                          }else
       break;                                  break;
   }                  }
                   
     /* while((c=getc(ficpar))=='#' && c!= EOF){ */      /* while((c=getc(ficpar))=='#' && c!= EOF){ */
     /*   ungetc(c,ficpar); */      /*   ungetc(c,ficpar); */
     /*   fgets(line, MAXLINE, ficpar); */      /*   fgets(line, MAXLINE, ficpar); */
Line 9282  Please run with mle=-1 to get a correct Line 9602  Please run with mle=-1 to get a correct
           
     estepm=0;      estepm=0;
     if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){      if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
                           
     if (num_filled != 6) {                          if (num_filled != 6) {
       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");                                  printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
       printf("but line=%s\n",line);                                  fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
       goto end;                                  goto end;
     }                          }
     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);                          printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
   }                  }
   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */                  /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */                  /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   
     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */      /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
     if (estepm==0 || estepm < stepm) estepm=stepm;      if (estepm==0 || estepm < stepm) estepm=stepm;
     if (fage <= 2) {      if (fage <= 2) {
Line 9303  Please run with mle=-1 to get a correct Line 9623  Please run with mle=-1 to get a correct
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);      fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   
     /* Other stuffs, more or less useful */          /* Other stuffs, more or less useful */    
     while((c=getc(ficpar))=='#' && c!= EOF){      while((c=getc(ficpar))=='#' && c!= EOF){
       ungetc(c,ficpar);        ungetc(c,ficpar);
Line 9360  Please run with mle=-1 to get a correct Line 9680  Please run with mle=-1 to get a correct
     ungetc(c,ficpar);      ungetc(c,ficpar);
           
     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);      fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
     fscanf(ficparo,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);      fprintf(ficparo,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
     fscanf(ficlog,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);      fprintf(ficlog,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
     fscanf(ficres,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);      fprintf(ficres,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
     /* day and month of proj2 are not used but only year anproj2.*/      /* day and month of proj2 are not used but only year anproj2.*/
           
           
      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */                  /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */      /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
           
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){      if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
         printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\                          printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\  This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);  Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
         fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\                          fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\  This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);  Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
     }else      }else{
       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);        printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
           }
     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\      printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \                                                                   model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                  jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);                                                                   jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
                         
    /*------------ free_vector  -------------*/                  /*------------ free_vector  -------------*/
    /*  chdir(path); */                  /*  chdir(path); */
                    
     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */      /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */      /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */      /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
Line 9397  Please run with mle=-1 to get a correct Line 9717  Please run with mle=-1 to get a correct
     /*free_matrix(covar,1,NCOVMAX,1,n);*/      /*free_matrix(covar,1,NCOVMAX,1,n);*/
     fclose(ficparo);      fclose(ficparo);
     fclose(ficres);      fclose(ficres);
                   
                   
     /* Other results (useful)*/      /* Other results (useful)*/
                   
                   
     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */      /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
     prlim=matrix(1,nlstate,1,nlstate);      prlim=matrix(1,nlstate,1,nlstate);
Line 9413  Please run with mle=-1 to get a correct Line 9733  Please run with mle=-1 to get a correct
     hPijx(p, bage, fage);      hPijx(p, bage, fage);
     fclose(ficrespij);      fclose(ficrespij);
   
                 ncovcombmax=  pow(2,cptcoveff);      /* ncovcombmax=  pow(2,cptcoveff); */
   /*-------------- Variance of one-step probabilities---*/      /*-------------- Variance of one-step probabilities---*/
     k=1;      k=1;
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);      varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
   
                 /* Prevalence for each covariates in probs[age][status][cov] */      /* Prevalence for each covariates in probs[age][status][cov] */
     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);      probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
     for(i=1;i<=AGESUP;i++)      for(i=1;i<=AGESUP;i++)
       for(j=1;j<=nlstate;j++)        for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
                                 for(k=1;k<=ncovcombmax;k++)                                  for(k=1;k<=ncovcombmax;k++)
                                         probs[i][j][k]=0.;                                          probs[i][j][k]=0.;
                 prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);      prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                 if (mobilav!=0 ||mobilavproj !=0 ) {      if (mobilav!=0 ||mobilavproj !=0 ) {
                         mobaverage= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);        mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                         if (mobilav!=0) {                          for(i=1;i<=AGESUP;i++)
                                   for(j=1;j<=nlstate;j++)
                                           for(k=1;k<=ncovcombmax;k++)
                                                   mobaverages[i][j][k]=0.;
         mobaverage=mobaverages;
         if (mobilav!=0) {
                                 if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){                                  if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                                         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);                                          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                                         printf(" Error in movingaverage mobilav=%d\n",mobilav);                                          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                                 }                                  }
                         }        }
                         /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */        /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                         /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */        /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                         else if (mobilavproj !=0) {        else if (mobilavproj !=0) {
                                 if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){                                  if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                                         fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);                                          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                                         printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);                                          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                                 }                                  }
                         }        }
                 }/* end if moving average */      }/* end if moving average */
                   
     /*---------- Forecasting ------------------*/      /*---------- Forecasting ------------------*/
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/      /*if((stepm == 1) && (strcmp(model,".")==0)){*/
     if(prevfcast==1){      if(prevfcast==1){
Line 9450  Please run with mle=-1 to get a correct Line 9775  Please run with mle=-1 to get a correct
       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);        prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
     }      }
     if(backcast==1){      if(backcast==1){
                 ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);              ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);        
                 ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);              ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);        
                 ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);        ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
   
                         /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                         /*#include "prevlim.h"*/  /* Use ficresplb, ficlog */  
                         bprlim=matrix(1,nlstate,1,nlstate);        bprlim=matrix(1,nlstate,1,nlstate);
                         back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);        back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                         fclose(ficresplb);        fclose(ficresplb);
   
                         hBijx(p, bage, fage, mobaverage);        hBijx(p, bage, fage, mobaverage);
                         fclose(ficrespijb);        fclose(ficrespijb);
                         free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */        free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
   
       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */        /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
                         free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);           bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                         free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);        free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                         free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);        free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                 }        free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */      }
   /* if (mobilavproj!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */  
   
     /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/  
     /*      }  */  
     /*      else{ */  
     /*        erreur=108; */  
     /*        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); */  
     /*        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); */  
     /*      } */  
           
     
     /* ------ Other prevalence ratios------------ */      /* ------ Other prevalence ratios------------ */
   
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */  
   
     /* prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */  
     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\  
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);  
     */  
     free_ivector(wav,1,imx);      free_ivector(wav,1,imx);
     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);      free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);      free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);         free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
                                   
                                   
                 /*   if (mobilav!=0) { */  
                 /*     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */  
                 /*     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */  
                 /* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */  
                 /* printf(" Error in movingaverage mobilav=%d\n",mobilav); */  
                 /*     } */  
                 /*   } */  
                   
                   
     /*---------- Health expectancies, no variances ------------*/      /*---------- Health expectancies, no variances ------------*/
                                   
     strcpy(filerese,"E_");      strcpy(filerese,"E_");
Line 9514  Please run with mle=-1 to get a correct Line 9815  Please run with mle=-1 to get a correct
     }      }
     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);      printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);      fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){                  
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/  
                   
     for (k=1; k <= (int) pow(2,cptcoveff); k++){      for (k=1; k <= (int) pow(2,cptcoveff); k++){
                         fprintf(ficreseij,"\n#****** ");        fprintf(ficreseij,"\n#****** ");
                         for(j=1;j<=cptcoveff;j++) {        for(j=1;j<=cptcoveff;j++) {
                                 fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);                                  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                         }        }
                         fprintf(ficreseij,"******\n");        fprintf(ficreseij,"******\n");
                           
                         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);  
                         oldm=oldms;savm=savms;  
                         evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);    
               
                         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
       /*}*/        oldm=oldms;savm=savms;
         evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
         
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     }      }
     fclose(ficreseij);      fclose(ficreseij);
     printf("done evsij\n");fflush(stdout);      printf("done evsij\n");fflush(stdout);
Line 9643  Please run with mle=-1 to get a correct Line 9941  Please run with mle=-1 to get a correct
                                                                 prlim[i][i]=mobaverage[(int)age][i][k];                                                                  prlim[i][i]=mobaverage[(int)age][i][k];
                                                 }                                                  }
                                         }                                          }
                                                     
                                         fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);                                          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                                         /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */                                          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                                         /* printf(" age %4.0f ",age); */                                          /* printf(" age %4.0f ",age); */
Line 9656  Please run with mle=-1 to get a correct Line 9954  Please run with mle=-1 to get a correct
                                                 epj[nlstate+1] +=epj[j];                                                  epj[nlstate+1] +=epj[j];
                                         }                                          }
                                         /* printf(" age %4.0f \n",age); */                                          /* printf(" age %4.0f \n",age); */
                                                     
                                         for(i=1, vepp=0.;i <=nlstate;i++)                                          for(i=1, vepp=0.;i <=nlstate;i++)
                                                 for(j=1;j <=nlstate;j++)                                                  for(j=1;j <=nlstate;j++)
                                                         vepp += vareij[i][j][(int)age];                                                          vepp += vareij[i][j][(int)age];
Line 9722  Please run with mle=-1 to get a correct Line 10020  Please run with mle=-1 to get a correct
     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);      fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
   
     /*---------- End : free ----------------*/      /*---------- End : free ----------------*/
     if (mobilav!=0 ||mobilavproj !=0) free_ma3x(mobaverage,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */      if (mobilav!=0 ||mobilavproj !=0)
         free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);      free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
   }  /* mle==-3 arrives here for freeing */  
  /* endfree:*/  
     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */      free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);      free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
     }  /* mle==-3 arrives here for freeing */
    /* endfree:*/
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);      free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);      free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);      free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_ma3x(cotqvar,1,maxwav,1,ntqv,1,n);
       free_ma3x(cotvar,1,maxwav,1,ntv,1,n);
       free_matrix(coqvar,1,maxwav,1,n);
     free_matrix(covar,0,NCOVMAX,1,n);      free_matrix(covar,0,NCOVMAX,1,n);
     free_matrix(matcov,1,npar,1,npar);      free_matrix(matcov,1,npar,1,npar);
     free_matrix(hess,1,npar,1,npar);      free_matrix(hess,1,npar,1,npar);
Line 9744  Please run with mle=-1 to get a correct Line 10046  Please run with mle=-1 to get a correct
     free_ivector(Tvar,1,NCOVMAX);      free_ivector(Tvar,1,NCOVMAX);
     free_ivector(Tprod,1,NCOVMAX);      free_ivector(Tprod,1,NCOVMAX);
     free_ivector(Tvaraff,1,NCOVMAX);      free_ivector(Tvaraff,1,NCOVMAX);
       free_ivector(invalidvarcomb,1,ncovcombmax);
     free_ivector(Tage,1,NCOVMAX);      free_ivector(Tage,1,NCOVMAX);
   
     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);      free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);

Removed from v.1.218  
changed lines
  Added in v.1.223


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