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

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

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