File:  [Local Repository] / imach / src / imach.c
Revision 1.117: download - view: text, annotated - select for diffs
Tue Mar 14 17:16:22 2006 UTC (18 years, 3 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): varevsij Comments added explaining the second
table of variances if popbased=1 .
(Module): Covariances of eij, ekl added, graphs fixed, new html link.
(Module): Function pstamp added
(Module): Version 0.98d

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

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