File:  [Local Repository] / imach / src / imach.c
Revision 1.102: download - view: text, annotated - select for diffs
Wed Sep 15 17:31:30 2004 UTC (19 years, 8 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Add the possibility to read data file including tab characters.

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

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