File:  [Local Repository] / imach / src / imach.c
Revision 1.89: download - view: text, annotated - select for diffs
Tue Jun 24 12:30:52 2003 UTC (20 years, 10 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Some bugs corrected for windows. Also, when
mle=-1 a template is output in file "or"mypar.txt with the design
of the covariance matrix to be input.

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

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