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

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