File:  [Local Repository] / imach / src / imach.c
Revision 1.79: download - view: text, annotated - select for diffs
Thu Jun 5 15:17:23 2003 UTC (20 years, 11 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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