File:  [Local Repository] / imach / src / imach.c
Revision 1.100: download - view: text, annotated - select for diffs
Mon Jul 12 18:29:06 2004 UTC (19 years, 10 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Add version for Mac OS X. Just define UNIX in Makefile

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

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