File:  [Local Repository] / imach / src / imach.c
Revision 1.82: download - view: text, annotated - select for diffs
Thu Jun 5 15:57:20 2003 UTC (21 years ago) by brouard
Branches: MAIN
CVS tags: HEAD
Add log in  imach.c and  fullversion number is now printed.

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

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