File:  [Local Repository] / imach / src / imach.c
Revision 1.84: download - view: text, annotated - select for diffs
Fri Jun 13 21:44:43 2003 UTC (21 years ago) by brouard
Branches: MAIN
CVS tags: HEAD
* imach.c (Repository): Replace "freqsummary" at a correct
place. It differs from routine "prevalence" which may be called
many times. Probs is memory consuming and must be used with
parcimony.
Version 0.95a2 (should output exactly the same maximization than 0.8a2)

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

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