Diff for /imach/src/imach.c between versions 1.92 and 1.125

version 1.92, 2003/06/25 16:30:45 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.92  2003/06/25 16:30:45  brouard    Revision 1.125  2006/04/04 15:20:31  lievre
   (Module): On windows (cygwin) function asctime_r doesn't    Errors in calculation of health expectancies. Age was not initialized.
   exist so I changed back to asctime which exists.    Forecasting file added.
   
   Revision 1.91  2003/06/25 15:30:29  brouard    Revision 1.124  2006/03/22 17:13:53  lievre
   * imach.c (Repository): Duplicated warning errors corrected.    Parameters are printed with %lf instead of %f (more numbers after the comma).
   (Repository): Elapsed time after each iteration is now output. It    The log-likelihood is printed in the log file
   helps to forecast when convergence will be reached. Elapsed time  
   is stamped in powell.  We created a new html file for the graphs    Revision 1.123  2006/03/20 10:52:43  brouard
   concerning matrix of covariance. It has extension -cov.htm.    * imach.c (Module): <title> changed, corresponds to .htm file
     name. <head> headers where missing.
   Revision 1.90  2003/06/24 12:34:15  brouard  
   (Module): Some bugs corrected for windows. Also, when    * imach.c (Module): Weights can have a decimal point as for
   mle=-1 a template is output in file "or"mypar.txt with the design    English (a comma might work with a correct LC_NUMERIC environment,
   of the covariance matrix to be input.    otherwise the weight is truncated).
     Modification of warning when the covariates values are not 0 or
   Revision 1.89  2003/06/24 12:30:52  brouard    1.
   (Module): Some bugs corrected for windows. Also, when    Version 0.98g
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.122  2006/03/20 09:45:41  brouard
     (Module): Weights can have a decimal point as for
   Revision 1.88  2003/06/23 17:54:56  brouard    English (a comma might work with a correct LC_NUMERIC environment,
   * 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.    otherwise the weight is truncated).
     Modification of warning when the covariates values are not 0 or
   Revision 1.87  2003/06/18 12:26:01  brouard    1.
   Version 0.96    Version 0.98g
   
   Revision 1.86  2003/06/17 20:04:08  brouard    Revision 1.121  2006/03/16 17:45:01  lievre
   (Module): Change position of html and gnuplot routines and added    * imach.c (Module): Comments concerning covariates added
   routine fileappend.  
     * imach.c (Module): refinements in the computation of lli if
   Revision 1.85  2003/06/17 13:12:43  brouard    status=-2 in order to have more reliable computation if stepm is
   * imach.c (Repository): Check when date of death was earlier that    not 1 month. Version 0.98f
   current date of interview. It may happen when the death was just  
   prior to the death. In this case, dh was negative and likelihood    Revision 1.120  2006/03/16 15:10:38  lievre
   was wrong (infinity). We still send an "Error" but patch by    (Module): refinements in the computation of lli if
   assuming that the date of death was just one stepm after the    status=-2 in order to have more reliable computation if stepm is
   interview.    not 1 month. Version 0.98f
   (Repository): Because some people have very long ID (first column)  
   we changed int to long in num[] and we added a new lvector for    Revision 1.119  2006/03/15 17:42:26  brouard
   memory allocation. But we also truncated to 8 characters (left    (Module): Bug if status = -2, the loglikelihood was
   truncation)    computed as likelihood omitting the logarithm. Version O.98e
   (Repository): No more line truncation errors.  
     Revision 1.118  2006/03/14 18:20:07  brouard
   Revision 1.84  2003/06/13 21:44:43  brouard    (Module): varevsij Comments added explaining the second
   * imach.c (Repository): Replace "freqsummary" at a correct    table of variances if popbased=1 .
   place. It differs from routine "prevalence" which may be called    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   many times. Probs is memory consuming and must be used with    (Module): Function pstamp added
   parcimony.    (Module): Version 0.98d
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)  
     Revision 1.117  2006/03/14 17:16:22  brouard
   Revision 1.83  2003/06/10 13:39:11  lievre    (Module): varevsij Comments added explaining the second
   *** empty log message ***    table of variances if popbased=1 .
     (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   Revision 1.82  2003/06/05 15:57:20  brouard    (Module): Function pstamp added
   Add log in  imach.c and  fullversion number is now printed.    (Module): Version 0.98d
   
 */    Revision 1.116  2006/03/06 10:29:27  brouard
 /*    (Module): Variance-covariance wrong links and
    Interpolated Markov Chain    varian-covariance of ej. is needed (Saito).
   
   Short summary of the programme:    Revision 1.115  2006/02/27 12:17:45  brouard
       (Module): One freematrix added in mlikeli! 0.98c
   This program computes Healthy Life Expectancies from  
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    Revision 1.114  2006/02/26 12:57:58  brouard
   first survey ("cross") where individuals from different ages are    (Module): Some improvements in processing parameter
   interviewed on their health status or degree of disability (in the    filename with strsep.
   case of a health survey which is our main interest) -2- at least a  
   second wave of interviews ("longitudinal") which measure each change    Revision 1.113  2006/02/24 14:20:24  brouard
   (if any) in individual health status.  Health expectancies are    (Module): Memory leaks checks with valgrind and:
   computed from the time spent in each health state according to a    datafile was not closed, some imatrix were not freed and on matrix
   model. More health states you consider, more time is necessary to reach the    allocation too.
   Maximum Likelihood of the parameters involved in the model.  The  
   simplest model is the multinomial logistic model where pij is the    Revision 1.112  2006/01/30 09:55:26  brouard
   probability to be observed in state j at the second wave    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   conditional to be observed in state i at the first wave. Therefore  
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    Revision 1.111  2006/01/25 20:38:18  brouard
   'age' is age and 'sex' is a covariate. If you want to have a more    (Module): Lots of cleaning and bugs added (Gompertz)
   complex model than "constant and age", you should modify the program    (Module): Comments can be added in data file. Missing date values
   where the markup *Covariates have to be included here again* invites    can be a simple dot '.'.
   you to do it.  More covariates you add, slower the  
   convergence.    Revision 1.110  2006/01/25 00:51:50  brouard
     (Module): Lots of cleaning and bugs added (Gompertz)
   The advantage of this computer programme, compared to a simple  
   multinomial logistic model, is clear when the delay between waves is not    Revision 1.109  2006/01/24 19:37:15  brouard
   identical for each individual. Also, if a individual missed an    (Module): Comments (lines starting with a #) are allowed in data.
   intermediate interview, the information is lost, but taken into  
   account using an interpolation or extrapolation.      Revision 1.108  2006/01/19 18:05:42  lievre
     Gnuplot problem appeared...
   hPijx is the probability to be observed in state i at age x+h    To be fixed
   conditional to the observed state i at age x. The delay 'h' can be  
   split into an exact number (nh*stepm) of unobserved intermediate    Revision 1.107  2006/01/19 16:20:37  brouard
   states. This elementary transition (by month, quarter,    Test existence of gnuplot in imach path
   semester or year) is modelled as a multinomial logistic.  The hPx  
   matrix is simply the matrix product of nh*stepm elementary matrices    Revision 1.106  2006/01/19 13:24:36  brouard
   and the contribution of each individual to the likelihood is simply    Some cleaning and links added in html output
   hPijx.  
     Revision 1.105  2006/01/05 20:23:19  lievre
   Also this programme outputs the covariance matrix of the parameters but also    *** empty log message ***
   of the life expectancies. It also computes the stable prevalence.   
       Revision 1.104  2005/09/30 16:11:43  lievre
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    (Module): sump fixed, loop imx fixed, and simplifications.
            Institut national d'études démographiques, Paris.    (Module): If the status is missing at the last wave but we know
   This software have been partly granted by Euro-REVES, a concerted action    that the person is alive, then we can code his/her status as -2
   from the European Union.    (instead of missing=-1 in earlier versions) and his/her
   It is copyrighted identically to a GNU software product, ie programme and    contributions to the likelihood is 1 - Prob of dying from last
   software can be distributed freely for non commercial use. Latest version    health status (= 1-p13= p11+p12 in the easiest case of somebody in
   can be accessed at http://euroreves.ined.fr/imach .    the healthy state at last known wave). Version is 0.98
   
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    Revision 1.103  2005/09/30 15:54:49  lievre
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    (Module): sump fixed, loop imx fixed, and simplifications.
     
   **********************************************************************/    Revision 1.102  2004/09/15 17:31:30  brouard
 /*    Add the possibility to read data file including tab characters.
   main  
   read parameterfile    Revision 1.101  2004/09/15 10:38:38  brouard
   read datafile    Fix on curr_time
   concatwav  
   freqsummary    Revision 1.100  2004/07/12 18:29:06  brouard
   if (mle >= 1)    Add version for Mac OS X. Just define UNIX in Makefile
     mlikeli  
   print results files    Revision 1.99  2004/06/05 08:57:40  brouard
   if mle==1     *** empty log message ***
      computes hessian  
   read end of parameter file: agemin, agemax, bage, fage, estepm    Revision 1.98  2004/05/16 15:05:56  brouard
       begin-prev-date,...    New version 0.97 . First attempt to estimate force of mortality
   open gnuplot file    directly from the data i.e. without the need of knowing the health
   open html file    state at each age, but using a Gompertz model: log u =a + b*age .
   stable prevalence    This is the basic analysis of mortality and should be done before any
    for age prevalim()    other analysis, in order to test if the mortality estimated from the
   h Pij x    cross-longitudinal survey is different from the mortality estimated
   variance of p varprob    from other sources like vital statistic data.
   forecasting if prevfcast==1 prevforecast call prevalence()  
   health expectancies    The same imach parameter file can be used but the option for mle should be -3.
   Variance-covariance of DFLE  
   prevalence()    Agnès, who wrote this part of the code, tried to keep most of the
    movingaverage()    former routines in order to include the new code within the former code.
   varevsij()   
   if popbased==1 varevsij(,popbased)    The output is very simple: only an estimate of the intercept and of
   total life expectancies    the slope with 95% confident intervals.
   Variance of stable prevalence  
  end    Current limitations:
 */    A) Even if you enter covariates, i.e. with the
     model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
     B) There is no computation of Life Expectancy nor Life Table.
   
      Revision 1.97  2004/02/20 13:25:42  lievre
 #include <math.h>    Version 0.96d. Population forecasting command line is (temporarily)
 #include <stdio.h>    suppressed.
 #include <stdlib.h>  
 #include <unistd.h>    Revision 1.96  2003/07/15 15:38:55  brouard
     * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
 #include <sys/time.h>    rewritten within the same printf. Workaround: many printfs.
 #include <time.h>  
 #include "timeval.h"    Revision 1.95  2003/07/08 07:54:34  brouard
     * imach.c (Repository):
 #define MAXLINE 256    (Repository): Using imachwizard code to output a more meaningful covariance
 #define GNUPLOTPROGRAM "gnuplot"    matrix (cov(a12,c31) instead of numbers.
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/  
 #define FILENAMELENGTH 132    Revision 1.94  2003/06/27 13:00:02  brouard
 /*#define DEBUG*/    Just cleaning
 /*#define windows*/  
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */    Revision 1.93  2003/06/25 16:33:55  brouard
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */    (Module): On windows (cygwin) function asctime_r doesn't
     exist so I changed back to asctime which exists.
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */    (Module): Version 0.96b
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  
     Revision 1.92  2003/06/25 16:30:45  brouard
 #define NINTERVMAX 8    (Module): On windows (cygwin) function asctime_r doesn't
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */    exist so I changed back to asctime which exists.
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */  
 #define NCOVMAX 8 /* Maximum number of covariates */    Revision 1.91  2003/06/25 15:30:29  brouard
 #define MAXN 20000    * imach.c (Repository): Duplicated warning errors corrected.
 #define YEARM 12. /* Number of months per year */    (Repository): Elapsed time after each iteration is now output. It
 #define AGESUP 130    helps to forecast when convergence will be reached. Elapsed time
 #define AGEBASE 40    is stamped in powell.  We created a new html file for the graphs
 #ifdef unix    concerning matrix of covariance. It has extension -cov.htm.
 #define DIRSEPARATOR '/'  
 #define ODIRSEPARATOR '\\'    Revision 1.90  2003/06/24 12:34:15  brouard
 #else    (Module): Some bugs corrected for windows. Also, when
 #define DIRSEPARATOR '\\'    mle=-1 a template is output in file "or"mypar.txt with the design
 #define ODIRSEPARATOR '/'    of the covariance matrix to be input.
 #endif  
     Revision 1.89  2003/06/24 12:30:52  brouard
 /* $Id$ */    (Module): Some bugs corrected for windows. Also, when
 /* $State$ */    mle=-1 a template is output in file "or"mypar.txt with the design
     of the covariance matrix to be input.
 char version[]="Imach version 0.96a, June 2003, INED-EUROREVES ";  
 char fullversion[]="$Revision$ $Date$";     Revision 1.88  2003/06/23 17:54:56  brouard
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */    * 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.
 int nvar;  
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;    Revision 1.87  2003/06/18 12:26:01  brouard
 int npar=NPARMAX;    Version 0.96
 int nlstate=2; /* Number of live states */  
 int ndeath=1; /* Number of dead states */    Revision 1.86  2003/06/17 20:04:08  brouard
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */    (Module): Change position of html and gnuplot routines and added
 int popbased=0;    routine fileappend.
   
 int *wav; /* Number of waves for this individuual 0 is possible */    Revision 1.85  2003/06/17 13:12:43  brouard
 int maxwav; /* Maxim number of waves */    * imach.c (Repository): Check when date of death was earlier that
 int jmin, jmax; /* min, max spacing between 2 waves */    current date of interview. It may happen when the death was just
 int gipmx, gsw; /* Global variables on the number of contributions     prior to the death. In this case, dh was negative and likelihood
                    to the likelihood and the sum of weights (done by funcone)*/    was wrong (infinity). We still send an "Error" but patch by
 int mle, weightopt;    assuming that the date of death was just one stepm after the
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */    interview.
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */    (Repository): Because some people have very long ID (first column)
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between    we changed int to long in num[] and we added a new lvector for
            * wave mi and wave mi+1 is not an exact multiple of stepm. */    memory allocation. But we also truncated to 8 characters (left
 double jmean; /* Mean space between 2 waves */    truncation)
 double **oldm, **newm, **savm; /* Working pointers to matrices */    (Repository): No more line truncation errors.
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */  
 FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;    Revision 1.84  2003/06/13 21:44:43  brouard
 FILE *ficlog, *ficrespow;    * imach.c (Repository): Replace "freqsummary" at a correct
 int globpr; /* Global variable for printing or not */    place. It differs from routine "prevalence" which may be called
 double fretone; /* Only one call to likelihood */    many times. Probs is memory consuming and must be used with
 long ipmx; /* Number of contributions */    parcimony.
 double sw; /* Sum of weights */    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */  
 FILE *ficresilk;    Revision 1.83  2003/06/10 13:39:11  lievre
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;    *** empty log message ***
 FILE *ficresprobmorprev;  
 FILE *fichtm, *fichtmcov; /* Html File */    Revision 1.82  2003/06/05 15:57:20  brouard
 FILE *ficreseij;    Add log in  imach.c and  fullversion number is now printed.
 char filerese[FILENAMELENGTH];  
 FILE  *ficresvij;  */
 char fileresv[FILENAMELENGTH];  /*
 FILE  *ficresvpl;     Interpolated Markov Chain
 char fileresvpl[FILENAMELENGTH];  
 char title[MAXLINE];    Short summary of the programme:
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];   
 char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH];    This program computes Healthy Life Expectancies from
 char tmpout[FILENAMELENGTH];     cross-longitudinal data. Cross-longitudinal data consist in: -1- a
 char command[FILENAMELENGTH];    first survey ("cross") where individuals from different ages are
 int  outcmd=0;    interviewed on their health status or degree of disability (in the
     case of a health survey which is our main interest) -2- at least a
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];    second wave of interviews ("longitudinal") which measure each change
 char lfileres[FILENAMELENGTH];    (if any) in individual health status.  Health expectancies are
 char filelog[FILENAMELENGTH]; /* Log file */    computed from the time spent in each health state according to a
 char filerest[FILENAMELENGTH];    model. More health states you consider, more time is necessary to reach the
 char fileregp[FILENAMELENGTH];    Maximum Likelihood of the parameters involved in the model.  The
 char popfile[FILENAMELENGTH];    simplest model is the multinomial logistic model where pij is the
     probability to be observed in state j at the second wave
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;    conditional to be observed in state i at the first wave. Therefore
     the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;    'age' is age and 'sex' is a covariate. If you want to have a more
 struct timezone tzp;    complex model than "constant and age", you should modify the program
 extern int gettimeofday();    where the markup *Covariates have to be included here again* invites
 struct tm tmg, tm, tmf, *gmtime(), *localtime();    you to do it.  More covariates you add, slower the
 long time_value;    convergence.
 extern long time();  
 char strcurr[80], strfor[80];    The advantage of this computer programme, compared to a simple
     multinomial logistic model, is clear when the delay between waves is not
 #define NR_END 1    identical for each individual. Also, if a individual missed an
 #define FREE_ARG char*    intermediate interview, the information is lost, but taken into
 #define FTOL 1.0e-10    account using an interpolation or extrapolation.  
   
 #define NRANSI     hPijx is the probability to be observed in state i at age x+h
 #define ITMAX 200     conditional to the observed state i at age x. The delay 'h' can be
     split into an exact number (nh*stepm) of unobserved intermediate
 #define TOL 2.0e-4     states. This elementary transition (by month, quarter,
     semester or year) is modelled as a multinomial logistic.  The hPx
 #define CGOLD 0.3819660     matrix is simply the matrix product of nh*stepm elementary matrices
 #define ZEPS 1.0e-10     and the contribution of each individual to the likelihood is simply
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);     hPijx.
   
 #define GOLD 1.618034     Also this programme outputs the covariance matrix of the parameters but also
 #define GLIMIT 100.0     of the life expectancies. It also computes the period (stable) prevalence.
 #define TINY 1.0e-20    
     Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 static double maxarg1,maxarg2;             Institut national d'études démographiques, Paris.
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))    This software have been partly granted by Euro-REVES, a concerted action
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))    from the European Union.
       It is copyrighted identically to a GNU software product, ie programme and
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))    software can be distributed freely for non commercial use. Latest version
 #define rint(a) floor(a+0.5)    can be accessed at http://euroreves.ined.fr/imach .
   
 static double sqrarg;    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}    
     **********************************************************************/
 int imx;   /*
 int stepm;    main
 /* Stepm, step in month: minimum step interpolation*/    read parameterfile
     read datafile
 int estepm;    concatwav
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/    freqsummary
     if (mle >= 1)
 int m,nb;      mlikeli
 long *num;    print results files
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage;    if mle==1
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;       computes hessian
 double **pmmij, ***probs;    read end of parameter file: agemin, agemax, bage, fage, estepm
 double dateintmean=0;        begin-prev-date,...
     open gnuplot file
 double *weight;    open html file
 int **s; /* Status */    period (stable) prevalence
 double *agedc, **covar, idx;     for age prevalim()
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;    h Pij x
     variance of p varprob
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */    forecasting if prevfcast==1 prevforecast call prevalence()
 double ftolhess; /* Tolerance for computing hessian */    health expectancies
     Variance-covariance of DFLE
 /**************** split *************************/    prevalence()
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )     movingaverage()
 {    varevsij()
   char  *ss;                            /* pointer */    if popbased==1 varevsij(,popbased)
   int   l1, l2;                         /* length counters */    total life expectancies
     Variance of period (stable) prevalence
   l1 = strlen(path );                   /* length of path */   end
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  */
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  
   if ( ss == NULL ) {                   /* no directory, so use current */  
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/   
     /* get current working directory */  #include <math.h>
     /*    extern  char* getcwd ( char *buf , int len);*/  #include <stdio.h>
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  #include <stdlib.h>
       return( GLOCK_ERROR_GETCWD );  #include <string.h>
     }  #include <unistd.h>
     strcpy( name, path );               /* we've got it */  
   } else {                              /* strip direcotry from path */  #include <limits.h>
     ss++;                               /* after this, the filename */  #include <sys/types.h>
     l2 = strlen( ss );                  /* length of filename */  #include <sys/stat.h>
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  #include <errno.h>
     strcpy( name, ss );         /* save file name */  extern int errno;
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  
     dirc[l1-l2] = 0;                    /* add zero */  /* #include <sys/time.h> */
   }  #include <time.h>
   l1 = strlen( dirc );                  /* length of directory */  #include "timeval.h"
   /*#ifdef windows  
   if ( dirc[l1-1] != '\\' ) { dirc[l1] = '\\'; dirc[l1+1] = 0; }  /* #include <libintl.h> */
 #else  /* #define _(String) gettext (String) */
   if ( dirc[l1-1] != '/' ) { dirc[l1] = '/'; dirc[l1+1] = 0; }  
 #endif  #define MAXLINE 256
   */  
   ss = strrchr( name, '.' );            /* find last / */  #define GNUPLOTPROGRAM "gnuplot"
   ss++;  /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
   strcpy(ext,ss);                       /* save extension */  #define FILENAMELENGTH 132
   l1= strlen( name);  
   l2= strlen(ss)+1;  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
   strncpy( finame, name, l1-l2);  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
   finame[l1-l2]= 0;  
   return( 0 );                          /* we're done */  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 }  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
   
   #define NINTERVMAX 8
 /******************************************/  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
   #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 void replace_back_to_slash(char *s, char*t)  #define NCOVMAX 8 /* Maximum number of covariates */
 {  #define MAXN 20000
   int i;  #define YEARM 12. /* Number of months per year */
   int lg=0;  #define AGESUP 130
   i=0;  #define AGEBASE 40
   lg=strlen(t);  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
   for(i=0; i<= lg; i++) {  #ifdef UNIX
     (s[i] = t[i]);  #define DIRSEPARATOR '/'
     if (t[i]== '\\') s[i]='/';  #define CHARSEPARATOR "/"
   }  #define ODIRSEPARATOR '\\'
 }  #else
   #define DIRSEPARATOR '\\'
 int nbocc(char *s, char occ)  #define CHARSEPARATOR "\\"
 {  #define ODIRSEPARATOR '/'
   int i,j=0;  #endif
   int lg=20;  
   i=0;  /* $Id$ */
   lg=strlen(s);  /* $State$ */
   for(i=0; i<= lg; i++) {  
   if  (s[i] == occ ) j++;  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
   }  char fullversion[]="$Revision$ $Date$";
   return j;  char strstart[80];
 }  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
   int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 void cutv(char *u,char *v, char*t, char occ)  int nvar;
 {  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
   /* cuts string t into u and v where u is ended by char occ excluding it  int npar=NPARMAX;
      and v is after occ excluding it too : ex cutv(u,v,"abcdef2ghi2j",2)  int nlstate=2; /* Number of live states */
      gives u="abcedf" and v="ghi2j" */  int ndeath=1; /* Number of dead states */
   int i,lg,j,p=0;  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
   i=0;  int popbased=0;
   for(j=0; j<=strlen(t)-1; j++) {  
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;  int *wav; /* Number of waves for this individuual 0 is possible */
   }  int maxwav; /* Maxim number of waves */
   int jmin, jmax; /* min, max spacing between 2 waves */
   lg=strlen(t);  int ijmin, ijmax; /* Individuals having jmin and jmax */
   for(j=0; j<p; j++) {  int gipmx, gsw; /* Global variables on the number of contributions
     (u[j] = t[j]);                     to the likelihood and the sum of weights (done by funcone)*/
   }  int mle, weightopt;
      u[p]='\0';  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
   int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
    for(j=0; j<= lg; j++) {  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
     if (j>=(p+1))(v[j-p-1] = t[j]);             * wave mi and wave mi+1 is not an exact multiple of stepm. */
   }  double jmean; /* Mean space between 2 waves */
 }  double **oldm, **newm, **savm; /* Working pointers to matrices */
   double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 /********************** nrerror ********************/  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
   FILE *ficlog, *ficrespow;
 void nrerror(char error_text[])  int globpr; /* Global variable for printing or not */
 {  double fretone; /* Only one call to likelihood */
   fprintf(stderr,"ERREUR ...\n");  long ipmx; /* Number of contributions */
   fprintf(stderr,"%s\n",error_text);  double sw; /* Sum of weights */
   exit(EXIT_FAILURE);  char filerespow[FILENAMELENGTH];
 }  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 /*********************** vector *******************/  FILE *ficresilk;
 double *vector(int nl, int nh)  FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 {  FILE *ficresprobmorprev;
   double *v;  FILE *fichtm, *fichtmcov; /* Html File */
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));  FILE *ficreseij;
   if (!v) nrerror("allocation failure in vector");  char filerese[FILENAMELENGTH];
   return v-nl+NR_END;  FILE *ficresstdeij;
 }  char fileresstde[FILENAMELENGTH];
   FILE *ficrescveij;
 /************************ free vector ******************/  char filerescve[FILENAMELENGTH];
 void free_vector(double*v, int nl, int nh)  FILE  *ficresvij;
 {  char fileresv[FILENAMELENGTH];
   free((FREE_ARG)(v+nl-NR_END));  FILE  *ficresvpl;
 }  char fileresvpl[FILENAMELENGTH];
   char title[MAXLINE];
 /************************ivector *******************************/  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 int *ivector(long nl,long nh)  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 {  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
   int *v;  char command[FILENAMELENGTH];
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));  int  outcmd=0;
   if (!v) nrerror("allocation failure in ivector");  
   return v-nl+NR_END;  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
 }  
   char filelog[FILENAMELENGTH]; /* Log file */
 /******************free ivector **************************/  char filerest[FILENAMELENGTH];
 void free_ivector(int *v, long nl, long nh)  char fileregp[FILENAMELENGTH];
 {  char popfile[FILENAMELENGTH];
   free((FREE_ARG)(v+nl-NR_END));  
 }  char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
   
 /************************lvector *******************************/  struct timeval start_time, end_time, curr_time, last_time, forecast_time;
 long *lvector(long nl,long nh)  struct timezone tzp;
 {  extern int gettimeofday();
   long *v;  struct tm tmg, tm, tmf, *gmtime(), *localtime();
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));  long time_value;
   if (!v) nrerror("allocation failure in ivector");  extern long time();
   return v-nl+NR_END;  char strcurr[80], strfor[80];
 }  
   char *endptr;
 /******************free lvector **************************/  long lval;
 void free_lvector(long *v, long nl, long nh)  double dval;
 {  
   free((FREE_ARG)(v+nl-NR_END));  #define NR_END 1
 }  #define FREE_ARG char*
   #define FTOL 1.0e-10
 /******************* imatrix *******************************/  
 int **imatrix(long nrl, long nrh, long ncl, long nch)   #define NRANSI
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */   #define ITMAX 200
 {   
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;   #define TOL 2.0e-4
   int **m;   
     #define CGOLD 0.3819660
   /* allocate pointers to rows */   #define ZEPS 1.0e-10
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));   #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
   if (!m) nrerror("allocation failure 1 in matrix()");   
   m += NR_END;   #define GOLD 1.618034
   m -= nrl;   #define GLIMIT 100.0
     #define TINY 1.0e-20
     
   /* allocate rows and set pointers to them */   static double maxarg1,maxarg2;
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));   #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");   #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
   m[nrl] += NR_END;    
   m[nrl] -= ncl;   #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
     #define rint(a) floor(a+0.5)
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;   
     static double sqrarg;
   /* return pointer to array of pointers to rows */   #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
   return m;   #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
 }   int agegomp= AGEGOMP;
   
 /****************** free_imatrix *************************/  int imx;
 void free_imatrix(m,nrl,nrh,ncl,nch)  int stepm=1;
       int **m;  /* Stepm, step in month: minimum step interpolation*/
       long nch,ncl,nrh,nrl;   
      /* free an int matrix allocated by imatrix() */   int estepm;
 {   /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   free((FREE_ARG) (m[nrl]+ncl-NR_END));   
   free((FREE_ARG) (m+nrl-NR_END));   int m,nb;
 }   long *num;
   int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
 /******************* matrix *******************************/  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 double **matrix(long nrl, long nrh, long ncl, long nch)  double **pmmij, ***probs;
 {  double *ageexmed,*agecens;
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;  double dateintmean=0;
   double **m;  
   double *weight;
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  int **s; /* Status */
   if (!m) nrerror("allocation failure 1 in matrix()");  double *agedc, **covar, idx;
   m += NR_END;  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
   m -= nrl;  double *lsurv, *lpop, *tpop;
   
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  double ftolhess; /* Tolerance for computing hessian */
   m[nrl] += NR_END;  
   m[nrl] -= ncl;  /**************** split *************************/
   static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;  {
   return m;    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])        the name of the file (name), its extension only (ext) and its first part of the name (finame)
    */    */
 }    char  *ss;                            /* pointer */
     int   l1, l2;                         /* length counters */
 /*************************free matrix ************************/  
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)    l1 = strlen(path );                   /* length of path */
 {    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
   free((FREE_ARG)(m+nrl-NR_END));    if ( ss == NULL ) {                   /* no directory, so determine current directory */
 }      strcpy( name, path );               /* we got the fullname name because no directory */
       /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 /******************* ma3x *******************************/        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)      /* get current working directory */
 {      /*    extern  char* getcwd ( char *buf , int len);*/
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
   double ***m;        return( GLOCK_ERROR_GETCWD );
       }
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));      /* got dirc from getcwd*/
   if (!m) nrerror("allocation failure 1 in matrix()");      printf(" DIRC = %s \n",dirc);
   m += NR_END;    } else {                              /* strip direcotry from path */
   m -= nrl;      ss++;                               /* after this, the filename */
       l2 = strlen( ss );                  /* length of filename */
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));      if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");      strcpy( name, ss );         /* save file name */
   m[nrl] += NR_END;      strncpy( dirc, path, l1 - l2 );     /* now the directory */
   m[nrl] -= ncl;      dirc[l1-l2] = 0;                    /* add zero */
       printf(" DIRC2 = %s \n",dirc);
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    }
     /* We add a separator at the end of dirc if not exists */
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));    l1 = strlen( dirc );                  /* length of directory */
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");    if( dirc[l1-1] != DIRSEPARATOR ){
   m[nrl][ncl] += NR_END;      dirc[l1] =  DIRSEPARATOR;
   m[nrl][ncl] -= nll;      dirc[l1+1] = 0;
   for (j=ncl+1; j<=nch; j++)       printf(" DIRC3 = %s \n",dirc);
     m[nrl][j]=m[nrl][j-1]+nlay;    }
       ss = strrchr( name, '.' );            /* find last / */
   for (i=nrl+1; i<=nrh; i++) {    if (ss >0){
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;      ss++;
     for (j=ncl+1; j<=nch; j++)       strcpy(ext,ss);                     /* save extension */
       m[i][j]=m[i][j-1]+nlay;      l1= strlen( name);
   }      l2= strlen(ss)+1;
   return m;       strncpy( finame, name, l1-l2);
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])      finame[l1-l2]= 0;
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)    }
   */  
 }    return( 0 );                          /* we're done */
   }
 /*************************free ma3x ************************/  
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)  
 {  /******************************************/
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));  
   free((FREE_ARG)(m[nrl]+ncl-NR_END));  void replace_back_to_slash(char *s, char*t)
   free((FREE_ARG)(m+nrl-NR_END));  {
 }    int i;
     int lg=0;
 /***************** f1dim *************************/    i=0;
 extern int ncom;     lg=strlen(t);
 extern double *pcom,*xicom;    for(i=0; i<= lg; i++) {
 extern double (*nrfunc)(double []);       (s[i] = t[i]);
        if (t[i]== '\\') s[i]='/';
 double f1dim(double x)     }
 {   }
   int j;   
   double f;  int nbocc(char *s, char occ)
   double *xt;   {
      int i,j=0;
   xt=vector(1,ncom);     int lg=20;
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];     i=0;
   f=(*nrfunc)(xt);     lg=strlen(s);
   free_vector(xt,1,ncom);     for(i=0; i<= lg; i++) {
   return f;     if  (s[i] == occ ) j++;
 }     }
     return j;
 /*****************brent *************************/  }
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)   
 {   void cutv(char *u,char *v, char*t, char occ)
   int iter;   {
   double a,b,d,etemp;    /* cuts string t into u and v where u ends before first occurence of char 'occ'
   double fu,fv,fw,fx;       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
   double ftemp;       gives u="abcedf" and v="ghi2j" */
   double p,q,r,tol1,tol2,u,v,w,x,xm;     int i,lg,j,p=0;
   double e=0.0;     i=0;
      for(j=0; j<=strlen(t)-1; j++) {
   a=(ax < cx ? ax : cx);       if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
   b=(ax > cx ? ax : cx);     }
   x=w=v=bx;   
   fw=fv=fx=(*f)(x);     lg=strlen(t);
   for (iter=1;iter<=ITMAX;iter++) {     for(j=0; j<p; j++) {
     xm=0.5*(a+b);       (u[j] = t[j]);
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     }
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/       u[p]='\0';
     printf(".");fflush(stdout);  
     fprintf(ficlog,".");fflush(ficlog);     for(j=0; j<= lg; j++) {
 #ifdef DEBUG      if (j>=(p+1))(v[j-p-1] = t[j]);
     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);    }
     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);  }
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */  
 #endif  /********************** nrerror ********************/
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){   
       *xmin=x;   void nrerror(char error_text[])
       return fx;   {
     }     fprintf(stderr,"ERREUR ...\n");
     ftemp=fu;    fprintf(stderr,"%s\n",error_text);
     if (fabs(e) > tol1) {     exit(EXIT_FAILURE);
       r=(x-w)*(fx-fv);   }
       q=(x-v)*(fx-fw);   /*********************** vector *******************/
       p=(x-v)*q-(x-w)*r;   double *vector(int nl, int nh)
       q=2.0*(q-r);   {
       if (q > 0.0) p = -p;     double *v;
       q=fabs(q);     v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
       etemp=e;     if (!v) nrerror("allocation failure in vector");
       e=d;     return v-nl+NR_END;
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))   }
         d=CGOLD*(e=(x >= xm ? a-x : b-x));   
       else {   /************************ free vector ******************/
         d=p/q;   void free_vector(double*v, int nl, int nh)
         u=x+d;   {
         if (u-a < tol2 || b-u < tol2)     free((FREE_ARG)(v+nl-NR_END));
           d=SIGN(tol1,xm-x);   }
       }   
     } else {   /************************ivector *******************************/
       d=CGOLD*(e=(x >= xm ? a-x : b-x));   int *ivector(long nl,long nh)
     }   {
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));     int *v;
     fu=(*f)(u);     v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
     if (fu <= fx) {     if (!v) nrerror("allocation failure in ivector");
       if (u >= x) a=x; else b=x;     return v-nl+NR_END;
       SHFT(v,w,x,u)   }
         SHFT(fv,fw,fx,fu)   
         } else {   /******************free ivector **************************/
           if (u < x) a=u; else b=u;   void free_ivector(int *v, long nl, long nh)
           if (fu <= fw || w == x) {   {
             v=w;     free((FREE_ARG)(v+nl-NR_END));
             w=u;   }
             fv=fw;   
             fw=fu;   /************************lvector *******************************/
           } else if (fu <= fv || v == x || v == w) {   long *lvector(long nl,long nh)
             v=u;   {
             fv=fu;     long *v;
           }     v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
         }     if (!v) nrerror("allocation failure in ivector");
   }     return v-nl+NR_END;
   nrerror("Too many iterations in brent");   }
   *xmin=x;   
   return fx;   /******************free lvector **************************/
 }   void free_lvector(long *v, long nl, long nh)
   {
 /****************** mnbrak ***********************/    free((FREE_ARG)(v+nl-NR_END));
   }
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,   
             double (*func)(double))   /******************* imatrix *******************************/
 {   int **imatrix(long nrl, long nrh, long ncl, long nch)
   double ulim,u,r,q, dum;       /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
   double fu;   {
      long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
   *fa=(*func)(*ax);     int **m;
   *fb=(*func)(*bx);    
   if (*fb > *fa) {     /* allocate pointers to rows */
     SHFT(dum,*ax,*bx,dum)     m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
       SHFT(dum,*fb,*fa,dum)     if (!m) nrerror("allocation failure 1 in matrix()");
       }     m += NR_END;
   *cx=(*bx)+GOLD*(*bx-*ax);     m -= nrl;
   *fc=(*func)(*cx);    
   while (*fb > *fc) {    
     r=(*bx-*ax)*(*fb-*fc);     /* allocate rows and set pointers to them */
     q=(*bx-*cx)*(*fb-*fa);     m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));     m[nrl] += NR_END;
     ulim=(*bx)+GLIMIT*(*cx-*bx);     m[nrl] -= ncl;
     if ((*bx-u)*(u-*cx) > 0.0) {    
       fu=(*func)(u);     for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
     } else if ((*cx-u)*(u-ulim) > 0.0) {    
       fu=(*func)(u);     /* return pointer to array of pointers to rows */
       if (fu < *fc) {     return m;
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))   }
           SHFT(*fb,*fc,fu,(*func)(u))   
           }   /****************** free_imatrix *************************/
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {   void free_imatrix(m,nrl,nrh,ncl,nch)
       u=ulim;         int **m;
       fu=(*func)(u);         long nch,ncl,nrh,nrl;
     } else {        /* free an int matrix allocated by imatrix() */
       u=(*cx)+GOLD*(*cx-*bx);   {
       fu=(*func)(u);     free((FREE_ARG) (m[nrl]+ncl-NR_END));
     }     free((FREE_ARG) (m+nrl-NR_END));
     SHFT(*ax,*bx,*cx,u)   }
       SHFT(*fa,*fb,*fc,fu)   
       }   /******************* matrix *******************************/
 }   double **matrix(long nrl, long nrh, long ncl, long nch)
   {
 /*************** linmin ************************/    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
     double **m;
 int ncom;   
 double *pcom,*xicom;    m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 double (*nrfunc)(double []);     if (!m) nrerror("allocation failure 1 in matrix()");
      m += NR_END;
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))     m -= nrl;
 {   
   double brent(double ax, double bx, double cx,     m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                double (*f)(double), double tol, double *xmin);     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   double f1dim(double x);     m[nrl] += NR_END;
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,     m[nrl] -= ncl;
               double *fc, double (*func)(double));   
   int j;     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   double xx,xmin,bx,ax;     return m;
   double fx,fb,fa;    /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
       */
   ncom=n;   }
   pcom=vector(1,n);   
   xicom=vector(1,n);   /*************************free matrix ************************/
   nrfunc=func;   void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   for (j=1;j<=n;j++) {   {
     pcom[j]=p[j];     free((FREE_ARG)(m[nrl]+ncl-NR_END));
     xicom[j]=xi[j];     free((FREE_ARG)(m+nrl-NR_END));
   }   }
   ax=0.0;   
   xx=1.0;   /******************* ma3x *******************************/
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);   double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);   {
 #ifdef DEBUG    long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);    double ***m;
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  
 #endif    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   for (j=1;j<=n;j++) {     if (!m) nrerror("allocation failure 1 in matrix()");
     xi[j] *= xmin;     m += NR_END;
     p[j] += xi[j];     m -= nrl;
   }   
   free_vector(xicom,1,n);     m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   free_vector(pcom,1,n);     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 }     m[nrl] += NR_END;
     m[nrl] -= ncl;
 char *asc_diff_time(long time_sec, char ascdiff[])  
 {    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   long sec_left, days, hours, minutes;  
   days = (time_sec) / (60*60*24);    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
   sec_left = (time_sec) % (60*60*24);    if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
   hours = (sec_left) / (60*60) ;    m[nrl][ncl] += NR_END;
   sec_left = (sec_left) %(60*60);    m[nrl][ncl] -= nll;
   minutes = (sec_left) /60;    for (j=ncl+1; j<=nch; j++)
   sec_left = (sec_left) % (60);      m[nrl][j]=m[nrl][j-1]+nlay;
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);     
   return ascdiff;    for (i=nrl+1; i<=nrh; i++) {
 }      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
       for (j=ncl+1; j<=nch; j++)
 /*************** powell ************************/        m[i][j]=m[i][j-1]+nlay;
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,     }
             double (*func)(double []))     return m;
 {     /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
   void linmin(double p[], double xi[], int n, double *fret,              &(m[i][j][k]) <=> *((*(m+i) + j)+k)
               double (*func)(double []));     */
   int i,ibig,j;   }
   double del,t,*pt,*ptt,*xit;  
   double fp,fptt;  /*************************free ma3x ************************/
   double *xits;  void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
   int niterf, itmp;  {
     free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
   pt=vector(1,n);     free((FREE_ARG)(m[nrl]+ncl-NR_END));
   ptt=vector(1,n);     free((FREE_ARG)(m+nrl-NR_END));
   xit=vector(1,n);   }
   xits=vector(1,n);   
   *fret=(*func)(p);   /*************** function subdirf ***********/
   for (j=1;j<=n;j++) pt[j]=p[j];   char *subdirf(char fileres[])
   for (*iter=1;;++(*iter)) {   {
     fp=(*fret);     /* Caution optionfilefiname is hidden */
     ibig=0;     strcpy(tmpout,optionfilefiname);
     del=0.0;     strcat(tmpout,"/"); /* Add to the right */
     last_time=curr_time;    strcat(tmpout,fileres);
     (void) gettimeofday(&curr_time,&tzp);    return tmpout;
     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);  }
     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);  
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);  /*************** function subdirf2 ***********/
     for (i=1;i<=n;i++) {  char *subdirf2(char fileres[], char *preop)
       printf(" %d %.12f",i, p[i]);  {
       fprintf(ficlog," %d %.12lf",i, p[i]);   
       fprintf(ficrespow," %.12lf", p[i]);    /* Caution optionfilefiname is hidden */
     }    strcpy(tmpout,optionfilefiname);
     printf("\n");    strcat(tmpout,"/");
     fprintf(ficlog,"\n");    strcat(tmpout,preop);
     fprintf(ficrespow,"\n");fflush(ficrespow);    strcat(tmpout,fileres);
     if(*iter <=3){    return tmpout;
       tm = *localtime(&curr_time.tv_sec);  }
       strcpy(strcurr,asctime(&tmf));  
 /*       asctime_r(&tm,strcurr); */  /*************** function subdirf3 ***********/
       forecast_time=curr_time;  char *subdirf3(char fileres[], char *preop, char *preop2)
       itmp = strlen(strcurr);  {
       if(strcurr[itmp-1]=='\n')   
         strcurr[itmp-1]='\0';    /* Caution optionfilefiname is hidden */
       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);    strcpy(tmpout,optionfilefiname);
       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);    strcat(tmpout,"/");
       for(niterf=10;niterf<=30;niterf+=10){    strcat(tmpout,preop);
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);    strcat(tmpout,preop2);
         tmf = *localtime(&forecast_time.tv_sec);    strcat(tmpout,fileres);
 /*      asctime_r(&tmf,strfor); */    return tmpout;
         strcpy(strfor,asctime(&tmf));  }
         itmp = strlen(strfor);  
         if(strfor[itmp-1]=='\n')  /***************** f1dim *************************/
         strfor[itmp-1]='\0';  extern int ncom;
         printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s or\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);  extern double *pcom,*xicom;
         fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s or\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);  extern double (*nrfunc)(double []);
       }   
     }  double f1dim(double x)
     for (i=1;i<=n;i++) {   {
       for (j=1;j<=n;j++) xit[j]=xi[j][i];     int j;
       fptt=(*fret);     double f;
 #ifdef DEBUG    double *xt;
       printf("fret=%lf \n",*fret);   
       fprintf(ficlog,"fret=%lf \n",*fret);    xt=vector(1,ncom);
 #endif    for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
       printf("%d",i);fflush(stdout);    f=(*nrfunc)(xt);
       fprintf(ficlog,"%d",i);fflush(ficlog);    free_vector(xt,1,ncom);
       linmin(p,xit,n,fret,func);     return f;
       if (fabs(fptt-(*fret)) > del) {   }
         del=fabs(fptt-(*fret));   
         ibig=i;   /*****************brent *************************/
       }   double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
 #ifdef DEBUG  {
       printf("%d %.12e",i,(*fret));    int iter;
       fprintf(ficlog,"%d %.12e",i,(*fret));    double a,b,d,etemp;
       for (j=1;j<=n;j++) {    double fu,fv,fw,fx;
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);    double ftemp;
         printf(" x(%d)=%.12e",j,xit[j]);    double p,q,r,tol1,tol2,u,v,w,x,xm;
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);    double e=0.0;
       }   
       for(j=1;j<=n;j++) {    a=(ax < cx ? ax : cx);
         printf(" p=%.12e",p[j]);    b=(ax > cx ? ax : cx);
         fprintf(ficlog," p=%.12e",p[j]);    x=w=v=bx;
       }    fw=fv=fx=(*f)(x);
       printf("\n");    for (iter=1;iter<=ITMAX;iter++) {
       fprintf(ficlog,"\n");      xm=0.5*(a+b);
 #endif      tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
     }       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {      printf(".");fflush(stdout);
 #ifdef DEBUG      fprintf(ficlog,".");fflush(ficlog);
       int k[2],l;  #ifdef DEBUG
       k[0]=1;      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);
       k[1]=-1;      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);
       printf("Max: %.12e",(*func)(p));      /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
       fprintf(ficlog,"Max: %.12e",(*func)(p));  #endif
       for (j=1;j<=n;j++) {      if (fabs(x-xm) <= (tol2-0.5*(b-a))){
         printf(" %.12e",p[j]);        *xmin=x;
         fprintf(ficlog," %.12e",p[j]);        return fx;
       }      }
       printf("\n");      ftemp=fu;
       fprintf(ficlog,"\n");      if (fabs(e) > tol1) {
       for(l=0;l<=1;l++) {        r=(x-w)*(fx-fv);
         for (j=1;j<=n;j++) {        q=(x-v)*(fx-fw);
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];        p=(x-v)*q-(x-w)*r;
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        q=2.0*(q-r);
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        if (q > 0.0) p = -p;
         }        q=fabs(q);
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        etemp=e;
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        e=d;
       }        if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
 #endif          d=CGOLD*(e=(x >= xm ? a-x : b-x));
         else {
           d=p/q;
       free_vector(xit,1,n);           u=x+d;
       free_vector(xits,1,n);           if (u-a < tol2 || b-u < tol2)
       free_vector(ptt,1,n);             d=SIGN(tol1,xm-x);
       free_vector(pt,1,n);         }
       return;       } else {
     }         d=CGOLD*(e=(x >= xm ? a-x : b-x));
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");       }
     for (j=1;j<=n;j++) {       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
       ptt[j]=2.0*p[j]-pt[j];       fu=(*f)(u);
       xit[j]=p[j]-pt[j];       if (fu <= fx) {
       pt[j]=p[j];         if (u >= x) a=x; else b=x;
     }         SHFT(v,w,x,u)
     fptt=(*func)(ptt);           SHFT(fv,fw,fx,fu)
     if (fptt < fp) {           } else {
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);             if (u < x) a=u; else b=u;
       if (t < 0.0) {             if (fu <= fw || w == x) {
         linmin(p,xit,n,fret,func);               v=w;
         for (j=1;j<=n;j++) {               w=u;
           xi[j][ibig]=xi[j][n];               fv=fw;
           xi[j][n]=xit[j];               fw=fu;
         }            } else if (fu <= fv || v == x || v == w) {
 #ifdef DEBUG              v=u;
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);              fv=fu;
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);            }
         for(j=1;j<=n;j++){          }
           printf(" %.12e",xit[j]);    }
           fprintf(ficlog," %.12e",xit[j]);    nrerror("Too many iterations in brent");
         }    *xmin=x;
         printf("\n");    return fx;
         fprintf(ficlog,"\n");  }
 #endif  
       }  /****************** mnbrak ***********************/
     }   
   }   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
 }               double (*func)(double))
   {
 /**** Prevalence limit (stable prevalence)  ****************/    double ulim,u,r,q, dum;
     double fu;
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)   
 {    *fa=(*func)(*ax);
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit    *fb=(*func)(*bx);
      matrix by transitions matrix until convergence is reached */    if (*fb > *fa) {
       SHFT(dum,*ax,*bx,dum)
   int i, ii,j,k;        SHFT(dum,*fb,*fa,dum)
   double min, max, maxmin, maxmax,sumnew=0.;        }
   double **matprod2();    *cx=(*bx)+GOLD*(*bx-*ax);
   double **out, cov[NCOVMAX], **pmij();    *fc=(*func)(*cx);
   double **newm;    while (*fb > *fc) {
   double agefin, delaymax=50 ; /* Max number of years to converge */      r=(*bx-*ax)*(*fb-*fc);
       q=(*bx-*cx)*(*fb-*fa);
   for (ii=1;ii<=nlstate+ndeath;ii++)      u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
     for (j=1;j<=nlstate+ndeath;j++){        (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);      ulim=(*bx)+GLIMIT*(*cx-*bx);
     }      if ((*bx-u)*(u-*cx) > 0.0) {
         fu=(*func)(u);
    cov[1]=1.;      } else if ((*cx-u)*(u-ulim) > 0.0) {
          fu=(*func)(u);
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */        if (fu < *fc) {
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
     newm=savm;            SHFT(*fb,*fc,fu,(*func)(u))
     /* Covariates have to be included here again */            }
      cov[2]=agefin;      } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
           u=ulim;
       for (k=1; k<=cptcovn;k++) {        fu=(*func)(u);
         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];      } else {
         /*      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]]);*/        u=(*cx)+GOLD*(*cx-*bx);
       }        fu=(*func)(u);
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];      }
       for (k=1; k<=cptcovprod;k++)      SHFT(*ax,*bx,*cx,u)
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        SHFT(*fa,*fb,*fc,fu)
         }
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/  }
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/  
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/  /*************** linmin ************************/
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);  
   int ncom;
     savm=oldm;  double *pcom,*xicom;
     oldm=newm;  double (*nrfunc)(double []);
     maxmax=0.;   
     for(j=1;j<=nlstate;j++){  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
       min=1.;  {
       max=0.;    double brent(double ax, double bx, double cx,
       for(i=1; i<=nlstate; i++) {                 double (*f)(double), double tol, double *xmin);
         sumnew=0;    double f1dim(double x);
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
         prlim[i][j]= newm[i][j]/(1-sumnew);                double *fc, double (*func)(double));
         max=FMAX(max,prlim[i][j]);    int j;
         min=FMIN(min,prlim[i][j]);    double xx,xmin,bx,ax;
       }    double fx,fb,fa;
       maxmin=max-min;   
       maxmax=FMAX(maxmax,maxmin);    ncom=n;
     }    pcom=vector(1,n);
     if(maxmax < ftolpl){    xicom=vector(1,n);
       return prlim;    nrfunc=func;
     }    for (j=1;j<=n;j++) {
   }      pcom[j]=p[j];
 }      xicom[j]=xi[j];
     }
 /*************** transition probabilities ***************/     ax=0.0;
     xx=1.0;
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )    mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
 {    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
   double s1, s2;  #ifdef DEBUG
   /*double t34;*/    printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   int i,j,j1, nc, ii, jj;    fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   #endif
     for(i=1; i<= nlstate; i++){    for (j=1;j<=n;j++) {
     for(j=1; j<i;j++){      xi[j] *= xmin;
       for (nc=1, s2=0.;nc <=ncovmodel; nc++){      p[j] += xi[j];
         /*s2 += param[i][j][nc]*cov[nc];*/    }
         s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];    free_vector(xicom,1,n);
         /*printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2);*/    free_vector(pcom,1,n);
       }  }
       ps[i][j]=s2;  
       /*printf("s1=%.17e, s2=%.17e\n",s1,s2);*/  char *asc_diff_time(long time_sec, char ascdiff[])
     }  {
     for(j=i+1; j<=nlstate+ndeath;j++){    long sec_left, days, hours, minutes;
       for (nc=1, s2=0.;nc <=ncovmodel; nc++){    days = (time_sec) / (60*60*24);
         s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];    sec_left = (time_sec) % (60*60*24);
         /*printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2);*/    hours = (sec_left) / (60*60) ;
       }    sec_left = (sec_left) %(60*60);
       ps[i][j]=s2;    minutes = (sec_left) /60;
     }    sec_left = (sec_left) % (60);
   }    sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
     /*ps[3][2]=1;*/    return ascdiff;
   }
   for(i=1; i<= nlstate; i++){  
      s1=0;  /*************** powell ************************/
     for(j=1; j<i; j++)  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
       s1+=exp(ps[i][j]);              double (*func)(double []))
     for(j=i+1; j<=nlstate+ndeath; j++)  {
       s1+=exp(ps[i][j]);    void linmin(double p[], double xi[], int n, double *fret,
     ps[i][i]=1./(s1+1.);                double (*func)(double []));
     for(j=1; j<i; j++)    int i,ibig,j;
       ps[i][j]= exp(ps[i][j])*ps[i][i];    double del,t,*pt,*ptt,*xit;
     for(j=i+1; j<=nlstate+ndeath; j++)    double fp,fptt;
       ps[i][j]= exp(ps[i][j])*ps[i][i];    double *xits;
     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */    int niterf, itmp;
   } /* end i */  
     pt=vector(1,n);
   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){    ptt=vector(1,n);
     for(jj=1; jj<= nlstate+ndeath; jj++){    xit=vector(1,n);
       ps[ii][jj]=0;    xits=vector(1,n);
       ps[ii][ii]=1;    *fret=(*func)(p);
     }    for (j=1;j<=n;j++) pt[j]=p[j];
   }    for (*iter=1;;++(*iter)) {
       fp=(*fret);
       ibig=0;
   /*   for(ii=1; ii<= nlstate+ndeath; ii++){      del=0.0;
     for(jj=1; jj<= nlstate+ndeath; jj++){      last_time=curr_time;
      printf("%lf ",ps[ii][jj]);      (void) gettimeofday(&curr_time,&tzp);
    }      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);
     printf("\n ");      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); fflush(ficlog);
     }  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
     printf("\n ");printf("%lf ",cov[2]);*/     for (i=1;i<=n;i++) {
 /*        printf(" %d %.12f",i, p[i]);
   for(i=1; i<= npar; i++) printf("%f ",x[i]);        fprintf(ficlog," %d %.12lf",i, p[i]);
   goto end;*/        fprintf(ficrespow," %.12lf", p[i]);
     return ps;      }
 }      printf("\n");
       fprintf(ficlog,"\n");
 /**************** Product of 2 matrices ******************/      fprintf(ficrespow,"\n");fflush(ficrespow);
       if(*iter <=3){
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)        tm = *localtime(&curr_time.tv_sec);
 {        strcpy(strcurr,asctime(&tm));
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times  /*       asctime_r(&tm,strcurr); */
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */        forecast_time=curr_time;
   /* in, b, out are matrice of pointers which should have been initialized         itmp = strlen(strcurr);
      before: only the contents of out is modified. The function returns        if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
      a pointer to pointers identical to out */          strcurr[itmp-1]='\0';
   long i, j, k;        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
   for(i=nrl; i<= nrh; i++)        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
     for(k=ncolol; k<=ncoloh; k++)        for(niterf=10;niterf<=30;niterf+=10){
       for(j=ncl,out[i][k]=0.; j<=nch; j++)          forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
         out[i][k] +=in[i][j]*b[j][k];          tmf = *localtime(&forecast_time.tv_sec);
   /*      asctime_r(&tmf,strfor); */
   return out;          strcpy(strfor,asctime(&tmf));
 }          itmp = strlen(strfor);
           if(strfor[itmp-1]=='\n')
           strfor[itmp-1]='\0';
 /************* Higher Matrix Product ***************/          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);
           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);
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )        }
 {      }
   /* Computes the transition matrix starting at age 'age' over       for (i=1;i<=n;i++) {
      'nhstepm*hstepm*stepm' months (i.e. until        for (j=1;j<=n;j++) xit[j]=xi[j][i];
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying         fptt=(*fret);
      nhstepm*hstepm matrices.   #ifdef DEBUG
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step         printf("fret=%lf \n",*fret);
      (typically every 2 years instead of every month which is too big         fprintf(ficlog,"fret=%lf \n",*fret);
      for the memory).  #endif
      Model is determined by parameters x and covariates have to be         printf("%d",i);fflush(stdout);
      included manually here.         fprintf(ficlog,"%d",i);fflush(ficlog);
         linmin(p,xit,n,fret,func);
      */        if (fabs(fptt-(*fret)) > del) {
           del=fabs(fptt-(*fret));
   int i, j, d, h, k;          ibig=i;
   double **out, cov[NCOVMAX];        }
   double **newm;  #ifdef DEBUG
         printf("%d %.12e",i,(*fret));
   /* Hstepm could be zero and should return the unit matrix */        fprintf(ficlog,"%d %.12e",i,(*fret));
   for (i=1;i<=nlstate+ndeath;i++)        for (j=1;j<=n;j++) {
     for (j=1;j<=nlstate+ndeath;j++){          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
       oldm[i][j]=(i==j ? 1.0 : 0.0);          printf(" x(%d)=%.12e",j,xit[j]);
       po[i][j][0]=(i==j ? 1.0 : 0.0);          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
     }        }
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */        for(j=1;j<=n;j++) {
   for(h=1; h <=nhstepm; h++){          printf(" p=%.12e",p[j]);
     for(d=1; d <=hstepm; d++){          fprintf(ficlog," p=%.12e",p[j]);
       newm=savm;        }
       /* Covariates have to be included here again */        printf("\n");
       cov[1]=1.;        fprintf(ficlog,"\n");
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;  #endif
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];      }
       for (k=1; k<=cptcovage;k++)      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];  #ifdef DEBUG
       for (k=1; k<=cptcovprod;k++)        int k[2],l;
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        k[0]=1;
         k[1]=-1;
         printf("Max: %.12e",(*func)(p));
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/        fprintf(ficlog,"Max: %.12e",(*func)(p));
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/        for (j=1;j<=n;j++) {
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,           printf(" %.12e",p[j]);
                    pmij(pmmij,cov,ncovmodel,x,nlstate));          fprintf(ficlog," %.12e",p[j]);
       savm=oldm;        }
       oldm=newm;        printf("\n");
     }        fprintf(ficlog,"\n");
     for(i=1; i<=nlstate+ndeath; i++)        for(l=0;l<=1;l++) {
       for(j=1;j<=nlstate+ndeath;j++) {          for (j=1;j<=n;j++) {
         po[i][j][h]=newm[i][j];            ptt[j]=p[j]+(p[j]-pt[j])*k[l];
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);            printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
          */            fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
       }          }
   } /* end h */          printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
   return po;          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 }        }
   #endif
   
 /*************** log-likelihood *************/  
 double func( double *x)        free_vector(xit,1,n);
 {        free_vector(xits,1,n);
   int i, ii, j, k, mi, d, kk;        free_vector(ptt,1,n);
   double l, ll[NLSTATEMAX], cov[NCOVMAX];        free_vector(pt,1,n);
   double **out;        return;
   double sw; /* Sum of weights */      }
   double lli; /* Individual log likelihood */      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
   int s1, s2;      for (j=1;j<=n;j++) {
   double bbh, survp;        ptt[j]=2.0*p[j]-pt[j];
   long ipmx;        xit[j]=p[j]-pt[j];
   /*extern weight */        pt[j]=p[j];
   /* We are differentiating ll according to initial status */      }
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/      fptt=(*func)(ptt);
   /*for(i=1;i<imx;i++)       if (fptt < fp) {
     printf(" %d\n",s[4][i]);        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
   */        if (t < 0.0) {
   cov[1]=1.;          linmin(p,xit,n,fret,func);
           for (j=1;j<=n;j++) {
   for(k=1; k<=nlstate; k++) ll[k]=0.;            xi[j][ibig]=xi[j][n];
             xi[j][n]=xit[j];
   if(mle==1){          }
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  #ifdef DEBUG
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
       for(mi=1; mi<= wav[i]-1; mi++){          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
         for (ii=1;ii<=nlstate+ndeath;ii++)          for(j=1;j<=n;j++){
           for (j=1;j<=nlstate+ndeath;j++){            printf(" %.12e",xit[j]);
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);            fprintf(ficlog," %.12e",xit[j]);
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          }
           }          printf("\n");
         for(d=0; d<dh[mi][i]; d++){          fprintf(ficlog,"\n");
           newm=savm;  #endif
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        }
           for (kk=1; kk<=cptcovage;kk++) {      }
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    }
           }  }
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,  
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));  /**** Prevalence limit (stable or period prevalence)  ****************/
           savm=oldm;  
           oldm=newm;  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
         } /* end mult */  {
           /* Computes the prevalence limit in each live state at age x by left multiplying the unit
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */       matrix by transitions matrix until convergence is reached */
         /* But now since version 0.9 we anticipate for bias and large stepm.  
          * If stepm is larger than one month (smallest stepm) and if the exact delay     int i, ii,j,k;
          * (in months) between two waves is not a multiple of stepm, we rounded to     double min, max, maxmin, maxmax,sumnew=0.;
          * the nearest (and in case of equal distance, to the lowest) interval but now    double **matprod2();
          * we keep into memory the bias bh[mi][i] and also the previous matrix product    double **out, cov[NCOVMAX], **pmij();
          * (i.e to dh[mi][i]-1) saved in 'savm'. The we inter(extra)polate the    double **newm;
          * probability in order to take into account the bias as a fraction of the way    double agefin, delaymax=50 ; /* Max number of years to converge */
          * from savm to out if bh is neagtive or even beyond if bh is positive. bh varies  
          * -stepm/2 to stepm/2 .    for (ii=1;ii<=nlstate+ndeath;ii++)
          * For stepm=1 the results are the same as for previous versions of Imach.      for (j=1;j<=nlstate+ndeath;j++){
          * For stepm > 1 the results are less biased than in previous versions.         oldm[ii][j]=(ii==j ? 1.0 : 0.0);
          */      }
         s1=s[mw[mi][i]][i];  
         s2=s[mw[mi+1][i]][i];     cov[1]=1.;
         bbh=(double)bh[mi][i]/(double)stepm;    
         /* bias is positive if real duration   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
          * is higher than the multiple of stepm and negative otherwise.    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
          */      newm=savm;
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/      /* Covariates have to be included here again */
         if( s2 > nlstate){        cov[2]=agefin;
           /* i.e. if s2 is a death state and if the date of death is known then the contribution   
              to the likelihood is the probability to die between last step unit time and current         for (k=1; k<=cptcovn;k++) {
              step unit time, which is also the differences between probability to die before dh           cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
              and probability to die before dh-stepm .           /*      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]]);*/
              In version up to 0.92 likelihood was computed        }
         as if date of death was unknown. Death was treated as any other        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         health state: the date of the interview describes the actual state        for (k=1; k<=cptcovprod;k++)
         and not the date of a change in health state. The former idea was          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         to consider that at each interview the state was recorded  
         (healthy, disable or death) and IMaCh was corrected; but when we        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
         introduced the exact date of death then we should have modified        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
         the contribution of an exact death to the likelihood. This new        /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
         contribution is smaller and very dependent of the step unit      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
         stepm. It is no more the probability to die between last interview  
         and month of death but the probability to survive from last      savm=oldm;
         interview up to one month before death multiplied by the      oldm=newm;
         probability to die within a month. Thanks to Chris      maxmax=0.;
         Jackson for correcting this bug.  Former versions increased      for(j=1;j<=nlstate;j++){
         mortality artificially. The bad side is that we add another loop        min=1.;
         which slows down the processing. The difference can be up to 10%        max=0.;
         lower mortality.        for(i=1; i<=nlstate; i++) {
           */          sumnew=0;
           lli=log(out[s1][s2] - savm[s1][s2]);          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
         }else{          prlim[i][j]= newm[i][j]/(1-sumnew);
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */          max=FMAX(max,prlim[i][j]);
           /*  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 */          min=FMIN(min,prlim[i][j]);
         }         }
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/        maxmin=max-min;
         /*if(lli ==000.0)*/        maxmax=FMAX(maxmax,maxmin);
         /*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); */      }
         ipmx +=1;      if(maxmax < ftolpl){
         sw += weight[i];        return prlim;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;      }
       } /* end of wave */    }
     } /* end of individual */  }
   }  else if(mle==2){  
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  /*************** transition probabilities ***************/
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];  
       for(mi=1; mi<= wav[i]-1; mi++){  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
         for (ii=1;ii<=nlstate+ndeath;ii++)  {
           for (j=1;j<=nlstate+ndeath;j++){    double s1, s2;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    /*double t34;*/
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    int i,j,j1, nc, ii, jj;
           }  
         for(d=0; d<=dh[mi][i]; d++){      for(i=1; i<= nlstate; i++){
           newm=savm;        for(j=1; j<i;j++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
           for (kk=1; kk<=cptcovage;kk++) {            /*s2 += param[i][j][nc]*cov[nc];*/
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
           }  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          }
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          ps[i][j]=s2;
           savm=oldm;  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
           oldm=newm;        }
         } /* end mult */        for(j=i+1; j<=nlstate+ndeath;j++){
                 for (nc=1, s2=0.;nc <=ncovmodel; nc++){
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
         /* But now since version 0.9 we anticipate for bias and large stepm.  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
          * If stepm is larger than one month (smallest stepm) and if the exact delay           }
          * (in months) between two waves is not a multiple of stepm, we rounded to           ps[i][j]=s2;
          * the nearest (and in case of equal distance, to the lowest) interval but now        }
          * we keep into memory the bias bh[mi][i] and also the previous matrix product      }
          * (i.e to dh[mi][i]-1) saved in 'savm'. The we inter(extra)polate the      /*ps[3][2]=1;*/
          * probability in order to take into account the bias as a fraction of the way     
          * from savm to out if bh is neagtive or even beyond if bh is positive. bh varies      for(i=1; i<= nlstate; i++){
          * -stepm/2 to stepm/2 .        s1=0;
          * For stepm=1 the results are the same as for previous versions of Imach.        for(j=1; j<i; j++)
          * For stepm > 1 the results are less biased than in previous versions.           s1+=exp(ps[i][j]);
          */        for(j=i+1; j<=nlstate+ndeath; j++)
         s1=s[mw[mi][i]][i];          s1+=exp(ps[i][j]);
         s2=s[mw[mi+1][i]][i];        ps[i][i]=1./(s1+1.);
         bbh=(double)bh[mi][i]/(double)stepm;         for(j=1; j<i; j++)
         /* bias is positive if real duration          ps[i][j]= exp(ps[i][j])*ps[i][i];
          * is higher than the multiple of stepm and negative otherwise.        for(j=i+1; j<=nlstate+ndeath; j++)
          */          ps[i][j]= exp(ps[i][j])*ps[i][i];
         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 */        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/      } /* end i */
         /*lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.-+bh)*out[s1][s2])); */ /* exponential interpolation */     
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/      for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
         /*if(lli ==000.0)*/        for(jj=1; jj<= nlstate+ndeath; jj++){
         /*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); */          ps[ii][jj]=0;
         ipmx +=1;          ps[ii][ii]=1;
         sw += weight[i];        }
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;      }
       } /* end of wave */     
     } /* end of individual */  
   }  else if(mle==3){  /* exponential inter-extrapolation */  /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];  /*         printf("ddd %lf ",ps[ii][jj]); */
       for(mi=1; mi<= wav[i]-1; mi++){  /*       } */
         for (ii=1;ii<=nlstate+ndeath;ii++)  /*       printf("\n "); */
           for (j=1;j<=nlstate+ndeath;j++){  /*        } */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);  /*        printf("\n ");printf("%lf ",cov[2]); */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);         /*
           }        for(i=1; i<= npar; i++) printf("%f ",x[i]);
         for(d=0; d<dh[mi][i]; d++){        goto end;*/
           newm=savm;      return ps;
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;  }
           for (kk=1; kk<=cptcovage;kk++) {  
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];  /**************** Product of 2 matrices ******************/
           }  
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,  double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));  {
           savm=oldm;    /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
           oldm=newm;       b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
         } /* end mult */    /* in, b, out are matrice of pointers which should have been initialized
              before: only the contents of out is modified. The function returns
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */       a pointer to pointers identical to out */
         /* But now since version 0.9 we anticipate for bias and large stepm.    long i, j, k;
          * If stepm is larger than one month (smallest stepm) and if the exact delay     for(i=nrl; i<= nrh; i++)
          * (in months) between two waves is not a multiple of stepm, we rounded to       for(k=ncolol; k<=ncoloh; k++)
          * the nearest (and in case of equal distance, to the lowest) interval but now        for(j=ncl,out[i][k]=0.; j<=nch; j++)
          * we keep into memory the bias bh[mi][i] and also the previous matrix product          out[i][k] +=in[i][j]*b[j][k];
          * (i.e to dh[mi][i]-1) saved in 'savm'. The we inter(extra)polate the  
          * probability in order to take into account the bias as a fraction of the way    return out;
          * from savm to out if bh is neagtive or even beyond if bh is positive. bh varies  }
          * -stepm/2 to stepm/2 .  
          * For stepm=1 the results are the same as for previous versions of Imach.  
          * For stepm > 1 the results are less biased than in previous versions.   /************* Higher Matrix Product ***************/
          */  
         s1=s[mw[mi][i]][i];  double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
         s2=s[mw[mi+1][i]][i];  {
         bbh=(double)bh[mi][i]/(double)stepm;     /* Computes the transition matrix starting at age 'age' over
         /* bias is positive if real duration       'nhstepm*hstepm*stepm' months (i.e. until
          * is higher than the multiple of stepm and negative otherwise.       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
          */       nhstepm*hstepm matrices.
         /* 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 */       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
         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 */       (typically every 2 years instead of every month which is too big
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/       for the memory).
         /*if(lli ==000.0)*/       Model is determined by parameters x and covariates have to be
         /*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); */       included manually here.
         ipmx +=1;  
         sw += weight[i];       */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;  
       } /* end of wave */    int i, j, d, h, k;
     } /* end of individual */    double **out, cov[NCOVMAX];
   }else if (mle==4){  /* ml=4 no inter-extrapolation */    double **newm;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];    /* Hstepm could be zero and should return the unit matrix */
       for(mi=1; mi<= wav[i]-1; mi++){    for (i=1;i<=nlstate+ndeath;i++)
         for (ii=1;ii<=nlstate+ndeath;ii++)      for (j=1;j<=nlstate+ndeath;j++){
           for (j=1;j<=nlstate+ndeath;j++){        oldm[i][j]=(i==j ? 1.0 : 0.0);
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);        po[i][j][0]=(i==j ? 1.0 : 0.0);
             savm[ii][j]=(ii==j ? 1.0 : 0.0);      }
           }    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
         for(d=0; d<dh[mi][i]; d++){    for(h=1; h <=nhstepm; h++){
           newm=savm;      for(d=1; d <=hstepm; d++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        newm=savm;
           for (kk=1; kk<=cptcovage;kk++) {        /* Covariates have to be included here again */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];        cov[1]=1.;
           }        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                 for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,        for (k=1; k<=cptcovage;k++)
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           savm=oldm;        for (k=1; k<=cptcovprod;k++)
           oldm=newm;          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         } /* end mult */  
         
         s1=s[mw[mi][i]][i];        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
         s2=s[mw[mi+1][i]][i];        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
         if( s2 > nlstate){         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
           lli=log(out[s1][s2] - savm[s1][s2]);                     pmij(pmmij,cov,ncovmodel,x,nlstate));
         }else{        savm=oldm;
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */        oldm=newm;
         }      }
         ipmx +=1;      for(i=1; i<=nlstate+ndeath; i++)
         sw += weight[i];        for(j=1;j<=nlstate+ndeath;j++) {
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          po[i][j][h]=newm[i][j];
 /*      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]); */          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
       } /* end of wave */           */
     } /* end of individual */        }
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */    } /* end h */
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){    return po;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];  }
       for(mi=1; mi<= wav[i]-1; mi++){  
         for (ii=1;ii<=nlstate+ndeath;ii++)  
           for (j=1;j<=nlstate+ndeath;j++){  /*************** log-likelihood *************/
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);  double func( double *x)
             savm[ii][j]=(ii==j ? 1.0 : 0.0);  {
           }    int i, ii, j, k, mi, d, kk;
         for(d=0; d<dh[mi][i]; d++){    double l, ll[NLSTATEMAX], cov[NCOVMAX];
           newm=savm;    double **out;
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    double sw; /* Sum of weights */
           for (kk=1; kk<=cptcovage;kk++) {    double lli; /* Individual log likelihood */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    int s1, s2;
           }    double bbh, survp;
             long ipmx;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    /*extern weight */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    /* We are differentiating ll according to initial status */
           savm=oldm;    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
           oldm=newm;    /*for(i=1;i<imx;i++)
         } /* end mult */      printf(" %d\n",s[4][i]);
           */
         s1=s[mw[mi][i]][i];    cov[1]=1.;
         s2=s[mw[mi+1][i]][i];  
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */    for(k=1; k<=nlstate; k++) ll[k]=0.;
         ipmx +=1;  
         sw += weight[i];    if(mle==1){
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         /*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]);*/        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       } /* end of wave */        for(mi=1; mi<= wav[i]-1; mi++){
     } /* end of individual */          for (ii=1;ii<=nlstate+ndeath;ii++)
   } /* End of if */            for (j=1;j<=nlstate+ndeath;j++){
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */            }
   return -l;          for(d=0; d<dh[mi][i]; d++){
 }            newm=savm;
             cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 /*************** log-likelihood *************/            for (kk=1; kk<=cptcovage;kk++) {
 double funcone( double *x)              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 {            }
   /* Same as likeli but slower because of a lot of printf and if */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   int i, ii, j, k, mi, d, kk;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   double l, ll[NLSTATEMAX], cov[NCOVMAX];            savm=oldm;
   double **out;            oldm=newm;
   double lli; /* Individual log likelihood */          } /* end mult */
   double llt;       
   int s1, s2;          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
   double bbh, survp;          /* But now since version 0.9 we anticipate for bias at large stepm.
   /*extern weight */           * If stepm is larger than one month (smallest stepm) and if the exact delay
   /* We are differentiating ll according to initial status */           * (in months) between two waves is not a multiple of stepm, we rounded to
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/           * the nearest (and in case of equal distance, to the lowest) interval but now
   /*for(i=1;i<imx;i++)            * we keep into memory the bias bh[mi][i] and also the previous matrix product
     printf(" %d\n",s[4][i]);           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
   */           * probability in order to take into account the bias as a fraction of the way
   cov[1]=1.;           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
            * -stepm/2 to stepm/2 .
   for(k=1; k<=nlstate; k++) ll[k]=0.;           * For stepm=1 the results are the same as for previous versions of Imach.
            * For stepm > 1 the results are less biased than in previous versions.
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){           */
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          s1=s[mw[mi][i]][i];
     for(mi=1; mi<= wav[i]-1; mi++){          s2=s[mw[mi+1][i]][i];
       for (ii=1;ii<=nlstate+ndeath;ii++)          bbh=(double)bh[mi][i]/(double)stepm;
         for (j=1;j<=nlstate+ndeath;j++){          /* bias bh is positive if real duration
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);           * is higher than the multiple of stepm and negative otherwise.
           savm[ii][j]=(ii==j ? 1.0 : 0.0);           */
         }          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
       for(d=0; d<dh[mi][i]; d++){          if( s2 > nlstate){
         newm=savm;            /* i.e. if s2 is a death state and if the date of death is known
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;               then the contribution to the likelihood is the probability to
         for (kk=1; kk<=cptcovage;kk++) {               die between last step unit time and current  step unit time,
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];               which is also equal to probability to die before dh
         }               minus probability to die before dh-stepm .
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,               In version up to 0.92 likelihood was computed
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          as if date of death was unknown. Death was treated as any other
         savm=oldm;          health state: the date of the interview describes the actual state
         oldm=newm;          and not the date of a change in health state. The former idea was
       } /* end mult */          to consider that at each interview the state was recorded
                 (healthy, disable or death) and IMaCh was corrected; but when we
       s1=s[mw[mi][i]][i];          introduced the exact date of death then we should have modified
       s2=s[mw[mi+1][i]][i];          the contribution of an exact death to the likelihood. This new
       bbh=(double)bh[mi][i]/(double)stepm;           contribution is smaller and very dependent of the step unit
       /* bias is positive if real duration          stepm. It is no more the probability to die between last interview
        * is higher than the multiple of stepm and negative otherwise.          and month of death but the probability to survive from last
        */          interview up to one month before death multiplied by the
       if( s2 > nlstate && (mle <5) ){  /* Jackson */          probability to die within a month. Thanks to Chris
         lli=log(out[s1][s2] - savm[s1][s2]);          Jackson for correcting this bug.  Former versions increased
       } else if (mle==1){          mortality artificially. The bad side is that we add another loop
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */          which slows down the processing. The difference can be up to 10%
       } else if(mle==2){          lower mortality.
         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 */            */
       } else if(mle==3){  /* exponential inter-extrapolation */            lli=log(out[s1][s2] - savm[s1][s2]);
         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 */  
       } else if (mle==4){  /* mle=4 no inter-extrapolation */  
         lli=log(out[s1][s2]); /* Original formula */          } else if  (s2==-2) {
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */            for (j=1,survp=0. ; j<=nlstate; j++)
         lli=log(out[s1][s2]); /* Original formula */              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
       } /* End of if */            /*survp += out[s1][j]; */
       ipmx +=1;            lli= log(survp);
       sw += weight[i];          }
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;         
 /*       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]); */          else if  (s2==-4) {
       if(globpr){            for (j=3,survp=0. ; j<=nlstate; j++)  
         fprintf(ficresilk,"%9d %6d %1d %1d %1d %1d %3d %10.6f %6.4f\              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
  %10.6f %10.6f %10.6f ", \            lli= log(survp);
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],          }
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);  
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){          else if  (s2==-5) {
           llt +=ll[k]*gipmx/gsw;            for (j=1,survp=0. ; j<=2; j++)  
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         }            lli= log(survp);
         fprintf(ficresilk," %10.6f\n", -llt);          }
       }         
     } /* end of wave */          else{
   } /* end of individual */            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];            /*  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 */
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */          }
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
   if(globpr==0){ /* First time we count the contributions and weights */          /*if(lli ==000.0)*/
     gipmx=ipmx;          /*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); */
     gsw=sw;          ipmx +=1;
   }          sw += weight[i];
   return -l;          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 }        } /* end of wave */
       } /* end of individual */
 char *subdirf(char fileres[])    }  else if(mle==2){
 {      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   /* Caution optionfilefiname is hidden */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   strcpy(tmpout,optionfilefiname);        for(mi=1; mi<= wav[i]-1; mi++){
   strcat(tmpout,"/"); /* Add to the right */          for (ii=1;ii<=nlstate+ndeath;ii++)
   strcat(tmpout,fileres);            for (j=1;j<=nlstate+ndeath;j++){
   return tmpout;              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 }              savm[ii][j]=(ii==j ? 1.0 : 0.0);
             }
 char *subdirf2(char fileres[], char *preop)          for(d=0; d<=dh[mi][i]; d++){
 {            newm=savm;
               cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   strcpy(tmpout,optionfilefiname);            for (kk=1; kk<=cptcovage;kk++) {
   strcat(tmpout,"/");              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   strcat(tmpout,preop);            }
   strcat(tmpout,fileres);            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   return tmpout;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 }            savm=oldm;
 char *subdirf3(char fileres[], char *preop, char *preop2)            oldm=newm;
 {          } /* end mult */
          
   strcpy(tmpout,optionfilefiname);          s1=s[mw[mi][i]][i];
   strcat(tmpout,"/");          s2=s[mw[mi+1][i]][i];
   strcat(tmpout,preop);          bbh=(double)bh[mi][i]/(double)stepm;
   strcat(tmpout,preop2);          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 */
   strcat(tmpout,fileres);          ipmx +=1;
   return tmpout;          sw += weight[i];
 }          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         } /* end of wave */
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))      } /* end of individual */
 {    }  else if(mle==3){  /* exponential inter-extrapolation */
   /* This routine should help understanding what is done with       for (i=1,ipmx=0, sw=0.; i<=imx; i++){
      the selection of individuals/waves and        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
      to check the exact contribution to the likelihood.        for(mi=1; mi<= wav[i]-1; mi++){
      Plotting could be done.          for (ii=1;ii<=nlstate+ndeath;ii++)
    */            for (j=1;j<=nlstate+ndeath;j++){
   int k;              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
               savm[ii][j]=(ii==j ? 1.0 : 0.0);
   if(*globpri !=0){ /* Just counts and sums, no printings */            }
     strcpy(fileresilk,"ilk");           for(d=0; d<dh[mi][i]; d++){
     strcat(fileresilk,fileres);            newm=savm;
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       printf("Problem with resultfile: %s\n", fileresilk);            for (kk=1; kk<=cptcovage;kk++) {
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     }            }
     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");            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */            savm=oldm;
     for(k=1; k<=nlstate; k++)             oldm=newm;
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);          } /* end mult */
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");       
   }          s1=s[mw[mi][i]][i];
           s2=s[mw[mi+1][i]][i];
   *fretone=(*funcone)(p);          bbh=(double)bh[mi][i]/(double)stepm;
   if(*globpri !=0){          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 */
     fclose(ficresilk);          ipmx +=1;
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));          sw += weight[i];
     fflush(fichtm);           ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   }         } /* end of wave */
   return;      } /* end of individual */
 }    }else if (mle==4){  /* ml=4 no inter-extrapolation */
       for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 /*********** Maximum Likelihood Estimation ***************/        for(mi=1; mi<= wav[i]-1; mi++){
           for (ii=1;ii<=nlstate+ndeath;ii++)
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))            for (j=1;j<=nlstate+ndeath;j++){
 {              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   int i,j, iter;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   double **xi;            }
   double fret;          for(d=0; d<dh[mi][i]; d++){
   double fretone; /* Only one call to likelihood */            newm=savm;
   char filerespow[FILENAMELENGTH];            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   xi=matrix(1,npar,1,npar);            for (kk=1; kk<=cptcovage;kk++) {
   for (i=1;i<=npar;i++)              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     for (j=1;j<=npar;j++)            }
       xi[i][j]=(i==j ? 1.0 : 0.0);         
   printf("Powell\n");  fprintf(ficlog,"Powell\n");            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   strcpy(filerespow,"pow");                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   strcat(filerespow,fileres);            savm=oldm;
   if((ficrespow=fopen(filerespow,"w"))==NULL) {            oldm=newm;
     printf("Problem with resultfile: %s\n", filerespow);          } /* end mult */
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);       
   }          s1=s[mw[mi][i]][i];
   fprintf(ficrespow,"# Powell\n# iter -2*LL");          s2=s[mw[mi+1][i]][i];
   for (i=1;i<=nlstate;i++)          if( s2 > nlstate){
     for(j=1;j<=nlstate+ndeath;j++)            lli=log(out[s1][s2] - savm[s1][s2]);
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);          }else{
   fprintf(ficrespow,"\n");            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
           }
   powell(p,xi,npar,ftol,&iter,&fret,func);          ipmx +=1;
           sw += weight[i];
   fclose(ficrespow);          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));  /*      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]); */
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));        } /* end of wave */
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));      } /* end of individual */
     }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 }      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 /**** Computes Hessian and covariance matrix ***/        for(mi=1; mi<= wav[i]-1; mi++){
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))          for (ii=1;ii<=nlstate+ndeath;ii++)
 {            for (j=1;j<=nlstate+ndeath;j++){
   double  **a,**y,*x,pd;              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   double **hess;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   int i, j,jk;            }
   int *indx;          for(d=0; d<dh[mi][i]; d++){
             newm=savm;
   double hessii(double p[], double delta, int theta, double delti[]);            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   double hessij(double p[], double delti[], int i, int j);            for (kk=1; kk<=cptcovage;kk++) {
   void lubksb(double **a, int npar, int *indx, double b[]) ;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   void ludcmp(double **a, int npar, int *indx, double *d) ;            }
          
   hess=matrix(1,npar,1,npar);            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   printf("\nCalculation of the hessian matrix. Wait...\n");            savm=oldm;
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");            oldm=newm;
   for (i=1;i<=npar;i++){          } /* end mult */
     printf("%d",i);fflush(stdout);       
     fprintf(ficlog,"%d",i);fflush(ficlog);          s1=s[mw[mi][i]][i];
     hess[i][i]=hessii(p,ftolhess,i,delti);          s2=s[mw[mi+1][i]][i];
     /*printf(" %f ",p[i]);*/          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
     /*printf(" %lf ",hess[i][i]);*/          ipmx +=1;
   }          sw += weight[i];
             ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   for (i=1;i<=npar;i++) {          /*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]);*/
     for (j=1;j<=npar;j++)  {        } /* end of wave */
       if (j>i) {       } /* end of individual */
         printf(".%d%d",i,j);fflush(stdout);    } /* End of if */
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
         hess[i][j]=hessij(p,delti,i,j);    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
         hess[j][i]=hess[i][j];        l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
         /*printf(" %lf ",hess[i][j]);*/    return -l;
       }  }
     }  
   }  /*************** log-likelihood *************/
   printf("\n");  double funcone( double *x)
   fprintf(ficlog,"\n");  {
     /* Same as likeli but slower because of a lot of printf and if */
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");    int i, ii, j, k, mi, d, kk;
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");    double l, ll[NLSTATEMAX], cov[NCOVMAX];
       double **out;
   a=matrix(1,npar,1,npar);    double lli; /* Individual log likelihood */
   y=matrix(1,npar,1,npar);    double llt;
   x=vector(1,npar);    int s1, s2;
   indx=ivector(1,npar);    double bbh, survp;
   for (i=1;i<=npar;i++)    /*extern weight */
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];    /* We are differentiating ll according to initial status */
   ludcmp(a,npar,indx,&pd);    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     /*for(i=1;i<imx;i++)
   for (j=1;j<=npar;j++) {      printf(" %d\n",s[4][i]);
     for (i=1;i<=npar;i++) x[i]=0;    */
     x[j]=1;    cov[1]=1.;
     lubksb(a,npar,indx,x);  
     for (i=1;i<=npar;i++){     for(k=1; k<=nlstate; k++) ll[k]=0.;
       matcov[i][j]=x[i];  
     }    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   }      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       for(mi=1; mi<= wav[i]-1; mi++){
   printf("\n#Hessian matrix#\n");        for (ii=1;ii<=nlstate+ndeath;ii++)
   fprintf(ficlog,"\n#Hessian matrix#\n");          for (j=1;j<=nlstate+ndeath;j++){
   for (i=1;i<=npar;i++) {             oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     for (j=1;j<=npar;j++) {             savm[ii][j]=(ii==j ? 1.0 : 0.0);
       printf("%.3e ",hess[i][j]);          }
       fprintf(ficlog,"%.3e ",hess[i][j]);        for(d=0; d<dh[mi][i]; d++){
     }          newm=savm;
     printf("\n");          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
     fprintf(ficlog,"\n");          for (kk=1; kk<=cptcovage;kk++) {
   }            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
           }
   /* Recompute Inverse */          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   for (i=1;i<=npar;i++)                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];          savm=oldm;
   ludcmp(a,npar,indx,&pd);          oldm=newm;
         } /* end mult */
   /*  printf("\n#Hessian matrix recomputed#\n");       
         s1=s[mw[mi][i]][i];
   for (j=1;j<=npar;j++) {        s2=s[mw[mi+1][i]][i];
     for (i=1;i<=npar;i++) x[i]=0;        bbh=(double)bh[mi][i]/(double)stepm;
     x[j]=1;        /* bias is positive if real duration
     lubksb(a,npar,indx,x);         * is higher than the multiple of stepm and negative otherwise.
     for (i=1;i<=npar;i++){          */
       y[i][j]=x[i];        if( s2 > nlstate && (mle <5) ){  /* Jackson */
       printf("%.3e ",y[i][j]);          lli=log(out[s1][s2] - savm[s1][s2]);
       fprintf(ficlog,"%.3e ",y[i][j]);        } else if  (s2==-2) {
     }          for (j=1,survp=0. ; j<=nlstate; j++)
     printf("\n");            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
     fprintf(ficlog,"\n");          lli= log(survp);
   }        }else if (mle==1){
   */          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
         } else if(mle==2){
   free_matrix(a,1,npar,1,npar);          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 */
   free_matrix(y,1,npar,1,npar);        } else if(mle==3){  /* exponential inter-extrapolation */
   free_vector(x,1,npar);          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 */
   free_ivector(indx,1,npar);        } else if (mle==4){  /* mle=4 no inter-extrapolation */
   free_matrix(hess,1,npar,1,npar);          lli=log(out[s1][s2]); /* Original formula */
         } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
           lli=log(out[s1][s2]); /* Original formula */
 }        } /* End of if */
         ipmx +=1;
 /*************** hessian matrix ****************/        sw += weight[i];
 double hessii( double x[], double delta, int theta, double delti[])        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 {  /*       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]); */
   int i;        if(globpr){
   int l=1, lmax=20;          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
   double k1,k2;   %11.6f %11.6f %11.6f ", \
   double p2[NPARMAX+1];                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
   double res;                  2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
   double delt, delts, nkhi=10.,nkhif=1., khi=1.e-4;          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
   double fx;            llt +=ll[k]*gipmx/gsw;
   int k=0,kmax=10;            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
   double l1;          }
           fprintf(ficresilk," %10.6f\n", -llt);
   fx=func(x);        }
   for (i=1;i<=npar;i++) p2[i]=x[i];      } /* end of wave */
   for(l=0 ; l <=lmax; l++){    } /* end of individual */
     l1=pow(10,l);    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
     delts=delt;    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     for(k=1 ; k <kmax; k=k+1){    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
       delt = delta*(l1*k);    if(globpr==0){ /* First time we count the contributions and weights */
       p2[theta]=x[theta] +delt;      gipmx=ipmx;
       k1=func(p2)-fx;      gsw=sw;
       p2[theta]=x[theta]-delt;    }
       k2=func(p2)-fx;    return -l;
       /*res= (k1-2.0*fx+k2)/delt/delt; */  }
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */  
         
 #ifdef DEBUG  /*************** function likelione ***********/
       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);  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
       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);  {
 #endif    /* This routine should help understanding what is done with
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */       the selection of individuals/waves and
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){       to check the exact contribution to the likelihood.
         k=kmax;       Plotting could be done.
       }     */
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */    int k;
         k=kmax; l=lmax*10.;  
       }    if(*globpri !=0){ /* Just counts and sums, no printings */
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){       strcpy(fileresilk,"ilk");
         delts=delt;      strcat(fileresilk,fileres);
       }      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
     }        printf("Problem with resultfile: %s\n", fileresilk);
   }        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
   delti[theta]=delts;      }
   return res;       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");
         fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 }      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
       for(k=1; k<=nlstate; k++)
 double hessij( double x[], double delti[], int thetai,int thetaj)        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 {      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
   int i;    }
   int l=1, l1, lmax=20;  
   double k1,k2,k3,k4,res,fx;    *fretone=(*funcone)(p);
   double p2[NPARMAX+1];    if(*globpri !=0){
   int k;      fclose(ficresilk);
       fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
   fx=func(x);      fflush(fichtm);
   for (k=1; k<=2; k++) {    }
     for (i=1;i<=npar;i++) p2[i]=x[i];    return;
     p2[thetai]=x[thetai]+delti[thetai]/k;  }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;  
     k1=func(p2)-fx;  
     /*********** Maximum Likelihood Estimation ***************/
     p2[thetai]=x[thetai]+delti[thetai]/k;  
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
     k2=func(p2)-fx;  {
       int i,j, iter;
     p2[thetai]=x[thetai]-delti[thetai]/k;    double **xi;
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    double fret;
     k3=func(p2)-fx;    double fretone; /* Only one call to likelihood */
       /*  char filerespow[FILENAMELENGTH];*/
     p2[thetai]=x[thetai]-delti[thetai]/k;    xi=matrix(1,npar,1,npar);
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    for (i=1;i<=npar;i++)
     k4=func(p2)-fx;      for (j=1;j<=npar;j++)
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */        xi[i][j]=(i==j ? 1.0 : 0.0);
 #ifdef DEBUG    printf("Powell\n");  fprintf(ficlog,"Powell\n");
     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);    strcpy(filerespow,"pow");
     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);    strcat(filerespow,fileres);
 #endif    if((ficrespow=fopen(filerespow,"w"))==NULL) {
   }      printf("Problem with resultfile: %s\n", filerespow);
   return res;      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 }    }
     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 /************** Inverse of matrix **************/    for (i=1;i<=nlstate;i++)
 void ludcmp(double **a, int n, int *indx, double *d)       for(j=1;j<=nlstate+ndeath;j++)
 {         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   int i,imax,j,k;     fprintf(ficrespow,"\n");
   double big,dum,sum,temp;   
   double *vv;     powell(p,xi,npar,ftol,&iter,&fret,func);
    
   vv=vector(1,n);     free_matrix(xi,1,npar,1,npar);
   *d=1.0;     fclose(ficrespow);
   for (i=1;i<=n;i++) {     printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
     big=0.0;     fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
     for (j=1;j<=n;j++)     fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
       if ((temp=fabs(a[i][j])) > big) big=temp;   
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");   }
     vv[i]=1.0/big;   
   }   /**** Computes Hessian and covariance matrix ***/
   for (j=1;j<=n;j++) {   void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
     for (i=1;i<j;i++) {   {
       sum=a[i][j];     double  **a,**y,*x,pd;
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];     double **hess;
       a[i][j]=sum;     int i, j,jk;
     }     int *indx;
     big=0.0;   
     for (i=j;i<=n;i++) {     double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
       sum=a[i][j];     double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
       for (k=1;k<j;k++)     void lubksb(double **a, int npar, int *indx, double b[]) ;
         sum -= a[i][k]*a[k][j];     void ludcmp(double **a, int npar, int *indx, double *d) ;
       a[i][j]=sum;     double gompertz(double p[]);
       if ( (dum=vv[i]*fabs(sum)) >= big) {     hess=matrix(1,npar,1,npar);
         big=dum;   
         imax=i;     printf("\nCalculation of the hessian matrix. Wait...\n");
       }     fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
     }     for (i=1;i<=npar;i++){
     if (j != imax) {       printf("%d",i);fflush(stdout);
       for (k=1;k<=n;k++) {       fprintf(ficlog,"%d",i);fflush(ficlog);
         dum=a[imax][k];      
         a[imax][k]=a[j][k];        hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
         a[j][k]=dum;      
       }       /*  printf(" %f ",p[i]);
       *d = -(*d);           printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
       vv[imax]=vv[j];     }
     }    
     indx[j]=imax;     for (i=1;i<=npar;i++) {
     if (a[j][j] == 0.0) a[j][j]=TINY;       for (j=1;j<=npar;j++)  {
     if (j != n) {         if (j>i) {
       dum=1.0/(a[j][j]);           printf(".%d%d",i,j);fflush(stdout);
       for (i=j+1;i<=n;i++) a[i][j] *= dum;           fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
     }           hess[i][j]=hessij(p,delti,i,j,func,npar);
   }          
   free_vector(vv,1,n);  /* Doesn't work */          hess[j][i]=hess[i][j];    
 ;          /*printf(" %lf ",hess[i][j]);*/
 }         }
       }
 void lubksb(double **a, int n, int *indx, double b[])     }
 {     printf("\n");
   int i,ii=0,ip,j;     fprintf(ficlog,"\n");
   double sum;   
      printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
   for (i=1;i<=n;i++) {     fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
     ip=indx[i];    
     sum=b[ip];     a=matrix(1,npar,1,npar);
     b[ip]=b[i];     y=matrix(1,npar,1,npar);
     if (ii)     x=vector(1,npar);
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];     indx=ivector(1,npar);
     else if (sum) ii=i;     for (i=1;i<=npar;i++)
     b[i]=sum;       for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
   }     ludcmp(a,npar,indx,&pd);
   for (i=n;i>=1;i--) {   
     sum=b[i];     for (j=1;j<=npar;j++) {
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];       for (i=1;i<=npar;i++) x[i]=0;
     b[i]=sum/a[i][i];       x[j]=1;
   }       lubksb(a,npar,indx,x);
 }       for (i=1;i<=npar;i++){
         matcov[i][j]=x[i];
 /************ Frequencies ********************/      }
 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)    }
 {  /* Some frequencies */  
       printf("\n#Hessian matrix#\n");
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;    fprintf(ficlog,"\n#Hessian matrix#\n");
   int first;    for (i=1;i<=npar;i++) {
   double ***freq; /* Frequencies */      for (j=1;j<=npar;j++) {
   double *pp, **prop;        printf("%.3e ",hess[i][j]);
   double pos,posprop, k2, dateintsum=0,k2cpt=0;        fprintf(ficlog,"%.3e ",hess[i][j]);
   FILE *ficresp;      }
   char fileresp[FILENAMELENGTH];      printf("\n");
         fprintf(ficlog,"\n");
   pp=vector(1,nlstate);    }
   prop=matrix(1,nlstate,iagemin,iagemax+3);  
   strcpy(fileresp,"p");    /* Recompute Inverse */
   strcat(fileresp,fileres);    for (i=1;i<=npar;i++)
   if((ficresp=fopen(fileresp,"w"))==NULL) {      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
     printf("Problem with prevalence resultfile: %s\n", fileresp);    ludcmp(a,npar,indx,&pd);
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);  
     exit(0);    /*  printf("\n#Hessian matrix recomputed#\n");
   }  
   freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);    for (j=1;j<=npar;j++) {
   j1=0;      for (i=1;i<=npar;i++) x[i]=0;
         x[j]=1;
   j=cptcoveff;      lubksb(a,npar,indx,x);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}      for (i=1;i<=npar;i++){
         y[i][j]=x[i];
   first=1;        printf("%.3e ",y[i][j]);
         fprintf(ficlog,"%.3e ",y[i][j]);
   for(k1=1; k1<=j;k1++){      }
     for(i1=1; i1<=ncodemax[k1];i1++){      printf("\n");
       j1++;      fprintf(ficlog,"\n");
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    }
         scanf("%d", i);*/    */
       for (i=-1; i<=nlstate+ndeath; i++)    
         for (jk=-1; jk<=nlstate+ndeath; jk++)      free_matrix(a,1,npar,1,npar);
           for(m=iagemin; m <= iagemax+3; m++)    free_matrix(y,1,npar,1,npar);
             freq[i][jk][m]=0;    free_vector(x,1,npar);
     free_ivector(indx,1,npar);
     for (i=1; i<=nlstate; i++)      free_matrix(hess,1,npar,1,npar);
       for(m=iagemin; m <= iagemax+3; m++)  
         prop[i][m]=0;  
         }
       dateintsum=0;  
       k2cpt=0;  /*************** hessian matrix ****************/
       for (i=1; i<=imx; i++) {  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
         bool=1;  {
         if  (cptcovn>0) {    int i;
           for (z1=1; z1<=cptcoveff; z1++)     int l=1, lmax=20;
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     double k1,k2;
               bool=0;    double p2[NPARMAX+1];
         }    double res;
         if (bool==1){    double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
           for(m=firstpass; m<=lastpass; m++){    double fx;
             k2=anint[m][i]+(mint[m][i]/12.);    int k=0,kmax=10;
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/    double l1;
               if(agev[m][i]==0) agev[m][i]=iagemax+1;  
               if(agev[m][i]==1) agev[m][i]=iagemax+2;    fx=func(x);
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];    for (i=1;i<=npar;i++) p2[i]=x[i];
               if (m<lastpass) {    for(l=0 ; l <=lmax; l++){
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];      l1=pow(10,l);
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];      delts=delt;
               }      for(k=1 ; k <kmax; k=k+1){
                       delt = delta*(l1*k);
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {        p2[theta]=x[theta] +delt;
                 dateintsum=dateintsum+k2;        k1=func(p2)-fx;
                 k2cpt++;        p2[theta]=x[theta]-delt;
               }        k2=func(p2)-fx;
               /*}*/        /*res= (k1-2.0*fx+k2)/delt/delt; */
           }        res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
         }       
       }  #ifdef DEBUG
                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);
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/        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);
   #endif
       if  (cptcovn>0) {        /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
         fprintf(ficresp, "\n#********** Variable ");         if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          k=kmax;
         fprintf(ficresp, "**********\n#");        }
       }        else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
       for(i=1; i<=nlstate;i++)           k=kmax; l=lmax*10.;
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);        }
       fprintf(ficresp, "\n");        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
                 delts=delt;
       for(i=iagemin; i <= iagemax+3; i++){        }
         if(i==iagemax+3){      }
           fprintf(ficlog,"Total");    }
         }else{    delti[theta]=delts;
           if(first==1){    return res;
             first=0;   
             printf("See log file for details...\n");  }
           }  
           fprintf(ficlog,"Age %d", i);  double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
         }  {
         for(jk=1; jk <=nlstate ; jk++){    int i;
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)    int l=1, l1, lmax=20;
             pp[jk] += freq[jk][m][i];     double k1,k2,k3,k4,res,fx;
         }    double p2[NPARMAX+1];
         for(jk=1; jk <=nlstate ; jk++){    int k;
           for(m=-1, pos=0; m <=0 ; m++)  
             pos += freq[jk][m][i];    fx=func(x);
           if(pp[jk]>=1.e-10){    for (k=1; k<=2; k++) {
             if(first==1){      for (i=1;i<=npar;i++) p2[i]=x[i];
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);      p2[thetai]=x[thetai]+delti[thetai]/k;
             }      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);      k1=func(p2)-fx;
           }else{   
             if(first==1)      p2[thetai]=x[thetai]+delti[thetai]/k;
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);      k2=func(p2)-fx;
           }   
         }      p2[thetai]=x[thetai]-delti[thetai]/k;
       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
         for(jk=1; jk <=nlstate ; jk++){      k3=func(p2)-fx;
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)   
             pp[jk] += freq[jk][m][i];      p2[thetai]=x[thetai]-delti[thetai]/k;
         }             p2[thetaj]=x[thetaj]-delti[thetaj]/k;
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){      k4=func(p2)-fx;
           pos += pp[jk];      res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
           posprop += prop[jk][i];  #ifdef DEBUG
         }      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);
         for(jk=1; jk <=nlstate ; jk++){      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);
           if(pos>=1.e-5){  #endif
             if(first==1)    }
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);    return res;
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);  }
           }else{  
             if(first==1)  /************** Inverse of matrix **************/
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);  void ludcmp(double **a, int n, int *indx, double *d)
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);  {
           }    int i,imax,j,k;
           if( i <= iagemax){    double big,dum,sum,temp;
             if(pos>=1.e-5){    double *vv;
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);   
               /*probs[i][jk][j1]= pp[jk]/pos;*/    vv=vector(1,n);
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/    *d=1.0;
             }    for (i=1;i<=n;i++) {
             else      big=0.0;
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);      for (j=1;j<=n;j++)
           }        if ((temp=fabs(a[i][j])) > big) big=temp;
         }      if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
               vv[i]=1.0/big;
         for(jk=-1; jk <=nlstate+ndeath; jk++)    }
           for(m=-1; m <=nlstate+ndeath; m++)    for (j=1;j<=n;j++) {
             if(freq[jk][m][i] !=0 ) {      for (i=1;i<j;i++) {
             if(first==1)        sum=a[i][j];
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);        for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);        a[i][j]=sum;
             }      }
         if(i <= iagemax)      big=0.0;
           fprintf(ficresp,"\n");      for (i=j;i<=n;i++) {
         if(first==1)        sum=a[i][j];
           printf("Others in log...\n");        for (k=1;k<j;k++)
         fprintf(ficlog,"\n");          sum -= a[i][k]*a[k][j];
       }        a[i][j]=sum;
     }        if ( (dum=vv[i]*fabs(sum)) >= big) {
   }          big=dum;
   dateintmean=dateintsum/k2cpt;           imax=i;
          }
   fclose(ficresp);      }
   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);      if (j != imax) {
   free_vector(pp,1,nlstate);        for (k=1;k<=n;k++) {
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);          dum=a[imax][k];
   /* End of Freq */          a[imax][k]=a[j][k];
 }          a[j][k]=dum;
         }
 /************ Prevalence ********************/        *d = -(*d);
 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)        vv[imax]=vv[j];
 {        }
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people      indx[j]=imax;
      in each health status at the date of interview (if between dateprev1 and dateprev2).      if (a[j][j] == 0.0) a[j][j]=TINY;
      We still use firstpass and lastpass as another selection.      if (j != n) {
   */        dum=1.0/(a[j][j]);
          for (i=j+1;i<=n;i++) a[i][j] *= dum;
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;      }
   double ***freq; /* Frequencies */    }
   double *pp, **prop;    free_vector(vv,1,n);  /* Doesn't work */
   double pos,posprop;   ;
   double  y2; /* in fractional years */  }
   int iagemin, iagemax;  
   void lubksb(double **a, int n, int *indx, double b[])
   iagemin= (int) agemin;  {
   iagemax= (int) agemax;    int i,ii=0,ip,j;
   /*pp=vector(1,nlstate);*/    double sum;
   prop=matrix(1,nlstate,iagemin,iagemax+3);    
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/    for (i=1;i<=n;i++) {
   j1=0;      ip=indx[i];
         sum=b[ip];
   j=cptcoveff;      b[ip]=b[i];
   if (cptcovn<1) {j=1;ncodemax[1]=1;}      if (ii)
           for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
   for(k1=1; k1<=j;k1++){      else if (sum) ii=i;
     for(i1=1; i1<=ncodemax[k1];i1++){      b[i]=sum;
       j1++;    }
           for (i=n;i>=1;i--) {
       for (i=1; i<=nlstate; i++)        sum=b[i];
         for(m=iagemin; m <= iagemax+3; m++)      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
           prop[i][m]=0.0;      b[i]=sum/a[i][i];
          }
       for (i=1; i<=imx; i++) { /* Each individual */  }
         bool=1;  
         if  (cptcovn>0) {  void pstamp(FILE *fichier)
           for (z1=1; z1<=cptcoveff; z1++)   {
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
               bool=0;  }
         }   
         if (bool==1) {   /************ Frequencies ********************/
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/  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[])
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */  {  /* Some frequencies */
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */   
               if(agev[m][i]==0) agev[m][i]=iagemax+1;    int i, m, jk, k1,i1, j1, bool, z1,z2,j;
               if(agev[m][i]==1) agev[m][i]=iagemax+2;    int first;
               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);     double ***freq; /* Frequencies */
               if (s[m][i]>0 && s[m][i]<=nlstate) {     double *pp, **prop;
                 /*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]]);*/    double pos,posprop, k2, dateintsum=0,k2cpt=0;
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];    char fileresp[FILENAMELENGTH];
                 prop[s[m][i]][iagemax+3] += weight[i];    
               }     pp=vector(1,nlstate);
             }    prop=matrix(1,nlstate,iagemin,iagemax+3);
           } /* end selection of waves */    strcpy(fileresp,"p");
         }    strcat(fileresp,fileres);
       }    if((ficresp=fopen(fileresp,"w"))==NULL) {
       for(i=iagemin; i <= iagemax+3; i++){        printf("Problem with prevalence resultfile: %s\n", fileresp);
               fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {       exit(0);
           posprop += prop[jk][i];     }
         }     freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
     j1=0;
         for(jk=1; jk <=nlstate ; jk++){        
           if( i <=  iagemax){     j=cptcoveff;
             if(posprop>=1.e-5){     if (cptcovn<1) {j=1;ncodemax[1]=1;}
               probs[i][jk][j1]= prop[jk][i]/posprop;  
             }     first=1;
           }   
         }/* end jk */     for(k1=1; k1<=j;k1++){
       }/* end i */       for(i1=1; i1<=ncodemax[k1];i1++){
     } /* end i1 */        j1++;
   } /* end k1 */        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
             scanf("%d", i);*/
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/        for (i=-5; i<=nlstate+ndeath; i++)  
   /*free_vector(pp,1,nlstate);*/          for (jk=-5; jk<=nlstate+ndeath; jk++)  
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);            for(m=iagemin; m <= iagemax+3; m++)
 }  /* End of prevalence */              freq[i][jk][m]=0;
   
 /************* Waves Concatenation ***************/      for (i=1; i<=nlstate; i++)  
         for(m=iagemin; m <= iagemax+3; m++)
 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)          prop[i][m]=0;
 {       
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.        dateintsum=0;
      Death is a valid wave (if date is known).        k2cpt=0;
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i        for (i=1; i<=imx; i++) {
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]          bool=1;
      and mw[mi+1][i]. dh depends on stepm.          if  (cptcovn>0) {
      */            for (z1=1; z1<=cptcoveff; z1++)
               if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
   int i, mi, m;                bool=0;
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;          }
      double sum=0., jmean=0.;*/          if (bool==1){
   int first;            for(m=firstpass; m<=lastpass; m++){
   int j, k=0,jk, ju, jl;              k2=anint[m][i]+(mint[m][i]/12.);
   double sum=0.;              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
   first=0;                if(agev[m][i]==0) agev[m][i]=iagemax+1;
   jmin=1e+5;                if(agev[m][i]==1) agev[m][i]=iagemax+2;
   jmax=-1;                if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
   jmean=0.;                if (m<lastpass) {
   for(i=1; i<=imx; i++){                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
     mi=0;                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
     m=firstpass;                }
     while(s[m][i] <= nlstate){               
       if(s[m][i]>=1)                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
         mw[++mi][i]=m;                  dateintsum=dateintsum+k2;
       if(m >=lastpass)                  k2cpt++;
         break;                }
       else                /*}*/
         m++;            }
     }/* end while */          }
     if (s[m][i] > nlstate){        }
       mi++;     /* Death is another wave */         
       /* if(mi==0)  never been interviewed correctly before death */        /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
          /* Only death is a correct wave */        pstamp(ficresp);
       mw[mi][i]=m;        if  (cptcovn>0) {
     }          fprintf(ficresp, "\n#********** Variable ");
           for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
     wav[i]=mi;          fprintf(ficresp, "**********\n#");
     if(mi==0){        }
       nbwarn++;        for(i=1; i<=nlstate;i++)
       if(first==0){          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
         printf("Warning! None valid information for:%ld line=%d (skipped) and may be others, see log file\n",num[i],i);        fprintf(ficresp, "\n");
         first=1;       
       }        for(i=iagemin; i <= iagemax+3; i++){
       if(first==1){          if(i==iagemax+3){
         fprintf(ficlog,"Warning! None valid information for:%ld line=%d (skipped)\n",num[i],i);            fprintf(ficlog,"Total");
       }          }else{
     } /* end mi==0 */            if(first==1){
   } /* End individuals */              first=0;
               printf("See log file for details...\n");
   for(i=1; i<=imx; i++){            }
     for(mi=1; mi<wav[i];mi++){            fprintf(ficlog,"Age %d", i);
       if (stepm <=0)          }
         dh[mi][i]=1;          for(jk=1; jk <=nlstate ; jk++){
       else{            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */              pp[jk] += freq[jk][m][i];
           if (agedc[i] < 2*AGESUP) {          }
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);           for(jk=1; jk <=nlstate ; jk++){
             if(j==0) j=1;  /* Survives at least one month after exam */            for(m=-1, pos=0; m <=0 ; m++)
             else if(j<0){              pos += freq[jk][m][i];
               nberr++;            if(pp[jk]>=1.e-10){
               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]);              if(first==1){
               j=1; /* Temporary Dangerous patch */              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview.\n  You MUST fix the contradiction between dates.\n",stepm);              }
               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]);              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
               fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview.\n  You MUST fix the contradiction between dates.\n",stepm);            }else{
             }              if(first==1)
             k=k+1;                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             if (j >= jmax) jmax=j;              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             if (j <= jmin) jmin=j;            }
             sum=sum+j;          }
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/  
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/          for(jk=1; jk <=nlstate ; jk++){
           }            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
         }              pp[jk] += freq[jk][m][i];
         else{          }      
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
           /*      printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/            pos += pp[jk];
           k=k+1;            posprop += prop[jk][i];
           if (j >= jmax) jmax=j;          }
           else if (j <= jmin)jmin=j;          for(jk=1; jk <=nlstate ; jk++){
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */            if(pos>=1.e-5){
           /*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]);*/              if(first==1)
           if(j<0){                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             nberr++;              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             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]);            }else{
             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]);              if(first==1)
           }                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
           sum=sum+j;              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
         }            }
         jk= j/stepm;            if( i <= iagemax){
         jl= j -jk*stepm;              if(pos>=1.e-5){
         ju= j -(jk+1)*stepm;                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */                /*probs[i][jk][j1]= pp[jk]/pos;*/
           if(jl==0){                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
             dh[mi][i]=jk;              }
             bh[mi][i]=0;              else
           }else{ /* We want a negative bias in order to only have interpolation ie                fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   * at the price of an extra matrix product in likelihood */            }
             dh[mi][i]=jk+1;          }
             bh[mi][i]=ju;         
           }          for(jk=-1; jk <=nlstate+ndeath; jk++)
         }else{            for(m=-1; m <=nlstate+ndeath; m++)
           if(jl <= -ju){              if(freq[jk][m][i] !=0 ) {
             dh[mi][i]=jk;              if(first==1)
             bh[mi][i]=jl;       /* bias is positive if real duration                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                                  * is higher than the multiple of stepm and negative otherwise.                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                                  */              }
           }          if(i <= iagemax)
           else{            fprintf(ficresp,"\n");
             dh[mi][i]=jk+1;          if(first==1)
             bh[mi][i]=ju;            printf("Others in log...\n");
           }          fprintf(ficlog,"\n");
           if(dh[mi][i]==0){        }
             dh[mi][i]=1; /* At least one step */      }
             bh[mi][i]=ju; /* At least one step */    }
             /*  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);*/    dateintmean=dateintsum/k2cpt;
           }   
         } /* end if mle */    fclose(ficresp);
       }    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
     } /* end wave */    free_vector(pp,1,nlstate);
   }    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
   jmean=sum/k;    /* End of Freq */
   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);  }
   fprintf(ficlog,"Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);  
  }  /************ Prevalence ********************/
   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)
 /*********** Tricode ****************************/  {  
 void tricode(int *Tvar, int **nbcode, int imx)    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 {       in each health status at the date of interview (if between dateprev1 and dateprev2).
          We still use firstpass and lastpass as another selection.
   int Ndum[20],ij=1, k, j, i, maxncov=19;    */
   int cptcode=0;   
   cptcoveff=0;     int i, m, jk, k1, i1, j1, bool, z1,z2,j;
      double ***freq; /* Frequencies */
   for (k=0; k<maxncov; k++) Ndum[k]=0;    double *pp, **prop;
   for (k=1; k<=7; k++) ncodemax[k]=0;    double pos,posprop;
     double  y2; /* in fractional years */
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {    int iagemin, iagemax;
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum   
                                modality*/     iagemin= (int) agemin;
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/    iagemax= (int) agemax;
       Ndum[ij]++; /*store the modality */    /*pp=vector(1,nlstate);*/
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/    prop=matrix(1,nlstate,iagemin,iagemax+3);
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable     /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                                        Tvar[j]. If V=sex and male is 0 and     j1=0;
                                        female is 1, then  cptcode=1.*/   
     }    j=cptcoveff;
     if (cptcovn<1) {j=1;ncodemax[1]=1;}
     for (i=0; i<=cptcode; i++) {   
       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 */    for(k1=1; k1<=j;k1++){
     }      for(i1=1; i1<=ncodemax[k1];i1++){
         j1++;
     ij=1;        
     for (i=1; i<=ncodemax[j]; i++) {        for (i=1; i<=nlstate; i++)  
       for (k=0; k<= maxncov; k++) {          for(m=iagemin; m <= iagemax+3; m++)
         if (Ndum[k] != 0) {            prop[i][m]=0.0;
           nbcode[Tvar[j]][ij]=k;        
           /* 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; */        for (i=1; i<=imx; i++) { /* Each individual */
                     bool=1;
           ij++;          if  (cptcovn>0) {
         }            for (z1=1; z1<=cptcoveff; z1++)
         if (ij > ncodemax[j]) break;               if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
       }                  bool=0;
     }           }
   }            if (bool==1) {
             for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
  for (k=0; k< maxncov; k++) Ndum[k]=0;              y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
               if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
  for (i=1; i<=ncovmodel-2; i++) {                 if(agev[m][i]==0) agev[m][i]=iagemax+1;
    /* Listing of all covariables in staement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/                if(agev[m][i]==1) agev[m][i]=iagemax+2;
    ij=Tvar[i];                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);
    Ndum[ij]++;                if (s[m][i]>0 && s[m][i]<=nlstate) {
  }                  /*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]]);*/
                   prop[s[m][i]][(int)agev[m][i]] += weight[i];
  ij=1;                  prop[s[m][i]][iagemax+3] += weight[i];
  for (i=1; i<= maxncov; i++) {                }
    if((Ndum[i]!=0) && (i<=ncovcol)){              }
      Tvaraff[ij]=i; /*For printing */            } /* end selection of waves */
      ij++;          }
    }        }
  }        for(i=iagemin; i <= iagemax+3; i++){  
           
  cptcoveff=ij-1; /*Number of simple covariates*/          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
 }            posprop += prop[jk][i];
           }
 /*********** Health Expectancies ****************/  
           for(jk=1; jk <=nlstate ; jk++){    
 void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij, int estepm,double delti[],double **matcov )            if( i <=  iagemax){
               if(posprop>=1.e-5){
 {                probs[i][jk][j1]= prop[jk][i]/posprop;
   /* Health expectancies */              }
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;            }
   double age, agelim, hf;          }/* end jk */
   double ***p3mat,***varhe;        }/* end i */
   double **dnewm,**doldm;      } /* end i1 */
   double *xp;    } /* end k1 */
   double **gp, **gm;   
   double ***gradg, ***trgradg;    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
   int theta;    /*free_vector(pp,1,nlstate);*/
     free_matrix(prop,1,nlstate, iagemin,iagemax+3);
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);  }  /* End of prevalence */
   xp=vector(1,npar);  
   dnewm=matrix(1,nlstate*nlstate,1,npar);  /************* Waves Concatenation ***************/
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);  
     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)
   fprintf(ficreseij,"# Health expectancies\n");  {
   fprintf(ficreseij,"# Age");    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
   for(i=1; i<=nlstate;i++)       Death is a valid wave (if date is known).
     for(j=1; j<=nlstate;j++)       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
       fprintf(ficreseij," %1d-%1d (SE)",i,j);       dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
   fprintf(ficreseij,"\n");       and mw[mi+1][i]. dh depends on stepm.
        */
   if(estepm < stepm){  
     printf ("Problem %d lower than %d\n",estepm, stepm);    int i, mi, m;
   }    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
   else  hstepm=estepm;          double sum=0., jmean=0.;*/
   /* We compute the life expectancy from trapezoids spaced every estepm months    int first;
    * This is mainly to measure the difference between two models: for example    int j, k=0,jk, ju, jl;
    * if stepm=24 months pijx are given only every 2 years and by summing them    double sum=0.;
    * we are calculating an estimate of the Life Expectancy assuming a linear     first=0;
    * progression in between and thus overestimating or underestimating according    jmin=1e+5;
    * to the curvature of the survival function. If, for the same date, we     jmax=-1;
    * estimate the model with stepm=1 month, we can keep estepm to 24 months    jmean=0.;
    * to compare the new estimate of Life expectancy with the same linear     for(i=1; i<=imx; i++){
    * hypothesis. A more precise result, taking into account a more precise      mi=0;
    * curvature will be obtained if estepm is as small as stepm. */      m=firstpass;
       while(s[m][i] <= nlstate){
   /* For example we decided to compute the life expectancy with the smallest unit */        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.           mw[++mi][i]=m;
      nhstepm is the number of hstepm from age to agelim         if(m >=lastpass)
      nstepm is the number of stepm from age to agelin.           break;
      Look at hpijx to understand the reason of that which relies in memory size        else
      and note for a fixed period like estepm months */          m++;
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the      }/* end while */
      survival function given by stepm (the optimization length). Unfortunately it      if (s[m][i] > nlstate){
      means that if the survival funtion is printed only each two years of age and if        mi++;     /* Death is another wave */
      you sum them up and add 1 year (area under the trapezoids) you won't get the same         /* if(mi==0)  never been interviewed correctly before death */
      results. So we changed our mind and took the option of the best precision.           /* Only death is a correct wave */
   */        mw[mi][i]=m;
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */       }
   
   agelim=AGESUP;      wav[i]=mi;
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */      if(mi==0){
     /* nhstepm age range expressed in number of stepm */        nbwarn++;
     nstepm=(int) rint((agelim-age)*YEARM/stepm);         if(first==0){
     /* Typically if 20 years nstepm = 20*12/6=40 stepm */           printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
     /* if (stepm >= YEARM) hstepm=1;*/          first=1;
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */        }
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        if(first==1){
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
     gp=matrix(0,nhstepm,1,nlstate*nlstate);        }
     gm=matrix(0,nhstepm,1,nlstate*nlstate);      } /* end mi==0 */
     } /* End individuals */
     /* Computed by stepm unit matrices, product of hstepm matrices, stored  
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */    for(i=1; i<=imx; i++){
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);        for(mi=1; mi<wav[i];mi++){
          if (stepm <=0)
           dh[mi][i]=1;
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */        else{
           if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
     /* Computing Variances of health expectancies */            if (agedc[i] < 2*AGESUP) {
               j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
      for(theta=1; theta <=npar; theta++){              if(j==0) j=1;  /* Survives at least one month after exam */
       for(i=1; i<=npar; i++){               else if(j<0){
         xp[i] = x[i] + (i==theta ?delti[theta]:0);                nberr++;
       }                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]);
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);                  j=1; /* Temporary Dangerous patch */
                   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);
       cptj=0;                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]);
       for(j=1; j<= nlstate; j++){                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);
         for(i=1; i<=nlstate; i++){              }
           cptj=cptj+1;              k=k+1;
           for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){              if (j >= jmax){
             gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;                jmax=j;
           }                ijmax=i;
         }              }
       }              if (j <= jmin){
                      jmin=j;
                      ijmin=i;
       for(i=1; i<=npar; i++)               }
         xp[i] = x[i] - (i==theta ?delti[theta]:0);              sum=sum+j;
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);                /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                     /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
       cptj=0;            }
       for(j=1; j<= nlstate; j++){          }
         for(i=1;i<=nlstate;i++){          else{
           cptj=cptj+1;            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
           for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){  /*        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]); */
   
             gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;            k=k+1;
           }            if (j >= jmax) {
         }              jmax=j;
       }              ijmax=i;
       for(j=1; j<= nlstate*nlstate; j++)            }
         for(h=0; h<=nhstepm-1; h++){            else if (j <= jmin){
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];              jmin=j;
         }              ijmin=i;
      }             }
                /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 /* End theta */            /*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]);*/
             if(j<0){
      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);              nberr++;
               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]);
      for(h=0; h<=nhstepm-1; h++)              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]);
       for(j=1; j<=nlstate*nlstate;j++)            }
         for(theta=1; theta <=npar; theta++)            sum=sum+j;
           trgradg[h][j][theta]=gradg[h][theta][j];          }
                jk= j/stepm;
           jl= j -jk*stepm;
      for(i=1;i<=nlstate*nlstate;i++)          ju= j -(jk+1)*stepm;
       for(j=1;j<=nlstate*nlstate;j++)          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
         varhe[i][j][(int)age] =0.;            if(jl==0){
               dh[mi][i]=jk;
      printf("%d|",(int)age);fflush(stdout);              bh[mi][i]=0;
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);            }else{ /* We want a negative bias in order to only have interpolation ie
      for(h=0;h<=nhstepm-1;h++){                    * at the price of an extra matrix product in likelihood */
       for(k=0;k<=nhstepm-1;k++){              dh[mi][i]=jk+1;
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);              bh[mi][i]=ju;
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);            }
         for(i=1;i<=nlstate*nlstate;i++)          }else{
           for(j=1;j<=nlstate*nlstate;j++)            if(jl <= -ju){
             varhe[i][j][(int)age] += doldm[i][j]*hf*hf;              dh[mi][i]=jk;
       }              bh[mi][i]=jl;       /* bias is positive if real duration
     }                                   * is higher than the multiple of stepm and negative otherwise.
     /* Computing expectancies */                                   */
     for(i=1; i<=nlstate;i++)            }
       for(j=1; j<=nlstate;j++)            else{
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){              dh[mi][i]=jk+1;
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;              bh[mi][i]=ju;
                       }
 /* 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]);*/            if(dh[mi][i]==0){
               dh[mi][i]=1; /* At least one step */
         }              bh[mi][i]=ju; /* At least one step */
               /*  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);*/
     fprintf(ficreseij,"%3.0f",age );            }
     cptj=0;          } /* end if mle */
     for(i=1; i<=nlstate;i++)        }
       for(j=1; j<=nlstate;j++){      } /* end wave */
         cptj++;    }
         fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );    jmean=sum/k;
       }    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);
     fprintf(ficreseij,"\n");    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);
       }
     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);  
     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);  /*********** Tricode ****************************/
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);  void tricode(int *Tvar, int **nbcode, int imx)
     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);  {
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   
   }    int Ndum[20],ij=1, k, j, i, maxncov=19;
   printf("\n");    int cptcode=0;
   fprintf(ficlog,"\n");    cptcoveff=0;
    
   free_vector(xp,1,npar);    for (k=0; k<maxncov; k++) Ndum[k]=0;
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);    for (k=1; k<=7; k++) ncodemax[k]=0;
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);  
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);    for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
 }      for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
                                  modality*/
 /************ Variance ******************/        ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
 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)        Ndum[ij]++; /*store the modality */
 {        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
   /* Variance of health expectancies */        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/                                         Tvar[j]. If V=sex and male is 0 and
   /* double **newm;*/                                         female is 1, then  cptcode=1.*/
   double **dnewm,**doldm;      }
   double **dnewmp,**doldmp;  
   int i, j, nhstepm, hstepm, h, nstepm ;      for (i=0; i<=cptcode; i++) {
   int k, cptcode;        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 */
   double *xp;      }
   double **gp, **gm;  /* for var eij */  
   double ***gradg, ***trgradg; /*for var eij */      ij=1;
   double **gradgp, **trgradgp; /* for var p point j */      for (i=1; i<=ncodemax[j]; i++) {
   double *gpp, *gmp; /* for var p point j */        for (k=0; k<= maxncov; k++) {
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */          if (Ndum[k] != 0) {
   double ***p3mat;            nbcode[Tvar[j]][ij]=k;
   double age,agelim, hf;            /* 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; */
   double ***mobaverage;           
   int theta;            ij++;
   char digit[4];          }
   char digitp[25];          if (ij > ncodemax[j]) break;
         }  
   char fileresprobmorprev[FILENAMELENGTH];      }
     }  
   if(popbased==1){  
     if(mobilav!=0)   for (k=0; k< maxncov; k++) Ndum[k]=0;
       strcpy(digitp,"-populbased-mobilav-");  
     else strcpy(digitp,"-populbased-nomobil-");   for (i=1; i<=ncovmodel-2; i++) {
   }     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
   else      ij=Tvar[i];
     strcpy(digitp,"-stablbased-");     Ndum[ij]++;
    }
   if (mobilav!=0) {  
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);   ij=1;
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){   for (i=1; i<= maxncov; i++) {
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);     if((Ndum[i]!=0) && (i<=ncovcol)){
       printf(" Error in movingaverage mobilav=%d\n",mobilav);       Tvaraff[ij]=i; /*For printing */
     }       ij++;
   }     }
    }
   strcpy(fileresprobmorprev,"prmorprev");    
   sprintf(digit,"%-d",ij);   cptcoveff=ij-1; /*Number of simple covariates*/
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/  }
   strcat(fileresprobmorprev,digit); /* Tvar to be done */  
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */  /*********** Health Expectancies ****************/
   strcat(fileresprobmorprev,fileres);  
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {  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[] )
     printf("Problem with resultfile: %s\n", fileresprobmorprev);  
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);  {
   }    /* Health expectancies, no variances */
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    double age, agelim, hf;
   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);    double ***p3mat;
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);    double eip;
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){  
     fprintf(ficresprobmorprev," p.%-d SE",j);    pstamp(ficreseij);
     for(i=1; i<=nlstate;i++)    fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);    fprintf(ficreseij,"# Age");
   }      for(i=1; i<=nlstate;i++){
   fprintf(ficresprobmorprev,"\n");      for(j=1; j<=nlstate;j++){
   fprintf(ficgp,"\n# Routine varevsij");        fprintf(ficreseij," e%1d%1d ",i,j);
   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");      }
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);      fprintf(ficreseij," e%1d. ",i);
 /*   } */    }
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    fprintf(ficreseij,"\n");
   
   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are the stable prevalence in health states i\n");   
   fprintf(ficresvij,"# Age");    if(estepm < stepm){
   for(i=1; i<=nlstate;i++)      printf ("Problem %d lower than %d\n",estepm, stepm);
     for(j=1; j<=nlstate;j++)    }
       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);    else  hstepm=estepm;  
   fprintf(ficresvij,"\n");    /* We compute the life expectancy from trapezoids spaced every estepm months
      * This is mainly to measure the difference between two models: for example
   xp=vector(1,npar);     * if stepm=24 months pijx are given only every 2 years and by summing them
   dnewm=matrix(1,nlstate,1,npar);     * we are calculating an estimate of the Life Expectancy assuming a linear
   doldm=matrix(1,nlstate,1,nlstate);     * progression in between and thus overestimating or underestimating according
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);     * to the curvature of the survival function. If, for the same date, we
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);     * estimate the model with stepm=1 month, we can keep estepm to 24 months
      * to compare the new estimate of Life expectancy with the same linear
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);     * hypothesis. A more precise result, taking into account a more precise
   gpp=vector(nlstate+1,nlstate+ndeath);     * curvature will be obtained if estepm is as small as stepm. */
   gmp=vector(nlstate+1,nlstate+ndeath);  
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/    /* For example we decided to compute the life expectancy with the smallest unit */
       /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   if(estepm < stepm){       nhstepm is the number of hstepm from age to agelim
     printf ("Problem %d lower than %d\n",estepm, stepm);       nstepm is the number of stepm from age to agelin.
   }       Look at hpijx to understand the reason of that which relies in memory size
   else  hstepm=estepm;          and note for a fixed period like estepm months */
   /* For example we decided to compute the life expectancy with the smallest unit */    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.        survival function given by stepm (the optimization length). Unfortunately it
      nhstepm is the number of hstepm from age to agelim        means that if the survival funtion is printed only each two years of age and if
      nstepm is the number of stepm from age to agelin.        you sum them up and add 1 year (area under the trapezoids) you won't get the same
      Look at hpijx to understand the reason of that which relies in memory size       results. So we changed our mind and took the option of the best precision.
      and note for a fixed period like k years */    */
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
      survival function given by stepm (the optimization length). Unfortunately it  
      means that if the survival funtion is printed every two years of age and if    agelim=AGESUP;
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     /* If stepm=6 months */
      results. So we changed our mind and took the option of the best precision.      /* Computed by stepm unit matrices, product of hstepm matrices, stored
   */         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */      
   agelim = AGESUP;  /* nhstepm age range expressed in number of stepm */
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     /* Typically if 20 years nstepm = 20*12/6=40 stepm */
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */    /* if (stepm >= YEARM) hstepm=1;*/
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     gp=matrix(0,nhstepm,1,nlstate);  
     gm=matrix(0,nhstepm,1,nlstate);    for (age=bage; age<=fage; age ++){
   
   
     for(theta=1; theta <=npar; theta++){      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/     
         xp[i] = x[i] + (i==theta ?delti[theta]:0);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       }     
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        printf("%d|",(int)age);fflush(stdout);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
      
       if (popbased==1) {  
         if(mobilav ==0){      /* Computing expectancies */
           for(i=1; i<=nlstate;i++)      for(i=1; i<=nlstate;i++)
             prlim[i][i]=probs[(int)age][i][ij];        for(j=1; j<=nlstate;j++)
         }else{ /* mobilav */           for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
           for(i=1; i<=nlstate;i++)            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
             prlim[i][i]=mobaverage[(int)age][i][ij];           
         }            /*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]);*/
       }  
             }
       for(j=1; j<= nlstate; j++){     
         for(h=0; h<=nhstepm; h++){      fprintf(ficreseij,"%3.0f",age );
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)      for(i=1; i<=nlstate;i++){
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];        eip=0;
         }        for(j=1; j<=nlstate;j++){
       }          eip +=eij[i][j][(int)age];
       /* This for computing probability of death (h=1 means          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
          computed over hstepm matrices product = hstepm*stepm months)         }
          as a weighted average of prlim.        fprintf(ficreseij,"%9.4f", eip );
       */      }
       for(j=nlstate+1;j<=nlstate+ndeath;j++){      fprintf(ficreseij,"\n");
         for(i=1,gpp[j]=0.; i<= nlstate; i++)     
           gpp[j] += prlim[i][i]*p3mat[i][j][1];    }
       }        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       /* end probability of death */    printf("\n");
     fprintf(ficlog,"\n");
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */   
         xp[i] = x[i] - (i==theta ?delti[theta]:0);  }
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);    
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);  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[] )
    
       if (popbased==1) {  {
         if(mobilav ==0){    /* Covariances of health expectancies eij and of total life expectancies according
           for(i=1; i<=nlstate;i++)     to initial status i, ei. .
             prlim[i][i]=probs[(int)age][i][ij];    */
         }else{ /* mobilav */     int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
           for(i=1; i<=nlstate;i++)    double age, agelim, hf;
             prlim[i][i]=mobaverage[(int)age][i][ij];    double ***p3matp, ***p3matm, ***varhe;
         }    double **dnewm,**doldm;
       }    double *xp, *xm;
     double **gp, **gm;
       for(j=1; j<= nlstate; j++){    double ***gradg, ***trgradg;
         for(h=0; h<=nhstepm; h++){    int theta;
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)  
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];    double eip, vip;
         }  
       }    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
       /* This for computing probability of death (h=1 means    xp=vector(1,npar);
          computed over hstepm matrices product = hstepm*stepm months)     xm=vector(1,npar);
          as a weighted average of prlim.    dnewm=matrix(1,nlstate*nlstate,1,npar);
       */    doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
       for(j=nlstate+1;j<=nlstate+ndeath;j++){   
         for(i=1,gmp[j]=0.; i<= nlstate; i++)    pstamp(ficresstdeij);
          gmp[j] += prlim[i][i]*p3mat[i][j][1];    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
       }        fprintf(ficresstdeij,"# Age");
       /* end probability of death */    for(i=1; i<=nlstate;i++){
       for(j=1; j<=nlstate;j++)
       for(j=1; j<= nlstate; j++) /* vareij */        fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
         for(h=0; h<=nhstepm; h++){      fprintf(ficresstdeij," e%1d. ",i);
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];    }
         }    fprintf(ficresstdeij,"\n");
   
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */    pstamp(ficrescveij);
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
       }    fprintf(ficrescveij,"# Age");
     for(i=1; i<=nlstate;i++)
     } /* End theta */      for(j=1; j<=nlstate;j++){
         cptj= (j-1)*nlstate+i;
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */        for(i2=1; i2<=nlstate;i2++)
           for(j2=1; j2<=nlstate;j2++){
     for(h=0; h<=nhstepm; h++) /* veij */            cptj2= (j2-1)*nlstate+i2;
       for(j=1; j<=nlstate;j++)            if(cptj2 <= cptj)
         for(theta=1; theta <=npar; theta++)              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
           trgradg[h][j][theta]=gradg[h][theta][j];          }
       }
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */    fprintf(ficrescveij,"\n");
       for(theta=1; theta <=npar; theta++)   
         trgradgp[j][theta]=gradgp[theta][j];    if(estepm < stepm){
         printf ("Problem %d lower than %d\n",estepm, stepm);
     }
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    else  hstepm=estepm;  
     for(i=1;i<=nlstate;i++)    /* We compute the life expectancy from trapezoids spaced every estepm months
       for(j=1;j<=nlstate;j++)     * This is mainly to measure the difference between two models: for example
         vareij[i][j][(int)age] =0.;     * if stepm=24 months pijx are given only every 2 years and by summing them
      * we are calculating an estimate of the Life Expectancy assuming a linear
     for(h=0;h<=nhstepm;h++){     * progression in between and thus overestimating or underestimating according
       for(k=0;k<=nhstepm;k++){     * to the curvature of the survival function. If, for the same date, we
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);     * estimate the model with stepm=1 month, we can keep estepm to 24 months
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);     * to compare the new estimate of Life expectancy with the same linear
         for(i=1;i<=nlstate;i++)     * hypothesis. A more precise result, taking into account a more precise
           for(j=1;j<=nlstate;j++)     * curvature will be obtained if estepm is as small as stepm. */
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;  
       }    /* For example we decided to compute the life expectancy with the smallest unit */
     }    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
          nhstepm is the number of hstepm from age to agelim
     /* pptj */       nstepm is the number of stepm from age to agelin.
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);       Look at hpijx to understand the reason of that which relies in memory size
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);       and note for a fixed period like estepm months */
     for(j=nlstate+1;j<=nlstate+ndeath;j++)    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
       for(i=nlstate+1;i<=nlstate+ndeath;i++)       survival function given by stepm (the optimization length). Unfortunately it
         varppt[j][i]=doldmp[j][i];       means that if the survival funtion is printed only each two years of age and if
     /* end ppptj */       you sum them up and add 1 year (area under the trapezoids) you won't get the same
     /*  x centered again */       results. So we changed our mind and took the option of the best precision.
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);      */
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
    
     if (popbased==1) {    /* If stepm=6 months */
       if(mobilav ==0){    /* nhstepm age range expressed in number of stepm */
         for(i=1; i<=nlstate;i++)    agelim=AGESUP;
           prlim[i][i]=probs[(int)age][i][ij];    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
       }else{ /* mobilav */     /* Typically if 20 years nstepm = 20*12/6=40 stepm */
         for(i=1; i<=nlstate;i++)    /* if (stepm >= YEARM) hstepm=1;*/
           prlim[i][i]=mobaverage[(int)age][i][ij];    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       }   
     }    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                  p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     /* This for computing probability of death (h=1 means    gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
        computed over hstepm (estepm) matrices product = hstepm*stepm months)     trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
        as a weighted average of prlim.    gp=matrix(0,nhstepm,1,nlstate*nlstate);
     */    gm=matrix(0,nhstepm,1,nlstate*nlstate);
     for(j=nlstate+1;j<=nlstate+ndeath;j++){  
       for(i=1,gmp[j]=0.;i<= nlstate; i++)     for (age=bage; age<=fage; age ++){
         gmp[j] += prlim[i][i]*p3mat[i][j][1];   
     }          /* Computed by stepm unit matrices, product of hstepm matrices, stored
     /* end probability of death */         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
    
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){  
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));      /* Computing  Variances of health expectancies */
       for(i=1; i<=nlstate;i++){      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);         decrease memory allocation */
       }      for(theta=1; theta <=npar; theta++){
     }         for(i=1; i<=npar; i++){
     fprintf(ficresprobmorprev,"\n");          xp[i] = x[i] + (i==theta ?delti[theta]:0);
           xm[i] = x[i] - (i==theta ?delti[theta]:0);
     fprintf(ficresvij,"%.0f ",age );        }
     for(i=1; i<=nlstate;i++)        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
       for(j=1; j<=nlstate;j++){        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);   
       }        for(j=1; j<= nlstate; j++){
     fprintf(ficresvij,"\n");          for(i=1; i<=nlstate; i++){
     free_matrix(gp,0,nhstepm,1,nlstate);            for(h=0; h<=nhstepm-1; h++){
     free_matrix(gm,0,nhstepm,1,nlstate);              gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);              gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);            }
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          }
   } /* End age */        }
   free_vector(gpp,nlstate+1,nlstate+ndeath);       
   free_vector(gmp,nlstate+1,nlstate+ndeath);        for(ij=1; ij<= nlstate*nlstate; ij++)
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);          for(h=0; h<=nhstepm-1; h++){
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");          }
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */      }/* End theta */
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");     
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */     
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */      for(h=0; h<=nhstepm-1; h++)
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */        for(j=1; j<=nlstate*nlstate;j++)
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));          for(theta=1; theta <=npar; theta++)
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));            trgradg[h][j][theta]=gradg[h][theta][j];
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));     
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));  
   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);       for(ij=1;ij<=nlstate*nlstate;ij++)
   /*  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);        for(ji=1;ji<=nlstate*nlstate;ji++)
 */          varhe[ij][ji][(int)age] =0.;
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */  
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);       printf("%d|",(int)age);fflush(stdout);
        fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
   free_vector(xp,1,npar);       for(h=0;h<=nhstepm-1;h++){
   free_matrix(doldm,1,nlstate,1,nlstate);        for(k=0;k<=nhstepm-1;k++){
   free_matrix(dnewm,1,nlstate,1,npar);          matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);          for(ij=1;ij<=nlstate*nlstate;ij++)
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);            for(ji=1;ji<=nlstate*nlstate;ji++)
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
   fclose(ficresprobmorprev);        }
   fflush(ficgp);      }
   fflush(fichtm);   
 }  /* end varevsij */      /* Computing expectancies */
       hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 /************ Variance of prevlim ******************/      for(i=1; i<=nlstate;i++)
 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)        for(j=1; j<=nlstate;j++)
 {          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   /* Variance of prevalence limit */            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/           
   double **newm;            /* 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]);*/
   double **dnewm,**doldm;  
   int i, j, nhstepm, hstepm;          }
   int k, cptcode;  
   double *xp;      fprintf(ficresstdeij,"%3.0f",age );
   double *gp, *gm;      for(i=1; i<=nlstate;i++){
   double **gradg, **trgradg;        eip=0.;
   double age,agelim;        vip=0.;
   int theta;        for(j=1; j<=nlstate;j++){
              eip += eij[i][j][(int)age];
   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
   fprintf(ficresvpl,"# Age");            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
   for(i=1; i<=nlstate;i++)          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
       fprintf(ficresvpl," %1d-%1d",i,i);        }
   fprintf(ficresvpl,"\n");        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
       }
   xp=vector(1,npar);      fprintf(ficresstdeij,"\n");
   dnewm=matrix(1,nlstate,1,npar);  
   doldm=matrix(1,nlstate,1,nlstate);      fprintf(ficrescveij,"%3.0f",age );
         for(i=1; i<=nlstate;i++)
   hstepm=1*YEARM; /* Every year of age */        for(j=1; j<=nlstate;j++){
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */           cptj= (j-1)*nlstate+i;
   agelim = AGESUP;          for(i2=1; i2<=nlstate;i2++)
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */            for(j2=1; j2<=nlstate;j2++){
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */               cptj2= (j2-1)*nlstate+i2;
     if (stepm >= YEARM) hstepm=1;              if(cptj2 <= cptj)
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
     gradg=matrix(1,npar,1,nlstate);            }
     gp=vector(1,nlstate);        }
     gm=vector(1,nlstate);      fprintf(ficrescveij,"\n");
      
     for(theta=1; theta <=npar; theta++){    }
       for(i=1; i<=npar; i++){ /* Computes gradient */    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
       }    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
       for(i=1;i<=nlstate;i++)    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         gp[i] = prlim[i][i];    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         printf("\n");
       for(i=1; i<=npar; i++) /* Computes gradient */    fprintf(ficlog,"\n");
         xp[i] = x[i] - (i==theta ?delti[theta]:0);  
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    free_vector(xm,1,npar);
       for(i=1;i<=nlstate;i++)    free_vector(xp,1,npar);
         gm[i] = prlim[i][i];    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
     free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
       for(i=1;i<=nlstate;i++)    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];  }
     } /* End theta */  
   /************ Variance ******************/
     trgradg =matrix(1,nlstate,1,npar);  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[])
   {
     for(j=1; j<=nlstate;j++)    /* Variance of health expectancies */
       for(theta=1; theta <=npar; theta++)    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
         trgradg[j][theta]=gradg[theta][j];    /* double **newm;*/
     double **dnewm,**doldm;
     for(i=1;i<=nlstate;i++)    double **dnewmp,**doldmp;
       varpl[i][(int)age] =0.;    int i, j, nhstepm, hstepm, h, nstepm ;
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);    int k, cptcode;
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);    double *xp;
     for(i=1;i<=nlstate;i++)    double **gp, **gm;  /* for var eij */
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */    double ***gradg, ***trgradg; /*for var eij */
     double **gradgp, **trgradgp; /* for var p point j */
     fprintf(ficresvpl,"%.0f ",age );    double *gpp, *gmp; /* for var p point j */
     for(i=1; i<=nlstate;i++)    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));    double ***p3mat;
     fprintf(ficresvpl,"\n");    double age,agelim, hf;
     free_vector(gp,1,nlstate);    double ***mobaverage;
     free_vector(gm,1,nlstate);    int theta;
     free_matrix(gradg,1,npar,1,nlstate);    char digit[4];
     free_matrix(trgradg,1,nlstate,1,npar);    char digitp[25];
   } /* End age */  
     char fileresprobmorprev[FILENAMELENGTH];
   free_vector(xp,1,npar);  
   free_matrix(doldm,1,nlstate,1,npar);    if(popbased==1){
   free_matrix(dnewm,1,nlstate,1,nlstate);      if(mobilav!=0)
         strcpy(digitp,"-populbased-mobilav-");
 }      else strcpy(digitp,"-populbased-nomobil-");
     }
 /************ Variance of one-step probabilities  ******************/    else
 void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax)      strcpy(digitp,"-stablbased-");
 {  
   int i, j=0,  i1, k1, l1, t, tj;    if (mobilav!=0) {
   int k2, l2, j1,  z1;      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   int k=0,l, cptcode;      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
   int first=1, first1;        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   double **dnewm,**doldm;      }
   double *xp;    }
   double *gp, *gm;  
   double **gradg, **trgradg;    strcpy(fileresprobmorprev,"prmorprev");
   double **mu;    sprintf(digit,"%-d",ij);
   double age,agelim, cov[NCOVMAX];    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */    strcat(fileresprobmorprev,digit); /* Tvar to be done */
   int theta;    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
   char fileresprob[FILENAMELENGTH];    strcat(fileresprobmorprev,fileres);
   char fileresprobcov[FILENAMELENGTH];    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
   char fileresprobcor[FILENAMELENGTH];      printf("Problem with resultfile: %s\n", fileresprobmorprev);
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
   double ***varpij;    }
     printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   strcpy(fileresprob,"prob");    
   strcat(fileresprob,fileres);    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {    pstamp(ficresprobmorprev);
     printf("Problem with resultfile: %s\n", fileresprob);    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);
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
   }    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   strcpy(fileresprobcov,"probcov");       fprintf(ficresprobmorprev," p.%-d SE",j);
   strcat(fileresprobcov,fileres);      for(i=1; i<=nlstate;i++)
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
     printf("Problem with resultfile: %s\n", fileresprobcov);    }  
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);    fprintf(ficresprobmorprev,"\n");
   }    fprintf(ficgp,"\n# Routine varevsij");
   strcpy(fileresprobcor,"probcor");     /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   strcat(fileresprobcor,fileres);    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");
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
     printf("Problem with resultfile: %s\n", fileresprobcor);  /*   } */
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   }    pstamp(ficresvij);
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    if(popbased==1)
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    else
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    fprintf(ficresvij,"# Age");
       for(i=1; i<=nlstate;i++)
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");      for(j=1; j<=nlstate;j++)
   fprintf(ficresprob,"# Age");        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");    fprintf(ficresvij,"\n");
   fprintf(ficresprobcov,"# Age");  
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");    xp=vector(1,npar);
   fprintf(ficresprobcov,"# Age");    dnewm=matrix(1,nlstate,1,npar);
     doldm=matrix(1,nlstate,1,nlstate);
     dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
   for(i=1; i<=nlstate;i++)    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
     for(j=1; j<=(nlstate+ndeath);j++){  
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
       fprintf(ficresprobcov," p%1d-%1d ",i,j);    gpp=vector(nlstate+1,nlstate+ndeath);
       fprintf(ficresprobcor," p%1d-%1d ",i,j);    gmp=vector(nlstate+1,nlstate+ndeath);
     }      trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
  /* fprintf(ficresprob,"\n");   
   fprintf(ficresprobcov,"\n");    if(estepm < stepm){
   fprintf(ficresprobcor,"\n");      printf ("Problem %d lower than %d\n",estepm, stepm);
  */    }
  xp=vector(1,npar);    else  hstepm=estepm;  
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    /* For example we decided to compute the life expectancy with the smallest unit */
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);       nhstepm is the number of hstepm from age to agelim
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);       nstepm is the number of stepm from age to agelin.
   first=1;       Look at hpijx to understand the reason of that which relies in memory size
   fprintf(ficgp,"\n# Routine varprob");       and note for a fixed period like k years */
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   fprintf(fichtm,"\n");       survival function given by stepm (the optimization length). Unfortunately it
        means that if the survival funtion is printed every two years of age and if
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Computing matrix of variance-covariance of step probabilities</a></h4></li>\n",optionfilehtmcov);       you sum them up and add 1 year (area under the trapezoids) you won't get the same
   fprintf(fichtmcov,"\n<h4>Computing matrix of variance-covariance of step probabilities</h4>\n\       results. So we changed our mind and took the option of the best precision.
   file %s<br>\n",optionfilehtmcov);    */
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
 and drawn. It helps understanding how is the covariance between two incidences.\    agelim = AGESUP;
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
   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. \      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 standard deviations wide on each axis. <br>\      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\      gp=matrix(0,nhstepm,1,nlstate);
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\      gm=matrix(0,nhstepm,1,nlstate);
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");  
   
   cov[1]=1;      for(theta=1; theta <=npar; theta++){
   tj=cptcoveff;        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}          xp[i] = x[i] + (i==theta ?delti[theta]:0);
   j1=0;        }
   for(t=1; t<=tj;t++){        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
     for(i1=1; i1<=ncodemax[t];i1++){         prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
       j1++;  
       if  (cptcovn>0) {        if (popbased==1) {
         fprintf(ficresprob, "\n#********** Variable ");           if(mobilav ==0){
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);            for(i=1; i<=nlstate;i++)
         fprintf(ficresprob, "**********\n#\n");              prlim[i][i]=probs[(int)age][i][ij];
         fprintf(ficresprobcov, "\n#********** Variable ");           }else{ /* mobilav */
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);            for(i=1; i<=nlstate;i++)
         fprintf(ficresprobcov, "**********\n#\n");              prlim[i][i]=mobaverage[(int)age][i][ij];
                   }
         fprintf(ficgp, "\n#********** Variable ");         }
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);   
         fprintf(ficgp, "**********\n#\n");        for(j=1; j<= nlstate; j++){
                   for(h=0; h<=nhstepm; h++){
                     for(i=1, gp[h][j]=0.;i<=nlstate;i++)
         fprintf(fichtm, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");               gp[h][j] += prlim[i][i]*p3mat[i][j][h];
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          }
         fprintf(fichtm, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");        }
                 /* This for computing probability of death (h=1 means
         fprintf(ficresprobcor, "\n#********** Variable ");               computed over hstepm matrices product = hstepm*stepm months)
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);           as a weighted average of prlim.
         fprintf(ficresprobcor, "**********\n#");            */
       }        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                 for(i=1,gpp[j]=0.; i<= nlstate; i++)
       for (age=bage; age<=fage; age ++){             gpp[j] += prlim[i][i]*p3mat[i][j][1];
         cov[2]=age;        }    
         for (k=1; k<=cptcovn;k++) {        /* end probability of death */
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];  
         }        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         for (k=1; k<=cptcovprod;k++)        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
            
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));        if (popbased==1) {
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);          if(mobilav ==0){
         gp=vector(1,(nlstate)*(nlstate+ndeath));            for(i=1; i<=nlstate;i++)
         gm=vector(1,(nlstate)*(nlstate+ndeath));              prlim[i][i]=probs[(int)age][i][ij];
               }else{ /* mobilav */
         for(theta=1; theta <=npar; theta++){            for(i=1; i<=nlstate;i++)
           for(i=1; i<=npar; i++)              prlim[i][i]=mobaverage[(int)age][i][ij];
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);          }
                   }
           pmij(pmmij,cov,ncovmodel,xp,nlstate);  
                   for(j=1; j<= nlstate; j++){
           k=0;          for(h=0; h<=nhstepm; h++){
           for(i=1; i<= (nlstate); i++){            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
             for(j=1; j<=(nlstate+ndeath);j++){              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
               k=k+1;          }
               gp[k]=pmmij[i][j];        }
             }        /* This for computing probability of death (h=1 means
           }           computed over hstepm matrices product = hstepm*stepm months)
                      as a weighted average of prlim.
           for(i=1; i<=npar; i++)        */
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);        for(j=nlstate+1;j<=nlstate+ndeath;j++){
               for(i=1,gmp[j]=0.; i<= nlstate; i++)
           pmij(pmmij,cov,ncovmodel,xp,nlstate);           gmp[j] += prlim[i][i]*p3mat[i][j][1];
           k=0;        }    
           for(i=1; i<=(nlstate); i++){        /* end probability of death */
             for(j=1; j<=(nlstate+ndeath);j++){  
               k=k+1;        for(j=1; j<= nlstate; j++) /* vareij */
               gm[k]=pmmij[i][j];          for(h=0; h<=nhstepm; h++){
             }            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
           }          }
        
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)         for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];            gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
         }        }
   
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)      } /* End theta */
           for(theta=1; theta <=npar; theta++)  
             trgradg[j][theta]=gradg[theta][j];      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
           
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);       for(h=0; h<=nhstepm; h++) /* veij */
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);        for(j=1; j<=nlstate;j++)
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));          for(theta=1; theta <=npar; theta++)
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));            trgradg[h][j][theta]=gradg[h][theta][j];
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);  
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
         for(theta=1; theta <=npar; theta++)
         pmij(pmmij,cov,ncovmodel,x,nlstate);          trgradgp[j][theta]=gradgp[theta][j];
            
         k=0;  
         for(i=1; i<=(nlstate); i++){      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
           for(j=1; j<=(nlstate+ndeath);j++){      for(i=1;i<=nlstate;i++)
             k=k+1;        for(j=1;j<=nlstate;j++)
             mu[k][(int) age]=pmmij[i][j];          vareij[i][j][(int)age] =0.;
           }  
         }      for(h=0;h<=nhstepm;h++){
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)        for(k=0;k<=nhstepm;k++){
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
             varpij[i][j][(int)age] = doldm[i][j];          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
           for(i=1;i<=nlstate;i++)
         /*printf("\n%d ",(int)age);            for(j=1;j<=nlstate;j++)
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){              vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));        }
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));      }
           }*/   
       /* pptj */
         fprintf(ficresprob,"\n%d ",(int)age);      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
         fprintf(ficresprobcov,"\n%d ",(int)age);      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
         fprintf(ficresprobcor,"\n%d ",(int)age);      for(j=nlstate+1;j<=nlstate+ndeath;j++)
         for(i=nlstate+1;i<=nlstate+ndeath;i++)
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)          varppt[j][i]=doldmp[j][i];
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));      /* end ppptj */
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){      /*  x centered again */
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
         }   
         i=0;      if (popbased==1) {
         for (k=1; k<=(nlstate);k++){        if(mobilav ==0){
           for (l=1; l<=(nlstate+ndeath);l++){           for(i=1; i<=nlstate;i++)
             i=i++;            prlim[i][i]=probs[(int)age][i][ij];
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);        }else{ /* mobilav */
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);          for(i=1; i<=nlstate;i++)
             for (j=1; j<=i;j++){            prlim[i][i]=mobaverage[(int)age][i][ij];
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);        }
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));      }
             }               
           }      /* This for computing probability of death (h=1 means
         }/* end of loop for state */         computed over hstepm (estepm) matrices product = hstepm*stepm months)
       } /* end of loop for age */         as a weighted average of prlim.
       */
       /* Confidence intervalle of pij  */      for(j=nlstate+1;j<=nlstate+ndeath;j++){
       /*        for(i=1,gmp[j]=0.;i<= nlstate; i++)
         fprintf(ficgp,"\nset noparametric;unset label");          gmp[j] += prlim[i][i]*p3mat[i][j][1];
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");      }    
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");      /* end probability of death */
         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);  
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
       */        for(i=1; i<=nlstate;i++){
           fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/        }
       first1=1;      }
       for (k2=1; k2<=(nlstate);k2++){      fprintf(ficresprobmorprev,"\n");
         for (l2=1; l2<=(nlstate+ndeath);l2++){   
           if(l2==k2) continue;      fprintf(ficresvij,"%.0f ",age );
           j=(k2-1)*(nlstate+ndeath)+l2;      for(i=1; i<=nlstate;i++)
           for (k1=1; k1<=(nlstate);k1++){        for(j=1; j<=nlstate;j++){
             for (l1=1; l1<=(nlstate+ndeath);l1++){           fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
               if(l1==k1) continue;        }
               i=(k1-1)*(nlstate+ndeath)+l1;      fprintf(ficresvij,"\n");
               if(i<=j) continue;      free_matrix(gp,0,nhstepm,1,nlstate);
               for (age=bage; age<=fage; age ++){       free_matrix(gm,0,nhstepm,1,nlstate);
                 if ((int)age %5==0){      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;    } /* End age */
                   mu1=mu[i][(int) age]/stepm*YEARM ;    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   mu2=mu[j][(int) age]/stepm*YEARM;    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   c12=cv12/sqrt(v1*v2);    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   /* Computing eigen value of matrix of covariance */    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   /* Eigen vectors */    fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));  /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   /*v21=sqrt(1.-v11*v11); *//* error */  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   v21=(lc1-v1)/cv12*v11;  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   v12=-v21;    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
                   v22=v11;    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
                   tnalp=v21/v11;    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
                   if(first1==1){    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                     first1=0;    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);
                     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);    /*  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);
                   }  */
                   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);  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   /*printf(fignu*/    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */  
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */    free_vector(xp,1,npar);
                   if(first==1){    free_matrix(doldm,1,nlstate,1,nlstate);
                     first=0;    free_matrix(dnewm,1,nlstate,1,npar);
                     fprintf(ficgp,"\nset parametric;unset label");    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                     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);    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\    fclose(ficresprobmorprev);
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\    fflush(ficgp);
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\    fflush(fichtm);
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);  }  /* end varevsij */
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);  
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);  /************ Variance of prevlim ******************/
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);  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[])
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);  {
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);    /* Variance of prevalence limit */
                     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",\    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\    double **newm;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    double **dnewm,**doldm;
                   }else{    int i, j, nhstepm, hstepm;
                     first=0;    int k, cptcode;
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);    double *xp;
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);    double *gp, *gm;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);    double **gradg, **trgradg;
                     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",\    double age,agelim;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\    int theta;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));   
                   }/* if first */    pstamp(ficresvpl);
                 } /* age mod 5 */    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
               } /* end loop age */    fprintf(ficresvpl,"# Age");
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    for(i=1; i<=nlstate;i++)
               first=1;        fprintf(ficresvpl," %1d-%1d",i,i);
             } /*l12 */    fprintf(ficresvpl,"\n");
           } /* k12 */  
         } /*l1 */    xp=vector(1,npar);
       }/* k1 */    dnewm=matrix(1,nlstate,1,npar);
     } /* loop covariates */    doldm=matrix(1,nlstate,1,nlstate);
   }   
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);    hstepm=1*YEARM; /* Every year of age */
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
   free_vector(xp,1,npar);    agelim = AGESUP;
   fclose(ficresprob);    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
   fclose(ficresprobcov);      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
   fclose(ficresprobcor);      if (stepm >= YEARM) hstepm=1;
   fflush(ficgp);      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
   fflush(fichtmcov);      gradg=matrix(1,npar,1,nlstate);
 }      gp=vector(1,nlstate);
       gm=vector(1,nlstate);
   
 /******************* Printing html file ***********/      for(theta=1; theta <=npar; theta++){
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \        for(i=1; i<=npar; i++){ /* Computes gradient */
                   int lastpass, int stepm, int weightopt, char model[],\          xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\        }
                   int popforecast, int estepm ,\        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   double jprev1, double mprev1,double anprev1, \        for(i=1;i<=nlstate;i++)
                   double jprev2, double mprev2,double anprev2){          gp[i] = prlim[i][i];
   int jj1, k1, i1, cpt;     
   /*char optionfilehtm[FILENAMELENGTH];*/        for(i=1; i<=npar; i++) /* Computes gradient */
 /*   if((fichtm=fopen(optionfilehtm,"a"))==NULL)    { */          xp[i] = x[i] - (i==theta ?delti[theta]:0);
 /*     printf("Problem with %s \n",optionfilehtm), exit(0); */        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 /*     fprintf(ficlog,"Problem with %s \n",optionfilehtm), exit(0); */        for(i=1;i<=nlstate;i++)
 /*   } */          gm[i] = prlim[i][i];
   
    fprintf(fichtm,"<ul><li><h4>Result files (first order: no variance)</h4>\n \        for(i=1;i<=nlstate;i++)
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n \          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n \      } /* End theta */
  - Stable prevalence in each health state: <a href=\"%s\">%s</a> <br>\n \  
  - Life expectancies by age and initial health status (estepm=%2d months): \      trgradg =matrix(1,nlstate,1,npar);
    <a href=\"%s\">%s</a> <br>\n</li>", \  
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"),\      for(j=1; j<=nlstate;j++)
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"),\        for(theta=1; theta <=npar; theta++)
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"),\          trgradg[j][theta]=gradg[theta][j];
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));  
       for(i=1;i<=nlstate;i++)
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");        varpl[i][(int)age] =0.;
       matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
  m=cptcoveff;      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}      for(i=1;i<=nlstate;i++)
         varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
  jj1=0;  
  for(k1=1; k1<=m;k1++){      fprintf(ficresvpl,"%.0f ",age );
    for(i1=1; i1<=ncodemax[k1];i1++){      for(i=1; i<=nlstate;i++)
      jj1++;        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
      if (cptcovn > 0) {      fprintf(ficresvpl,"\n");
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");      free_vector(gp,1,nlstate);
        for (cpt=1; cpt<=cptcoveff;cpt++)       free_vector(gm,1,nlstate);
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);      free_matrix(gradg,1,npar,1,nlstate);
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");      free_matrix(trgradg,1,nlstate,1,npar);
      }    } /* End age */
      /* Pij */  
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: %s%d1.png<br> \    free_vector(xp,1,npar);
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);         free_matrix(doldm,1,nlstate,1,npar);
      /* Quasi-incidences */    free_matrix(dnewm,1,nlstate,1,nlstate);
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\  
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: %s%d2.png<br> \  }
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);   
        /* Stable prevalence in each health state */  /************ Variance of one-step probabilities  ******************/
        for(cpt=1; cpt<nlstate;cpt++){  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[])
          fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br> \  {
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);    int i, j=0,  i1, k1, l1, t, tj;
        }    int k2, l2, j1,  z1;
      for(cpt=1; cpt<=nlstate;cpt++) {    int k=0,l, cptcode;
         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): %s%d%d.png <br> \    int first=1, first1;
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
      }    double **dnewm,**doldm;
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \    double *xp;
 health expectancies in states (1) and (2): %s%d.png<br>\    double *gp, *gm;
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);    double **gradg, **trgradg;
    } /* end i1 */    double **mu;
  }/* End k1 */    double age,agelim, cov[NCOVMAX];
  fprintf(fichtm,"</ul>");    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
     int theta;
     char fileresprob[FILENAMELENGTH];
  fprintf(fichtm,"\n<br><li><h4> Result files (second order: variances)</h4>\n\    char fileresprobcov[FILENAMELENGTH];
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n\    char fileresprobcor[FILENAMELENGTH];
  - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n\  
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n\    double ***varpij;
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n\  
  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"%s\">%s</a><br>\n\    strcpy(fileresprob,"prob");
  - Health expectancies with their variances (no covariance): <a href=\"%s\">%s</a> <br>\n\    strcat(fileresprob,fileres);
  - Standard deviation of stable prevalences: <a href=\"%s\">%s</a> <br>\n",\    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
          rfileres,rfileres,\      printf("Problem with resultfile: %s\n", fileresprob);
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"),\      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"),\    }
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"),\    strcpy(fileresprobcov,"probcov");
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"),\    strcat(fileresprobcov,fileres);
          subdirf2(fileres,"t"),subdirf2(fileres,"t"),\    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));      printf("Problem with resultfile: %s\n", fileresprobcov);
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 /*  if(popforecast==1) fprintf(fichtm,"\n */    }
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */    strcpy(fileresprobcor,"probcor");
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */    strcat(fileresprobcor,fileres);
 /*      <br>",fileres,fileres,fileres,fileres); */    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 /*  else  */      printf("Problem with resultfile: %s\n", fileresprobcor);
 /*    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); */      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");    }
     printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
  m=cptcoveff;    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
     fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
  jj1=0;    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
  for(k1=1; k1<=m;k1++){    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
    for(i1=1; i1<=ncodemax[k1];i1++){    pstamp(ficresprob);
      jj1++;    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
      if (cptcovn > 0) {    fprintf(ficresprob,"# Age");
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");    pstamp(ficresprobcov);
        for (cpt=1; cpt<=cptcoveff;cpt++)     fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    fprintf(ficresprobcov,"# Age");
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");    pstamp(ficresprobcor);
      }    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
      for(cpt=1; cpt<=nlstate;cpt++) {    fprintf(ficresprobcor,"# Age");
        fprintf(fichtm,"<br>- Observed and period prevalence (with confident\  
 interval) in state (%d): %s%d%d.png <br>\  
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);      for(i=1; i<=nlstate;i++)
      }      for(j=1; j<=(nlstate+ndeath);j++){
    } /* end i1 */        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
  }/* End k1 */        fprintf(ficresprobcov," p%1d-%1d ",i,j);
  fprintf(fichtm,"</ul>");        fprintf(ficresprobcor," p%1d-%1d ",i,j);
  fflush(fichtm);      }  
 }   /* fprintf(ficresprob,"\n");
     fprintf(ficresprobcov,"\n");
 /******************* Gnuplot file **************/    fprintf(ficresprobcor,"\n");
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){   */
    xp=vector(1,npar);
   char dirfileres[132],optfileres[132];    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
   int ng;    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 /*     printf("Problem with file %s",optionfilegnuplot); */    first=1;
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */    fprintf(ficgp,"\n# Routine varprob");
 /*   } */    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
     fprintf(fichtm,"\n");
   /*#ifdef windows */  
   fprintf(ficgp,"cd \"%s\" \n",pathc);    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
     /*#endif */    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
   m=pow(2,cptcoveff);    file %s<br>\n",optionfilehtmcov);
     fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
   strcpy(dirfileres,optionfilefiname);  and drawn. It helps understanding how is the covariance between two incidences.\
   strcpy(optfileres,"vpl");   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
  /* 1eme*/    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. \
   for (cpt=1; cpt<= nlstate ; cpt ++) {  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
    for (k1=1; k1<= m ; k1 ++) {  would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);  standard deviations wide on each axis. <br>\
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
      fprintf(ficgp,"set xlabel \"Age\" \n\   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 set ylabel \"Probability\" \n\  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 set ter png small\n\  
 set size 0.65,0.65\n\    cov[1]=1;
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);    tj=cptcoveff;
     if (cptcovn<1) {tj=1;ncodemax[1]=1;}
      for (i=1; i<= nlstate ; i ++) {    j1=0;
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");    for(t=1; t<=tj;t++){
        else fprintf(ficgp," \%%*lf (\%%*lf)");      for(i1=1; i1<=ncodemax[t];i1++){
      }        j1++;
      fprintf(ficgp,"\" t\"Stable prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);        if  (cptcovn>0) {
      for (i=1; i<= nlstate ; i ++) {          fprintf(ficresprob, "\n#********** Variable ");
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        else fprintf(ficgp," \%%*lf (\%%*lf)");          fprintf(ficresprob, "**********\n#\n");
      }           fprintf(ficresprobcov, "\n#********** Variable ");
      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);           for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
      for (i=1; i<= nlstate ; i ++) {          fprintf(ficresprobcov, "**********\n#\n");
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");         
        else fprintf(ficgp," \%%*lf (\%%*lf)");          fprintf(ficgp, "\n#********** Variable ");
      }            for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
      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));          fprintf(ficgp, "**********\n#\n");
    }         
   }         
   /*2 eme*/          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
             for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
   for (k1=1; k1<= m ; k1 ++) {           fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);         
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);          fprintf(ficresprobcor, "\n#********** Variable ");    
               for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
     for (i=1; i<= nlstate+1 ; i ++) {          fprintf(ficresprobcor, "**********\n#");    
       k=2*i;        }
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);       
       for (j=1; j<= nlstate+1 ; j ++) {        for (age=bage; age<=fage; age ++){
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");          cov[2]=age;
         else fprintf(ficgp," \%%*lf (\%%*lf)");          for (k=1; k<=cptcovn;k++) {
       }               cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");          }
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);          for (k=1; k<=cptcovprod;k++)
       for (j=1; j<= nlstate+1 ; j ++) {            cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");         
         else fprintf(ficgp," \%%*lf (\%%*lf)");          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
       }             trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
       fprintf(ficgp,"\" t\"\" w l 0,");          gp=vector(1,(nlstate)*(nlstate+ndeath));
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);          gm=vector(1,(nlstate)*(nlstate+ndeath));
       for (j=1; j<= nlstate+1 ; j ++) {     
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");          for(theta=1; theta <=npar; theta++){
         else fprintf(ficgp," \%%*lf (\%%*lf)");            for(i=1; i<=npar; i++)
       }                 xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");           
       else fprintf(ficgp,"\" t\"\" w l 0,");            pmij(pmmij,cov,ncovmodel,xp,nlstate);
     }           
   }            k=0;
               for(i=1; i<= (nlstate); i++){
   /*3eme*/              for(j=1; j<=(nlstate+ndeath);j++){
                   k=k+1;
   for (k1=1; k1<= m ; k1 ++) {                 gp[k]=pmmij[i][j];
     for (cpt=1; cpt<= nlstate ; cpt ++) {              }
       k=2+nlstate*(2*cpt-2);            }
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);           
       fprintf(ficgp,"set ter png small\n\            for(i=1; i<=npar; i++)
 set size 0.65,0.65\n\              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 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);     
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);            pmij(pmmij,cov,ncovmodel,xp,nlstate);
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");            k=0;
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);            for(i=1; i<=(nlstate); i++){
         fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);              for(j=1; j<=(nlstate+ndeath);j++){
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");                k=k+1;
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);                gm[k]=pmmij[i][j];
                       }
       */            }
       for (i=1; i< nlstate ; i ++) {       
         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);            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
                       gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
       }           }
     }  
   }          for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
               for(theta=1; theta <=npar; theta++)
   /* CV preval stable (period) */              trgradg[j][theta]=gradg[theta][j];
   for (k1=1; k1<= m ; k1 ++) {          
     for (cpt=1; cpt<=nlstate ; cpt ++) {          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
       k=3;          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 set ter png small\nset size 0.65,0.65\n\          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 unset log y\n\          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);  
                 pmij(pmmij,cov,ncovmodel,x,nlstate);
       for (i=1; i< nlstate ; i ++)         
         fprintf(ficgp,"+$%d",k+i+1);          k=0;
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);          for(i=1; i<=(nlstate); i++){
                   for(j=1; j<=(nlstate+ndeath);j++){
       l=3+(nlstate+ndeath)*cpt;              k=k+1;
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);              mu[k][(int) age]=pmmij[i][j];
       for (i=1; i< nlstate ; i ++) {            }
         l=3+(nlstate+ndeath)*cpt;          }
         fprintf(ficgp,"+$%d",l+i+1);          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
       }            for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);                 varpij[i][j][(int)age] = doldm[i][j];
     }   
   }            /*printf("\n%d ",(int)age);
               for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
   /* proba elementaires */            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
   for(i=1,jk=1; i <=nlstate; i++){            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
     for(k=1; k <=(nlstate+ndeath); k++){            }*/
       if (k != i) {  
         for(j=1; j <=ncovmodel; j++){          fprintf(ficresprob,"\n%d ",(int)age);
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);          fprintf(ficresprobcov,"\n%d ",(int)age);
           jk++;           fprintf(ficresprobcor,"\n%d ",(int)age);
           fprintf(ficgp,"\n");  
         }          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
       }            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
     }          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
    }            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
             fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/          }
      for(jk=1; jk <=m; jk++) {          i=0;
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);           for (k=1; k<=(nlstate);k++){
        if (ng==2)            for (l=1; l<=(nlstate+ndeath);l++){
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");              i=i++;
        else              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
          fprintf(ficgp,"\nset title \"Probability\"\n");              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);              for (j=1; j<=i;j++){
        i=1;                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
        for(k2=1; k2<=nlstate; k2++) {                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
          k3=i;              }
          for(k=1; k<=(nlstate+ndeath); k++) {            }
            if (k != k2){          }/* end of loop for state */
              if(ng==2)        } /* end of loop for age */
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);  
              else        /* Confidence intervalle of pij  */
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);        /*
              ij=1;          fprintf(ficgp,"\nset noparametric;unset label");
              for(j=3; j <=ncovmodel; j++) {          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);          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);
                  ij++;          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                }          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                else          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);        */
              }  
              fprintf(ficgp,")/(1");        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                      first1=1;
              for(k1=1; k1 <=nlstate; k1++){           for (k2=1; k2<=(nlstate);k2++){
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);          for (l2=1; l2<=(nlstate+ndeath);l2++){
                ij=1;            if(l2==k2) continue;
                for(j=3; j <=ncovmodel; j++){            j=(k2-1)*(nlstate+ndeath)+l2;
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {            for (k1=1; k1<=(nlstate);k1++){
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);              for (l1=1; l1<=(nlstate+ndeath);l1++){
                    ij++;                if(l1==k1) continue;
                  }                i=(k1-1)*(nlstate+ndeath)+l1;
                  else                if(i<=j) continue;
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);                for (age=bage; age<=fage; age ++){
                }                  if ((int)age %5==0){
                fprintf(ficgp,")");                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
              }                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");                    mu1=mu[i][(int) age]/stepm*YEARM ;
              i=i+ncovmodel;                    mu2=mu[j][(int) age]/stepm*YEARM;
            }                    c12=cv12/sqrt(v1*v2);
          } /* end k */                    /* Computing eigen value of matrix of covariance */
        } /* end k2 */                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
      } /* end jk */                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
    } /* end ng */                    /* Eigen vectors */
    fflush(ficgp);                     v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 }  /* end gnuplot */                    /*v21=sqrt(1.-v11*v11); *//* error */
                     v21=(lc1-v1)/cv12*v11;
                     v12=-v21;
 /*************** Moving average **************/                    v22=v11;
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){                    tnalp=v21/v11;
                     if(first1==1){
   int i, cpt, cptcod;                      first1=0;
   int modcovmax =1;                      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);
   int mobilavrange, mob;                    }
   double age;                    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);
                     /*printf(fignu*/
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose                     /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                            a covariate has 2 modalities */                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */                    if(first==1){
                       first=0;
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){                      fprintf(ficgp,"\nset parametric;unset label");
     if(mobilav==1) mobilavrange=5; /* default */                      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);
     else mobilavrange=mobilav;                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
     for (age=bage; age<=fage; age++)                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
       for (i=1; i<=nlstate;i++)   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
         for (cptcod=1;cptcod<=modcovmax;cptcod++)  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
     /* We keep the original values on the extreme ages bage, fage and for                               subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
        we use a 5 terms etc. until the borders are no more concerned.                       fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
     */                       fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
     for (mob=3;mob <=mobilavrange;mob=mob+2){                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
         for (i=1; i<=nlstate;i++){                      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",\
           for (cptcod=1;cptcod<=modcovmax;cptcod++){                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
               for (cpt=1;cpt<=(mob-1)/2;cpt++){                    }else{
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];                      first=0;
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
               }                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
           }                      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",\
         }                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
       }/* end age */                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
     }/* end mob */                    }/* if first */
   }else return -1;                  } /* age mod 5 */
   return 0;                } /* end loop age */
 }/* End movingaverage */                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                 first=1;
               } /*l12 */
 /************** Forecasting ******************/            } /* k12 */
 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){          } /*l1 */
   /* proj1, year, month, day of starting projection         }/* k1 */
      agemin, agemax range of age      } /* loop covariates */
      dateprev1 dateprev2 range of dates during which prevalence is computed    }
      anproj2 year of en of projection (same day and month as proj1).    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
   */    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
   int *popage;    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
   double agec; /* generic age */    free_vector(xp,1,npar);
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;    fclose(ficresprob);
   double *popeffectif,*popcount;    fclose(ficresprobcov);
   double ***p3mat;    fclose(ficresprobcor);
   double ***mobaverage;    fflush(ficgp);
   char fileresf[FILENAMELENGTH];    fflush(fichtmcov);
   }
   agelim=AGESUP;  
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);  
    /******************* Printing html file ***********/
   strcpy(fileresf,"f");   void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
   strcat(fileresf,fileres);                    int lastpass, int stepm, int weightopt, char model[],\
   if((ficresf=fopen(fileresf,"w"))==NULL) {                    int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
     printf("Problem with forecast resultfile: %s\n", fileresf);                    int popforecast, int estepm ,\
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);                    double jprev1, double mprev1,double anprev1, \
   }                    double jprev2, double mprev2,double anprev2){
   printf("Computing forecasting: result on file '%s' \n", fileresf);    int jj1, k1, i1, cpt;
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);  
      fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
   if (cptcoveff==0) ncodemax[cptcoveff]=1;     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
   </ul>");
   if (mobilav!=0) {     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);     fprintf(fichtm,"\
       printf(" Error in movingaverage mobilav=%d\n",mobilav);   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
     }             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
   }     fprintf(fichtm,"\
    - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
   stepsize=(int) (stepm+YEARM-1)/YEARM;             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
   if (stepm<=12) stepsize=1;     fprintf(fichtm,"\
   if(estepm < stepm){   - (a) Life expectancies by health status at initial age, (b) health expectancies by health status at initial age:  ei., eij . If one or more covariate are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
     printf ("Problem %d lower than %d\n",estepm, stepm);     <a href=\"%s\">%s</a> <br>\n",
   }             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
   else  hstepm=estepm;        fprintf(fichtm,"\
    - Population projections by age and states: \
   hstepm=hstepm/stepm;      <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and  
                                fractional in yp1 */  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
   anprojmean=yp;  
   yp2=modf((yp1*12),&yp);   m=cptcoveff;
   mprojmean=yp;   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   yp1=modf((yp2*30.5),&yp);  
   jprojmean=yp;   jj1=0;
   if(jprojmean==0) jprojmean=1;   for(k1=1; k1<=m;k1++){
   if(mprojmean==0) jprojmean=1;     for(i1=1; i1<=ncodemax[k1];i1++){
        jj1++;
   i1=cptcoveff;       if (cptcovn > 0) {
   if (cptcovn < 1){i1=1;}         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
            for (cpt=1; cpt<=cptcoveff;cpt++)
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);            fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
            fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   fprintf(ficresf,"#****** Routine prevforecast **\n");       }
        /* Pij */
 /*            if (h==(int)(YEARM*yearp)){ */       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> \
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){       /* Quasi-incidences */
       k=k+1;       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
       fprintf(ficresf,"\n#******");   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> \
       for(j=1;j<=cptcoveff;j++) {  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
         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]]);         /* Period (stable) prevalence in each health state */
       }         for(cpt=1; cpt<nlstate;cpt++){
       fprintf(ficresf,"******\n");           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
       for(j=1; j<=nlstate+ndeath;j++){          }
         for(i=1; i<=nlstate;i++)                     for(cpt=1; cpt<=nlstate;cpt++) {
           fprintf(ficresf," p%d%d",i,j);          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> \
         fprintf(ficresf," p.%d",j);  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
       }       }
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {      } /* end i1 */
         fprintf(ficresf,"\n");   }/* End k1 */
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);      fprintf(fichtm,"</ul>");
   
         for (agec=fage; agec>=(ageminpar-1); agec--){   
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);    fprintf(fichtm,"\
           nhstepm = nhstepm/hstepm;   \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
           oldm=oldms;savm=savms;  
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);     fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                    subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
           for (h=0; h<=nhstepm; h++){   fprintf(fichtm,"\
             if (h*hstepm/YEARM*stepm ==yearp) {   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
               fprintf(ficresf,"\n");           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
               for(j=1;j<=cptcoveff;j++)   
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);   fprintf(fichtm,"\
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
             }            subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
             for(j=1; j<=nlstate+ndeath;j++) {   fprintf(fichtm,"\
               ppij=0.;   - 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): \
               for(i=1; i<=nlstate;i++) {     <a href=\"%s\">%s</a> <br>\n</li>",
                 if (mobilav==1)              estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];   fprintf(fichtm,"\
                 else {   - (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): \
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];     <a href=\"%s\">%s</a> <br>\n</li>",
                 }             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                 if (h*hstepm/YEARM*stepm== yearp) {   fprintf(fichtm,"\
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);   - 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",
                 }           estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
               } /* end i */   fprintf(fichtm,"\
               if (h*hstepm/YEARM*stepm==yearp) {   - 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",
                 fprintf(ficresf," %.3f", ppij);           subdirf2(fileres,"t"),subdirf2(fileres,"t"));
               }   fprintf(fichtm,"\
             }/* end j */   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
           } /* end h */           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  
         } /* end agec */  /*  if(popforecast==1) fprintf(fichtm,"\n */
       } /* end yearp */  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
     } /* end cptcod */  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
   } /* end  cptcov */  /*      <br>",fileres,fileres,fileres,fileres); */
          /*  else  */
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  /*    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); */
    fflush(fichtm);
   fclose(ficresf);   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 }  
    m=cptcoveff;
 /************** Forecasting *****not tested NB*************/   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 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){  
      jj1=0;
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;   for(k1=1; k1<=m;k1++){
   int *popage;     for(i1=1; i1<=ncodemax[k1];i1++){
   double calagedatem, agelim, kk1, kk2;       jj1++;
   double *popeffectif,*popcount;       if (cptcovn > 0) {
   double ***p3mat,***tabpop,***tabpopprev;         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
   double ***mobaverage;         for (cpt=1; cpt<=cptcoveff;cpt++)
   char filerespop[FILENAMELENGTH];           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
          fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);       }
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);       for(cpt=1; cpt<=nlstate;cpt++) {
   agelim=AGESUP;         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
     <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);       }
          fprintf(fichtm,"\n<br>- Total life expectancy by age and \
     health expectancies in states (1) and (2): %s%d.png<br>\
   strcpy(filerespop,"pop");   <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
   strcat(filerespop,fileres);     } /* end i1 */
   if((ficrespop=fopen(filerespop,"w"))==NULL) {   }/* End k1 */
     printf("Problem with forecast resultfile: %s\n", filerespop);   fprintf(fichtm,"</ul>");
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);   fflush(fichtm);
   }  }
   printf("Computing forecasting: result on file '%s' \n", filerespop);  
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);  /******************* Gnuplot file **************/
   void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   if (cptcoveff==0) ncodemax[cptcoveff]=1;  
     char dirfileres[132],optfileres[132];
   if (mobilav!=0) {    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    int ng;
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);  /*     printf("Problem with file %s",optionfilegnuplot); */
       printf(" Error in movingaverage mobilav=%d\n",mobilav);  /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
     }  /*   } */
   }  
     /*#ifdef windows */
   stepsize=(int) (stepm+YEARM-1)/YEARM;    fprintf(ficgp,"cd \"%s\" \n",pathc);
   if (stepm<=12) stepsize=1;      /*#endif */
       m=pow(2,cptcoveff);
   agelim=AGESUP;  
       strcpy(dirfileres,optionfilefiname);
   hstepm=1;    strcpy(optfileres,"vpl");
   hstepm=hstepm/stepm;    /* 1eme*/
       for (cpt=1; cpt<= nlstate ; cpt ++) {
   if (popforecast==1) {     for (k1=1; k1<= m ; k1 ++) {
     if((ficpop=fopen(popfile,"r"))==NULL) {       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
       printf("Problem with population file : %s\n",popfile);exit(0);       fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);       fprintf(ficgp,"set xlabel \"Age\" \n\
     }   set ylabel \"Probability\" \n\
     popage=ivector(0,AGESUP);  set ter png small\n\
     popeffectif=vector(0,AGESUP);  set size 0.65,0.65\n\
     popcount=vector(0,AGESUP);  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
       
     i=1;          for (i=1; i<= nlstate ; i ++) {
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
             else fprintf(ficgp," \%%*lf (\%%*lf)");
     imx=i;       }
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];       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);
   }       for (i=1; i<= nlstate ; i ++) {
          if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){         else fprintf(ficgp," \%%*lf (\%%*lf)");
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){       }
       k=k+1;       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);
       fprintf(ficrespop,"\n#******");       for (i=1; i<= nlstate ; i ++) {
       for(j=1;j<=cptcoveff;j++) {         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);         else fprintf(ficgp," \%%*lf (\%%*lf)");
       }       }  
       fprintf(ficrespop,"******\n");       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));
       fprintf(ficrespop,"# Age");     }
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);    }
       if (popforecast==1)  fprintf(ficrespop," [Population]");    /*2 eme*/
          
       for (cpt=0; cpt<=0;cpt++) {     for (k1=1; k1<= m ; k1 ++) {
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);         fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
               fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){      
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);       for (i=1; i<= nlstate+1 ; i ++) {
           nhstepm = nhstepm/hstepm;         k=2*i;
                   fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        for (j=1; j<= nlstate+1 ; j ++) {
           oldm=oldms;savm=savms;          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);            else fprintf(ficgp," \%%*lf (\%%*lf)");
                 }  
           for (h=0; h<=nhstepm; h++){        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
             if (h==(int) (calagedatem+YEARM*cpt)) {        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
             }         for (j=1; j<= nlstate+1 ; j ++) {
             for(j=1; j<=nlstate+ndeath;j++) {          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
               kk1=0.;kk2=0;          else fprintf(ficgp," \%%*lf (\%%*lf)");
               for(i=1; i<=nlstate;i++) {                      }  
                 if (mobilav==1)         fprintf(ficgp,"\" t\"\" w l 0,");
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                 else {        for (j=1; j<= nlstate+1 ; j ++) {
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                 }          else fprintf(ficgp," \%%*lf (\%%*lf)");
               }        }  
               if (h==(int)(calagedatem+12*cpt)){        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;        else fprintf(ficgp,"\" t\"\" w l 0,");
                   /*fprintf(ficrespop," %.3f", kk1);      }
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/    }
               }   
             }    /*3eme*/
             for(i=1; i<=nlstate;i++){   
               kk1=0.;    for (k1=1; k1<= m ; k1 ++) {
                 for(j=1; j<=nlstate;j++){      for (cpt=1; cpt<= nlstate ; cpt ++) {
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];         /*       k=2+nlstate*(2*cpt-2); */
                 }        k=2+(nlstate+1)*(cpt-1);
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
             }        fprintf(ficgp,"set ter png small\n\
   set size 0.65,0.65\n\
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)   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);
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
           }          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
         }          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
       }          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
            fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
   /******/         
         */
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {         for (i=1; i< nlstate ; i ++) {
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);             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);
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){           /*      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);*/
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);          
           nhstepm = nhstepm/hstepm;         }
                   fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      }
           oldm=oldms;savm=savms;    }
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);     
           for (h=0; h<=nhstepm; h++){    /* CV preval stable (period) */
             if (h==(int) (calagedatem+YEARM*cpt)) {    for (k1=1; k1<= m ; k1 ++) {
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);      for (cpt=1; cpt<=nlstate ; cpt ++) {
             }         k=3;
             for(j=1; j<=nlstate+ndeath;j++) {        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
               kk1=0.;kk2=0;        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
               for(i=1; i<=nlstate;i++) {                set ter png small\nset size 0.65,0.65\n\
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];      unset log y\n\
               }  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);               
             }        for (i=1; i< nlstate ; i ++)
           }          fprintf(ficgp,"+$%d",k+i+1);
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
         }       
       }        l=3+(nlstate+ndeath)*cpt;
    }         fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
   }        for (i=1; i< nlstate ; i ++) {
            l=3+(nlstate+ndeath)*cpt;
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          fprintf(ficgp,"+$%d",l+i+1);
         }
   if (popforecast==1) {        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
     free_ivector(popage,0,AGESUP);      }
     free_vector(popeffectif,0,AGESUP);    }  
     free_vector(popcount,0,AGESUP);   
   }    /* proba elementaires */
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    for(i=1,jk=1; i <=nlstate; i++){
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      for(k=1; k <=(nlstate+ndeath); k++){
   fclose(ficrespop);        if (k != i) {
 } /* End of popforecast */          for(j=1; j <=ncovmodel; j++){
             fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 int fileappend(FILE *fichier, char *optionfich)            jk++;
 {            fprintf(ficgp,"\n");
   if((fichier=fopen(optionfich,"a"))==NULL) {          }
     printf("Problem with file: %s\n", optionfich);        }
     fprintf(ficlog,"Problem with file: %s\n", optionfich);      }
     return (0);     }
   }  
   fflush(fichier);     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
   return (1);       for(jk=1; jk <=m; jk++) {
 }         fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)         if (ng==2)
 {           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
          else
   char ca[32], cb[32], cc[32];           fprintf(ficgp,"\nset title \"Probability\"\n");
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
   int numlinepar;         i=1;
          for(k2=1; k2<=nlstate; k2++) {
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");           k3=i;
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");           for(k=1; k<=(nlstate+ndeath); k++) {
   for(i=1; i <=nlstate; i++){             if (k != k2){
     jj=0;               if(ng==2)
     for(j=1; j <=nlstate+ndeath; j++){                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
       if(j==i) continue;               else
       jj++;                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
       /*ca[0]= k+'a'-1;ca[1]='\0';*/               ij=1;
       printf("%1d%1d",i,j);               for(j=3; j <=ncovmodel; j++) {
       fprintf(ficparo,"%1d%1d",i,j);                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
       for(k=1; k<=ncovmodel;k++){                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
         /*        printf(" %lf",param[i][j][k]); */                   ij++;
         /*        fprintf(ficparo," %lf",param[i][j][k]); */                 }
         printf(" 0.");                 else
         fprintf(ficparo," 0.");                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
       }               }
       printf("\n");               fprintf(ficgp,")/(1");
       fprintf(ficparo,"\n");               
     }               for(k1=1; k1 <=nlstate; k1++){  
   }                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
   printf("# Scales (for hessian or gradient estimation)\n");                 ij=1;
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");                 for(j=3; j <=ncovmodel; j++){
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/                    if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
   for(i=1; i <=nlstate; i++){                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
     jj=0;                     ij++;
     for(j=1; j <=nlstate+ndeath; j++){                   }
       if(j==i) continue;                   else
       jj++;                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
       fprintf(ficparo,"%1d%1d",i,j);                 }
       printf("%1d%1d",i,j);                 fprintf(ficgp,")");
       fflush(stdout);               }
       for(k=1; k<=ncovmodel;k++){               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
         /*      printf(" %le",delti3[i][j][k]); */               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */               i=i+ncovmodel;
         printf(" 0.");             }
         fprintf(ficparo," 0.");           } /* end k */
       }         } /* end k2 */
       numlinepar++;       } /* end jk */
       printf("\n");     } /* end ng */
       fprintf(ficparo,"\n");     fflush(ficgp);
     }  }  /* end gnuplot */
   }  
   printf("# Covariance matrix\n");  
 /* # 121 Var(a12)\n\ */  /*************** Moving average **************/
 /* # 122 Cov(b12,a12) Var(b12)\n\ */  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */  
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */    int i, cpt, cptcod;
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */    int modcovmax =1;
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */    int mobilavrange, mob;
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */    double age;
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */  
   fflush(stdout);    modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
   fprintf(ficparo,"# Covariance matrix\n");                             a covariate has 2 modalities */
   /* # 121 Var(a12)\n\ */    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
   /* # 122 Cov(b12,a12) Var(b12)\n\ */  
   /* #   ...\n\ */    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */      if(mobilav==1) mobilavrange=5; /* default */
         else mobilavrange=mobilav;
   for(itimes=1;itimes<=2;itimes++){      for (age=bage; age<=fage; age++)
     jj=0;        for (i=1; i<=nlstate;i++)
     for(i=1; i <=nlstate; i++){          for (cptcod=1;cptcod<=modcovmax;cptcod++)
       for(j=1; j <=nlstate+ndeath; j++){            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
         if(j==i) continue;      /* We keep the original values on the extreme ages bage, fage and for
         for(k=1; k<=ncovmodel;k++){         fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
           jj++;         we use a 5 terms etc. until the borders are no more concerned.
           ca[0]= k+'a'-1;ca[1]='\0';      */
           if(itimes==1){      for (mob=3;mob <=mobilavrange;mob=mob+2){
             printf("#%1d%1d%d",i,j,k);        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
             fprintf(ficparo,"#%1d%1d%d",i,j,k);          for (i=1; i<=nlstate;i++){
           }else{            for (cptcod=1;cptcod<=modcovmax;cptcod++){
             printf("%1d%1d%d",i,j,k);              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
             fprintf(ficparo,"%1d%1d%d",i,j,k);                for (cpt=1;cpt<=(mob-1)/2;cpt++){
             /*  printf(" %.5le",matcov[i][j]); */                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
           }                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
           ll=0;                }
           for(li=1;li <=nlstate; li++){              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
             for(lj=1;lj <=nlstate+ndeath; lj++){            }
               if(lj==li) continue;          }
               for(lk=1;lk<=ncovmodel;lk++){        }/* end age */
                 ll++;      }/* end mob */
                 if(ll<=jj){    }else return -1;
                   cb[0]= lk +'a'-1;cb[1]='\0';    return 0;
                   if(ll<jj){  }/* End movingaverage */
                     if(itimes==1){  
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);  
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);  /************** Forecasting ******************/
                     }else{  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){
                       printf(" 0.");    /* proj1, year, month, day of starting projection
                       fprintf(ficparo," 0.");       agemin, agemax range of age
                     }       dateprev1 dateprev2 range of dates during which prevalence is computed
                   }else{       anproj2 year of en of projection (same day and month as proj1).
                     if(itimes==1){    */
                       printf(" Var(%s%1d%1d)",ca,i,j);    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);    int *popage;
                     }else{    double agec; /* generic age */
                       printf(" 0.");    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                       fprintf(ficparo," 0.");    double *popeffectif,*popcount;
                     }    double ***p3mat;
                   }    double ***mobaverage;
                 }    char fileresf[FILENAMELENGTH];
               } /* end lk */  
             } /* end lj */    agelim=AGESUP;
           } /* end li */    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
           printf("\n");   
           fprintf(ficparo,"\n");    strcpy(fileresf,"f");
           numlinepar++;    strcat(fileresf,fileres);
         } /* end k*/    if((ficresf=fopen(fileresf,"w"))==NULL) {
       } /*end j */      printf("Problem with forecast resultfile: %s\n", fileresf);
     } /* end i */      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
   }    }
     printf("Computing forecasting: result on file '%s' \n", fileresf);
 } /* end of prwizard */    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
   
     if (cptcoveff==0) ncodemax[cptcoveff]=1;
 /***********************************************/  
 /**************** Main Program *****************/    if (mobilav!=0) {
 /***********************************************/      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 int main(int argc, char *argv[])        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 {        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);      }
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;    }
   int jj, imk;  
   int numlinepar=0; /* Current linenumber of parameter file */    stepsize=(int) (stepm+YEARM-1)/YEARM;
   /*  FILE *fichtm; *//* Html File */    if (stepm<=12) stepsize=1;
   /* FILE *ficgp;*/ /*Gnuplot File */    if(estepm < stepm){
   double agedeb, agefin,hf;      printf ("Problem %d lower than %d\n",estepm, stepm);
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;    }
     else  hstepm=estepm;  
   double fret;  
   double **xi,tmp,delta;    hstepm=hstepm/stepm;
     yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
   double dum; /* Dummy variable */                                 fractional in yp1 */
   double ***p3mat;    anprojmean=yp;
   double ***mobaverage;    yp2=modf((yp1*12),&yp);
   int *indx;    mprojmean=yp;
   char line[MAXLINE], linepar[MAXLINE];    yp1=modf((yp2*30.5),&yp);
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];    jprojmean=yp;
   char pathr[MAXLINE];     if(jprojmean==0) jprojmean=1;
   int firstobs=1, lastobs=10;    if(mprojmean==0) jprojmean=1;
   int sdeb, sfin; /* Status at beginning and end */  
   int c,  h , cpt,l;    i1=cptcoveff;
   int ju,jl, mi;    if (cptcovn < 1){i1=1;}
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;   
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;     fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */   
   int mobilav=0,popforecast=0;    fprintf(ficresf,"#****** Routine prevforecast **\n");
   int hstepm, nhstepm;  
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;  /*            if (h==(int)(YEARM*yearp)){ */
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
       for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   double bage, fage, age, agelim, agebase;        k=k+1;
   double ftolpl=FTOL;        fprintf(ficresf,"\n#******");
   double **prlim;        for(j=1;j<=cptcoveff;j++) {
   double *severity;          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]]);
   double ***param; /* Matrix of parameters */        }
   double  *p;        fprintf(ficresf,"******\n");
   double **matcov; /* Matrix of covariance */        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
   double ***delti3; /* Scale */        for(j=1; j<=nlstate+ndeath;j++){
   double *delti; /* Scale */          for(i=1; i<=nlstate;i++)              
   double ***eij, ***vareij;            fprintf(ficresf," p%d%d",i,j);
   double **varpl; /* Variances of prevalence limits by age */          fprintf(ficresf," p.%d",j);
   double *epj, vepp;        }
   double kk1, kk2;        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;          fprintf(ficresf,"\n");
           fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
   char *alph[]={"a","a","b","c","d","e"}, str[4];  
           for (agec=fage; agec>=(ageminpar-1); agec--){
             nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
   char z[1]="c", occ;            nhstepm = nhstepm/hstepm;
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];            oldm=oldms;savm=savms;
   char strstart[80], *strt, strtend[80];            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
   char *stratrunc;         
   int lstra;            for (h=0; h<=nhstepm; h++){
               if (h*hstepm/YEARM*stepm ==yearp) {
   long total_usecs;                fprintf(ficresf,"\n");
                  for(j=1;j<=cptcoveff;j++)
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   (void) gettimeofday(&start_time,&tzp);                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
   curr_time=start_time;              }
   tm = *localtime(&start_time.tv_sec);              for(j=1; j<=nlstate+ndeath;j++) {
   tmg = *gmtime(&start_time.tv_sec);                ppij=0.;
   strcpy(strstart,asctime(&tm));                for(i=1; i<=nlstate;i++) {
                   if (mobilav==1)
 /*  printf("Localtime (at start)=%s",strstart); */                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 /*  tp.tv_sec = tp.tv_sec +86400; */                  else {
 /*  tm = *localtime(&start_time.tv_sec); */                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */                  }
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */                  if (h*hstepm/YEARM*stepm== yearp) {
 /*   tmg.tm_hour=tmg.tm_hour + 1; */                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
 /*   tp.tv_sec = mktime(&tmg); */                  }
 /*   strt=asctime(&tmg); */                } /* end i */
 /*   printf("Time(after) =%s",strstart);  */                if (h*hstepm/YEARM*stepm==yearp) {
 /*  (void) time (&time_value);                  fprintf(ficresf," %.3f", ppij);
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);                }
 *  tm = *localtime(&time_value);              }/* end j */
 *  strstart=asctime(&tm);            } /* end h */
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 */          } /* end agec */
         } /* end yearp */
   nberr=0; /* Number of errors and warnings */      } /* end cptcod */
   nbwarn=0;    } /* end  cptcov */
   getcwd(pathcd, size);         
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   printf("\n%s\n%s",version,fullversion);  
   if(argc <=1){    fclose(ficresf);
     printf("\nEnter the parameter file name: ");  }
     scanf("%s",pathtot);  
   }  /************** Forecasting *****not tested NB*************/
   else{  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){
     strcpy(pathtot,argv[1]);   
   }    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/    int *popage;
   /*cygwin_split_path(pathtot,path,optionfile);    double calagedatem, agelim, kk1, kk2;
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/    double *popeffectif,*popcount;
   /* cutv(path,optionfile,pathtot,'\\');*/    double ***p3mat,***tabpop,***tabpopprev;
     double ***mobaverage;
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);    char filerespop[FILENAMELENGTH];
   printf("pathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);  
   chdir(path);    tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   strcpy(command,"mkdir ");    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   strcat(command,optionfilefiname);    agelim=AGESUP;
   if((outcmd=system(command)) != 0){    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);   
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
     /* fclose(ficlog); */   
 /*     exit(1); */   
   }    strcpy(filerespop,"pop");
 /*   if((imk=mkdir(optionfilefiname))<0){ */    strcat(filerespop,fileres);
 /*     perror("mkdir"); */    if((ficrespop=fopen(filerespop,"w"))==NULL) {
 /*   } */      printf("Problem with forecast resultfile: %s\n", filerespop);
       fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
   /*-------- arguments in the command line --------*/    }
     printf("Computing forecasting: result on file '%s' \n", filerespop);
   /* Log file */    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
   strcat(filelog, optionfilefiname);  
   strcat(filelog,".log");    /* */    if (cptcoveff==0) ncodemax[cptcoveff]=1;
   if((ficlog=fopen(filelog,"w"))==NULL)    {  
     printf("Problem with logfile %s\n",filelog);    if (mobilav!=0) {
     goto end;      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   }      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
   fprintf(ficlog,"Log filename:%s\n",filelog);        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   fprintf(ficlog,"\n%s\n%s",version,fullversion);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   fprintf(ficlog,"\nEnter the parameter file name: ");      }
   fprintf(ficlog,"pathtot=%s\n\    }
  path=%s \n\  
  optionfile=%s\n\    stepsize=(int) (stepm+YEARM-1)/YEARM;
  optionfilext=%s\n\    if (stepm<=12) stepsize=1;
  optionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);   
     agelim=AGESUP;
   printf("Localtime (at start):%s",strstart);   
   fprintf(ficlog,"Localtime (at start): %s",strstart);    hstepm=1;
   fflush(ficlog);    hstepm=hstepm/stepm;
 /*   (void) gettimeofday(&curr_time,&tzp); */   
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */    if (popforecast==1) {
       if((ficpop=fopen(popfile,"r"))==NULL) {
   /* */        printf("Problem with population file : %s\n",popfile);exit(0);
   strcpy(fileres,"r");        fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
   strcat(fileres, optionfilefiname);      }
   strcat(fileres,".txt");    /* Other files have txt extension */      popage=ivector(0,AGESUP);
       popeffectif=vector(0,AGESUP);
   /*---------arguments file --------*/      popcount=vector(0,AGESUP);
      
   if((ficpar=fopen(optionfile,"r"))==NULL)    {      i=1;  
     printf("Problem with optionfile %s\n",optionfile);      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);     
     fflush(ficlog);      imx=i;
     goto end;      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
   }    }
   
     for(cptcov=1,k=0;cptcov<=i2;cptcov++){
      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   strcpy(filereso,"o");        k=k+1;
   strcat(filereso,fileres);        fprintf(ficrespop,"\n#******");
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */        for(j=1;j<=cptcoveff;j++) {
     printf("Problem with Output resultfile: %s\n", filereso);          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);        }
     fflush(ficlog);        fprintf(ficrespop,"******\n");
     goto end;        fprintf(ficrespop,"# Age");
   }        for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
         if (popforecast==1)  fprintf(ficrespop," [Population]");
   /* Reads comments: lines beginning with '#' */       
   numlinepar=0;        for (cpt=0; cpt<=0;cpt++) {
   while((c=getc(ficpar))=='#' && c!= EOF){          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
     ungetc(c,ficpar);         
     fgets(line, MAXLINE, ficpar);          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
     numlinepar++;            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
     puts(line);            nhstepm = nhstepm/hstepm;
     fputs(line,ficparo);           
     fputs(line,ficlog);            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   }            oldm=oldms;savm=savms;
   ungetc(c,ficpar);            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
          
   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);            for (h=0; h<=nhstepm; h++){
   numlinepar++;              if (h==(int) (calagedatem+YEARM*cpt)) {
   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);                fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   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);              }
   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);              for(j=1; j<=nlstate+ndeath;j++) {
   fflush(ficlog);                kk1=0.;kk2=0;
   while((c=getc(ficpar))=='#' && c!= EOF){                for(i=1; i<=nlstate;i++) {              
     ungetc(c,ficpar);                  if (mobilav==1)
     fgets(line, MAXLINE, ficpar);                    kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
     numlinepar++;                  else {
     puts(line);                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
     fputs(line,ficparo);                  }
     fputs(line,ficlog);                }
   }                if (h==(int)(calagedatem+12*cpt)){
   ungetc(c,ficpar);                  tabpop[(int)(agedeb)][j][cptcod]=kk1;
                     /*fprintf(ficrespop," %.3f", kk1);
                          if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
   covar=matrix(0,NCOVMAX,1,n);                 }
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/              }
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;              for(i=1; i<=nlstate;i++){
                 kk1=0.;
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */                  for(j=1; j<=nlstate;j++){
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
                    }
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);              }
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);  
     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
     fclose (ficparo);                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
     fclose (ficlog);            }
     exit(0);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   }          }
   /* Read guess parameters */        }
   /* Reads comments: lines beginning with '#' */   
   while((c=getc(ficpar))=='#' && c!= EOF){    /******/
     ungetc(c,ficpar);  
     fgets(line, MAXLINE, ficpar);        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
     numlinepar++;          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
     puts(line);          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
     fputs(line,ficparo);            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
     fputs(line,ficlog);            nhstepm = nhstepm/hstepm;
   }           
   ungetc(c,ficpar);            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             oldm=oldms;savm=savms;
   param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   for(i=1; i <=nlstate; i++){            for (h=0; h<=nhstepm; h++){
     j=0;              if (h==(int) (calagedatem+YEARM*cpt)) {
     for(jj=1; jj <=nlstate+ndeath; jj++){                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
       if(jj==i) continue;              }
       j++;              for(j=1; j<=nlstate+ndeath;j++) {
       fscanf(ficpar,"%1d%1d",&i1,&j1);                kk1=0.;kk2=0;
       if ((i1 != i) && (j1 != j)){                for(i=1; i<=nlstate;i++) {              
         printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
         exit(1);                }
       }                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
       fprintf(ficparo,"%1d%1d",i1,j1);              }
       if(mle==1)            }
         printf("%1d%1d",i,j);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       fprintf(ficlog,"%1d%1d",i,j);          }
       for(k=1; k<=ncovmodel;k++){        }
         fscanf(ficpar," %lf",&param[i][j][k]);     }
         if(mle==1){    }
           printf(" %lf",param[i][j][k]);   
           fprintf(ficlog," %lf",param[i][j][k]);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         }  
         else    if (popforecast==1) {
           fprintf(ficlog," %lf",param[i][j][k]);      free_ivector(popage,0,AGESUP);
         fprintf(ficparo," %lf",param[i][j][k]);      free_vector(popeffectif,0,AGESUP);
       }      free_vector(popcount,0,AGESUP);
       fscanf(ficpar,"\n");    }
       numlinepar++;    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       if(mle==1)    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         printf("\n");    fclose(ficrespop);
       fprintf(ficlog,"\n");  } /* End of popforecast */
       fprintf(ficparo,"\n");  
     }  int fileappend(FILE *fichier, char *optionfich)
   }    {
   fflush(ficlog);    if((fichier=fopen(optionfich,"a"))==NULL) {
       printf("Problem with file: %s\n", optionfich);
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/      fprintf(ficlog,"Problem with file: %s\n", optionfich);
       return (0);
   p=param[1][1];    }
       fflush(fichier);
   /* Reads comments: lines beginning with '#' */    return (1);
   while((c=getc(ficpar))=='#' && c!= EOF){  }
     ungetc(c,ficpar);  
     fgets(line, MAXLINE, ficpar);  
     numlinepar++;  /**************** function prwizard **********************/
     puts(line);  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
     fputs(line,ficparo);  {
     fputs(line,ficlog);  
   }    /* Wizard to print covariance matrix template */
   ungetc(c,ficpar);  
     char ca[32], cb[32], cc[32];
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
   /* delti=vector(1,npar); *//* Scale of each paramater (output from hesscov) */    int numlinepar;
   for(i=1; i <=nlstate; i++){  
     for(j=1; j <=nlstate+ndeath-1; j++){    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       fscanf(ficpar,"%1d%1d",&i1,&j1);    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       if ((i1-i)*(j1-j)!=0){    for(i=1; i <=nlstate; i++){
         printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);      jj=0;
         exit(1);      for(j=1; j <=nlstate+ndeath; j++){
       }        if(j==i) continue;
       printf("%1d%1d",i,j);        jj++;
       fprintf(ficparo,"%1d%1d",i1,j1);        /*ca[0]= k+'a'-1;ca[1]='\0';*/
       fprintf(ficlog,"%1d%1d",i1,j1);        printf("%1d%1d",i,j);
       for(k=1; k<=ncovmodel;k++){        fprintf(ficparo,"%1d%1d",i,j);
         fscanf(ficpar,"%le",&delti3[i][j][k]);        for(k=1; k<=ncovmodel;k++){
         printf(" %le",delti3[i][j][k]);          /*        printf(" %lf",param[i][j][k]); */
         fprintf(ficparo," %le",delti3[i][j][k]);          /*        fprintf(ficparo," %lf",param[i][j][k]); */
         fprintf(ficlog," %le",delti3[i][j][k]);          printf(" 0.");
       }          fprintf(ficparo," 0.");
       fscanf(ficpar,"\n");        }
       numlinepar++;        printf("\n");
       printf("\n");        fprintf(ficparo,"\n");
       fprintf(ficparo,"\n");      }
       fprintf(ficlog,"\n");    }
     }    printf("# Scales (for hessian or gradient estimation)\n");
   }    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
   fflush(ficlog);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
     for(i=1; i <=nlstate; i++){
   delti=delti3[1][1];      jj=0;
       for(j=1; j <=nlstate+ndeath; j++){
         if(j==i) continue;
   /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */        jj++;
           fprintf(ficparo,"%1d%1d",i,j);
   /* Reads comments: lines beginning with '#' */        printf("%1d%1d",i,j);
   while((c=getc(ficpar))=='#' && c!= EOF){        fflush(stdout);
     ungetc(c,ficpar);        for(k=1; k<=ncovmodel;k++){
     fgets(line, MAXLINE, ficpar);          /*      printf(" %le",delti3[i][j][k]); */
     numlinepar++;          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
     puts(line);          printf(" 0.");
     fputs(line,ficparo);          fprintf(ficparo," 0.");
     fputs(line,ficlog);        }
   }        numlinepar++;
   ungetc(c,ficpar);        printf("\n");
           fprintf(ficparo,"\n");
   matcov=matrix(1,npar,1,npar);      }
   for(i=1; i <=npar; i++){    }
     fscanf(ficpar,"%s",&str);    printf("# Covariance matrix\n");
     if(mle==1)  /* # 121 Var(a12)\n\ */
       printf("%s",str);  /* # 122 Cov(b12,a12) Var(b12)\n\ */
     fprintf(ficlog,"%s",str);  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
     fprintf(ficparo,"%s",str);  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
     for(j=1; j <=i; j++){  /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
       fscanf(ficpar," %le",&matcov[i][j]);  /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
       if(mle==1){  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
         printf(" %.5le",matcov[i][j]);  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
       }    fflush(stdout);
       fprintf(ficlog," %.5le",matcov[i][j]);    fprintf(ficparo,"# Covariance matrix\n");
       fprintf(ficparo," %.5le",matcov[i][j]);    /* # 121 Var(a12)\n\ */
     }    /* # 122 Cov(b12,a12) Var(b12)\n\ */
     fscanf(ficpar,"\n");    /* #   ...\n\ */
     numlinepar++;    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
     if(mle==1)   
       printf("\n");    for(itimes=1;itimes<=2;itimes++){
     fprintf(ficlog,"\n");      jj=0;
     fprintf(ficparo,"\n");      for(i=1; i <=nlstate; i++){
   }        for(j=1; j <=nlstate+ndeath; j++){
   for(i=1; i <=npar; i++)          if(j==i) continue;
     for(j=i+1;j<=npar;j++)          for(k=1; k<=ncovmodel;k++){
       matcov[i][j]=matcov[j][i];            jj++;
                ca[0]= k+'a'-1;ca[1]='\0';
   if(mle==1)            if(itimes==1){
     printf("\n");              printf("#%1d%1d%d",i,j,k);
   fprintf(ficlog,"\n");              fprintf(ficparo,"#%1d%1d%d",i,j,k);
             }else{
   fflush(ficlog);              printf("%1d%1d%d",i,j,k);
               fprintf(ficparo,"%1d%1d%d",i,j,k);
   /*-------- Rewriting paramater file ----------*/              /*  printf(" %.5le",matcov[i][j]); */
   strcpy(rfileres,"r");    /* "Rparameterfile */            }
   strcat(rfileres,optionfilefiname);    /* Parameter file first name*/            ll=0;
   strcat(rfileres,".");    /* */            for(li=1;li <=nlstate; li++){
   strcat(rfileres,optionfilext);    /* Other files have txt extension */              for(lj=1;lj <=nlstate+ndeath; lj++){
   if((ficres =fopen(rfileres,"w"))==NULL) {                if(lj==li) continue;
     printf("Problem writing new parameter file: %s\n", fileres);goto end;                for(lk=1;lk<=ncovmodel;lk++){
     fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;                  ll++;
   }                  if(ll<=jj){
   fprintf(ficres,"#%s\n",version);                    cb[0]= lk +'a'-1;cb[1]='\0';
                         if(ll<jj){
   /*-------- data file ----------*/                      if(itimes==1){
   if((fic=fopen(datafile,"r"))==NULL)    {                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     printf("Problem with datafile: %s\n", datafile);goto end;                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;                      }else{
   }                        printf(" 0.");
                         fprintf(ficparo," 0.");
   n= lastobs;                      }
   severity = vector(1,maxwav);                    }else{
   outcome=imatrix(1,maxwav+1,1,n);                      if(itimes==1){
   num=lvector(1,n);                        printf(" Var(%s%1d%1d)",ca,i,j);
   moisnais=vector(1,n);                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
   annais=vector(1,n);                      }else{
   moisdc=vector(1,n);                        printf(" 0.");
   andc=vector(1,n);                        fprintf(ficparo," 0.");
   agedc=vector(1,n);                      }
   cod=ivector(1,n);                    }
   weight=vector(1,n);                  }
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */                } /* end lk */
   mint=matrix(1,maxwav,1,n);              } /* end lj */
   anint=matrix(1,maxwav,1,n);            } /* end li */
   s=imatrix(1,maxwav+1,1,n);            printf("\n");
   tab=ivector(1,NCOVMAX);            fprintf(ficparo,"\n");
   ncodemax=ivector(1,8);            numlinepar++;
           } /* end k*/
   i=1;        } /*end j */
   while (fgets(line, MAXLINE, fic) != NULL)    {      } /* end i */
     if ((i >= firstobs) && (i <=lastobs)) {    } /* end itimes */
           
       for (j=maxwav;j>=1;j--){  } /* end of prwizard */
         cutv(stra, strb,line,' '); s[j][i]=atoi(strb);   /******************* Gompertz Likelihood ******************************/
         strcpy(line,stra);  double gompertz(double x[])
         cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);  {
         cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);    double A,B,L=0.0,sump=0.,num=0.;
       }    int i,n=0; /* n is the size of the sample */
           
       cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);    for (i=0;i<=imx-1 ; i++) {
       cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);      sump=sump+weight[i];
       /*    sump=sump+1;*/
       cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);      num=num+1;
       cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);    }
    
       cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);   
       for (j=ncovcol;j>=1;j--){    /* for (i=0; i<=imx; i++)
         cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);       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]);*/
       }   
       lstra=strlen(stra);    for (i=1;i<=imx ; i++)
       if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */      {
         stratrunc = &(stra[lstra-9]);        if (cens[i] == 1 && wav[i]>1)
         num[i]=atol(stratrunc);          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
       }       
       else        if (cens[i] == 0 && wav[i]>1)
         num[i]=atol(stra);          A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                        +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
       /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){       
         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;}*/        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
         if (wav[i] > 1 ) { /* ??? */
       i=i+1;          L=L+A*weight[i];
     }          /*      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]);*/
   }        }
   /* printf("ii=%d", ij);      }
      scanf("%d",i);*/  
   imx=i-1; /* Number of individuals */   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
    
   /* for (i=1; i<=imx; i++){    return -2*L*num/sump;
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;  }
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;  
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;  /******************* Printing html file ***********/
     }*/  void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
    /*  for (i=1; i<=imx; i++){                    int lastpass, int stepm, int weightopt, char model[],\
      if (s[4][i]==9)  s[4][i]=-1;                     int imx,  double p[],double **matcov,double agemortsup){
      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]));}*/    int i,k;
     
  for (i=1; i<=imx; i++)    fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
      fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;    for (i=1;i<=2;i++)
      else weight[i]=1;*/      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]));
     fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
   /* Calculation of the number of parameter from char model*/    fprintf(fichtm,"</ul>");
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */  
   Tprod=ivector(1,15);   fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
   Tvaraff=ivector(1,15);   
   Tvard=imatrix(1,15,1,2);   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>");
   Tage=ivector(1,15);        
       for (k=agegomp;k<(agemortsup-2);k++)
   if (strlen(model) >1){ /* If there is at least 1 covariate */     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]);
     j=0, j1=0, k1=1, k2=1;  
     j=nbocc(model,'+'); /* j=Number of '+' */   
     j1=nbocc(model,'*'); /* j1=Number of '*' */    fflush(fichtm);
     cptcovn=j+1;   }
     cptcovprod=j1; /*Number of products */  
       /******************* Gnuplot file **************/
     strcpy(modelsav,model);   void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){  
       printf("Error. Non available option model=%s ",model);    char dirfileres[132],optfileres[132];
       fprintf(ficlog,"Error. Non available option model=%s ",model);    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
       goto end;    int ng;
     }  
       
     /* This loop fills the array Tvar from the string 'model'.*/    /*#ifdef windows */
     fprintf(ficgp,"cd \"%s\" \n",pathc);
     for(i=(j+1); i>=1;i--){      /*#endif */
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */   
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */  
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/    strcpy(dirfileres,optionfilefiname);
       /*scanf("%d",i);*/    strcpy(optfileres,"vpl");
       if (strchr(strb,'*')) {  /* Model includes a product */    fprintf(ficgp,"set out \"graphmort.png\"\n ");
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
         if (strcmp(strc,"age")==0) { /* Vn*age */    fprintf(ficgp, "set ter png small\n set log y\n");
           cptcovprod--;    fprintf(ficgp, "set size 0.65,0.65\n");
           cutv(strb,stre,strd,'V');    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/  
           cptcovage++;  }
             Tage[cptcovage]=i;  
             /*printf("stre=%s ", stre);*/  
         }  
         else if (strcmp(strd,"age")==0) { /* or age*Vn */  
           cptcovprod--;  
           cutv(strb,stre,strc,'V');  /***********************************************/
           Tvar[i]=atoi(stre);  /**************** Main Program *****************/
           cptcovage++;  /***********************************************/
           Tage[cptcovage]=i;  
         }  int main(int argc, char *argv[])
         else {  /* Age is not in the model */  {
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
           Tvar[i]=ncovcol+k1;    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */    int linei, month, year,iout;
           Tprod[k1]=i;    int jj, ll, li, lj, lk, imk;
           Tvard[k1][1]=atoi(strc); /* m*/    int numlinepar=0; /* Current linenumber of parameter file */
           Tvard[k1][2]=atoi(stre); /* n */    int itimes;
           Tvar[cptcovn+k2]=Tvard[k1][1];    int NDIM=2;
           Tvar[cptcovn+k2+1]=Tvard[k1][2];   
           for (k=1; k<=lastobs;k++)     char ca[32], cb[32], cc[32];
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];    char dummy[]="                         ";
           k1++;    /*  FILE *fichtm; *//* Html File */
           k2=k2+2;    /* FILE *ficgp;*/ /*Gnuplot File */
         }    struct stat info;
       }    double agedeb, agefin,hf;
       else { /* no more sum */    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/  
        /*  scanf("%d",i);*/    double fret;
       cutv(strd,strc,strb,'V');    double **xi,tmp,delta;
       Tvar[i]=atoi(strc);  
       }    double dum; /* Dummy variable */
       strcpy(modelsav,stra);      double ***p3mat;
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);    double ***mobaverage;
         scanf("%d",i);*/    int *indx;
     } /* end of loop + */    char line[MAXLINE], linepar[MAXLINE];
   } /* end model */    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
       char pathr[MAXLINE], pathimach[MAXLINE];
   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.    char **bp, *tok, *val; /* pathtot */
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/    int firstobs=1, lastobs=10;
     int sdeb, sfin; /* Status at beginning and end */
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);    int c,  h , cpt,l;
   printf("cptcovprod=%d ", cptcovprod);    int ju,jl, mi;
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
     int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
   scanf("%d ",i);    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
   fclose(fic);*/    int mobilav=0,popforecast=0;
     int hstepm, nhstepm;
     /*  if(mle==1){*/    int agemortsup;
   if (weightopt != 1) { /* Maximisation without weights*/    float  sumlpop=0.;
     for(i=1;i<=n;i++) weight[i]=1.0;    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
   }    double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
     /*-calculation of age at interview from date of interview and age at death -*/  
   agev=matrix(1,maxwav,1,imx);    double bage, fage, age, agelim, agebase;
     double ftolpl=FTOL;
   for (i=1; i<=imx; i++) {    double **prlim;
     for(m=2; (m<= maxwav); m++) {    double *severity;
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){    double ***param; /* Matrix of parameters */
         anint[m][i]=9999;    double  *p;
         s[m][i]=-1;    double **matcov; /* Matrix of covariance */
       }    double ***delti3; /* Scale */
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){    double *delti; /* Scale */
         nberr++;    double ***eij, ***vareij;
         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);    double **varpl; /* Variances of prevalence limits by age */
         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);    double *epj, vepp;
         s[m][i]=-1;    double kk1, kk2;
       }    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){    double **ximort;
         nberr++;    char *alph[]={"a","a","b","c","d","e"}, str[4];
         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]);     int *dcwave;
         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]);   
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */    char z[1]="c", occ;
       }  
     }    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
   }    char  *strt, strtend[80];
     char *stratrunc;
   for (i=1; i<=imx; i++)  {    int lstra;
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);  
     for(m=firstpass; (m<= lastpass); m++){    long total_usecs;
       if(s[m][i] >0){   
         if (s[m][i] >= nlstate+1) {  /*   setlocale (LC_ALL, ""); */
           if(agedc[i]>0)  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)  /*   textdomain (PACKAGE); */
               agev[m][i]=agedc[i];  /*   setlocale (LC_CTYPE, ""); */
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/  /*   setlocale (LC_MESSAGES, ""); */
             else {  
               if ((int)andc[i]!=9999){    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                 nbwarn++;    (void) gettimeofday(&start_time,&tzp);
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);    curr_time=start_time;
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);    tm = *localtime(&start_time.tv_sec);
                 agev[m][i]=-1;    tmg = *gmtime(&start_time.tv_sec);
               }    strcpy(strstart,asctime(&tm));
             }  
         }  /*  printf("Localtime (at start)=%s",strstart); */
         else if(s[m][i] !=9){ /* Standard case, age in fractional  /*  tp.tv_sec = tp.tv_sec +86400; */
                                  years but with the precision of a  /*  tm = *localtime(&start_time.tv_sec); */
                                  month */  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)  /*   tmg.tm_hour=tmg.tm_hour + 1; */
             agev[m][i]=1;  /*   tp.tv_sec = mktime(&tmg); */
           else if(agev[m][i] <agemin){   /*   strt=asctime(&tmg); */
             agemin=agev[m][i];  /*   printf("Time(after) =%s",strstart);  */
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/  /*  (void) time (&time_value);
           }  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
           else if(agev[m][i] >agemax){  *  tm = *localtime(&time_value);
             agemax=agev[m][i];  *  strstart=asctime(&tm);
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
           }  */
           /*agev[m][i]=anint[m][i]-annais[i];*/  
           /*     agev[m][i] = age[i]+2*m;*/    nberr=0; /* Number of errors and warnings */
         }    nbwarn=0;
         else { /* =9 */    getcwd(pathcd, size);
           agev[m][i]=1;  
           s[m][i]=-1;    printf("\n%s\n%s",version,fullversion);
         }    if(argc <=1){
       }      printf("\nEnter the parameter file name: ");
       else /*= 0 Unknown */      fgets(pathr,FILENAMELENGTH,stdin);
         agev[m][i]=1;      i=strlen(pathr);
     }      if(pathr[i-1]=='\n')
             pathr[i-1]='\0';
   }     for (tok = pathr; tok != NULL; ){
   for (i=1; i<=imx; i++)  {        printf("Pathr |%s|\n",pathr);
     for(m=firstpass; (m<=lastpass); m++){        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
       if (s[m][i] > (nlstate+ndeath)) {        printf("val= |%s| pathr=%s\n",val,pathr);
         nberr++;        strcpy (pathtot, val);
         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);             if(pathr[0] == '\0') break; /* Dirty */
         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);           }
         goto end;    }
       }    else{
     }      strcpy(pathtot,argv[1]);
   }    }
     /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
   /*for (i=1; i<=imx; i++){    /*cygwin_split_path(pathtot,path,optionfile);
   for (m=firstpass; (m<lastpass); m++){      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);    /* cutv(path,optionfile,pathtot,'\\');*/
 }  
     /* Split argv[0], imach program to get pathimach */
 }*/    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
     split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);    /*   strcpy(pathimach,argv[0]); */
     /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
   free_vector(severity,1,maxwav);    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
   free_imatrix(outcome,1,maxwav+1,1,n);    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
   free_vector(moisnais,1,n);    chdir(path); /* Can be a relative path */
   free_vector(annais,1,n);    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
   /* free_matrix(mint,1,maxwav,1,n);      printf("Current directory %s!\n",pathcd);
      free_matrix(anint,1,maxwav,1,n);*/    strcpy(command,"mkdir ");
   free_vector(moisdc,1,n);    strcat(command,optionfilefiname);
   free_vector(andc,1,n);    if((outcmd=system(command)) != 0){
       printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
          /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
   wav=ivector(1,imx);      /* fclose(ficlog); */
   dh=imatrix(1,lastpass-firstpass+1,1,imx);  /*     exit(1); */
   bh=imatrix(1,lastpass-firstpass+1,1,imx);    }
   mw=imatrix(1,lastpass-firstpass+1,1,imx);  /*   if((imk=mkdir(optionfilefiname))<0){ */
      /*     perror("mkdir"); */
   /* Concatenates waves */  /*   } */
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);  
     /*-------- arguments in the command line --------*/
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */  
     /* Log file */
   Tcode=ivector(1,100);    strcat(filelog, optionfilefiname);
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);     strcat(filelog,".log");    /* */
   ncodemax[1]=1;    if((ficlog=fopen(filelog,"w"))==NULL)    {
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);      printf("Problem with logfile %s\n",filelog);
             goto end;
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of     }
                                  the estimations*/    fprintf(ficlog,"Log filename:%s\n",filelog);
   h=0;    fprintf(ficlog,"\n%s\n%s",version,fullversion);
   m=pow(2,cptcoveff);    fprintf(ficlog,"\nEnter the parameter file name: \n");
      fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
   for(k=1;k<=cptcoveff; k++){   path=%s \n\
     for(i=1; i <=(m/pow(2,k));i++){   optionfile=%s\n\
       for(j=1; j <= ncodemax[k]; j++){   optionfilext=%s\n\
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
           h++;  
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;    printf("Local time (at start):%s",strstart);
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/    fprintf(ficlog,"Local time (at start): %s",strstart);
         }     fflush(ficlog);
       }  /*   (void) gettimeofday(&curr_time,&tzp); */
     }  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   }   
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);     /* */
      codtab[1][2]=1;codtab[2][2]=2; */    strcpy(fileres,"r");
   /* for(i=1; i <=m ;i++){     strcat(fileres, optionfilefiname);
      for(k=1; k <=cptcovn; k++){    strcat(fileres,".txt");    /* Other files have txt extension */
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);  
      }    /*---------arguments file --------*/
      printf("\n");  
      }    if((ficpar=fopen(optionfile,"r"))==NULL)    {
      scanf("%d",i);*/      printf("Problem with optionfile %s\n",optionfile);
           fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
   /*------------ gnuplot -------------*/      fflush(ficlog);
   strcpy(optionfilegnuplot,optionfilefiname);      goto end;
   strcat(optionfilegnuplot,".gp");    }
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {  
     printf("Problem with file %s",optionfilegnuplot);  
   }  
   else{    strcpy(filereso,"o");
     fprintf(ficgp,"\n# %s\n", version);     strcat(filereso,fileres);
     fprintf(ficgp,"# %s\n", optionfilegnuplot);     if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
     fprintf(ficgp,"set missing 'NaNq'\n");      printf("Problem with Output resultfile: %s\n", filereso);
   }      fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
   /*  fclose(ficgp);*/      fflush(ficlog);
   /*--------- index.htm --------*/      goto end;
     }
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */  
   strcat(optionfilehtm,".htm");    /* Reads comments: lines beginning with '#' */
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {    numlinepar=0;
     printf("Problem with %s \n",optionfilehtm), exit(0);    while((c=getc(ficpar))=='#' && c!= EOF){
   }      ungetc(c,ficpar);
       fgets(line, MAXLINE, ficpar);
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */      numlinepar++;
   strcat(optionfilehtmcov,"-cov.htm");      puts(line);
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {      fputs(line,ficparo);
     printf("Problem with %s \n",optionfilehtmcov), exit(0);      fputs(line,ficlog);
   }    }
   else{    ungetc(c,ficpar);
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \  
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    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);
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\    numlinepar++;
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);    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);
   }    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);
     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);
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \    fflush(ficlog);
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    while((c=getc(ficpar))=='#' && c!= EOF){
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\      ungetc(c,ficpar);
 \n\      fgets(line, MAXLINE, ficpar);
 <hr  size=\"2\" color=\"#EC5E5E\">\      numlinepar++;
  <ul><li><h4>Parameter files</h4>\n\      puts(line);
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\      fputs(line,ficparo);
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\      fputs(line,ficlog);
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\    }
  - Date and time at start: %s</ul>\n",\    ungetc(c,ficpar);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\  
           fileres,fileres,\     
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);    covar=matrix(0,NCOVMAX,1,n);
   fflush(fichtm);    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
     if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
   strcpy(pathr,path);  
   strcat(pathr,optionfilefiname);    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
   chdir(optionfilefiname); /* Move to directory named optionfile */    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
   strcpy(lfileres,fileres);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
   strcat(lfileres,"/");  
   strcat(lfileres,optionfilefiname);    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
       delti=delti3[1][1];
   /* Calculates basic frequencies. Computes observed prevalence at single age    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
      and prints on file fileres'p'. */    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
       printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
   fprintf(fichtm,"\n");      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\      fclose (ficparo);
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\      fclose (ficlog);
           imx,agemin,agemax,jmin,jmax,jmean);      goto end;
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      exit(0);
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    }
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    else if(mle==-3) {
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
           fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
          param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
   /* For Powell, parameters are in a vector p[] starting at p[1]      matcov=matrix(1,npar,1,npar);
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */    }
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */    else{
       /* Read guess parameters */
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/      /* Reads comments: lines beginning with '#' */
   likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */      while((c=getc(ficpar))=='#' && c!= EOF){
   printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);        ungetc(c,ficpar);
   for (k=1; k<=npar;k++)        fgets(line, MAXLINE, ficpar);
     printf(" %d %8.5f",k,p[k]);        numlinepar++;
   printf("\n");        puts(line);
   globpr=1; /* to print the contributions */        fputs(line,ficparo);
   likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */        fputs(line,ficlog);
   printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);      }
   for (k=1; k<=npar;k++)      ungetc(c,ficpar);
     printf(" %d %8.5f",k,p[k]);     
   printf("\n");      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
   if(mle>=1){ /* Could be 1 or 2 */      for(i=1; i <=nlstate; i++){
     mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);        j=0;
   }        for(jj=1; jj <=nlstate+ndeath; jj++){
               if(jj==i) continue;
   /*--------- results files --------------*/          j++;
   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);          fscanf(ficpar,"%1d%1d",&i1,&j1);
             if ((i1 != i) && (j1 != j)){
             printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
   jk=1;  It might be a problem of design; if ncovcol and the model are correct\n \
   fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");            exit(1);
   fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");          }
   for(i=1,jk=1; i <=nlstate; i++){          fprintf(ficparo,"%1d%1d",i1,j1);
     for(k=1; k <=(nlstate+ndeath); k++){          if(mle==1)
       if (k != i)             printf("%1d%1d",i,j);
         {          fprintf(ficlog,"%1d%1d",i,j);
           printf("%d%d ",i,k);          for(k=1; k<=ncovmodel;k++){
           fprintf(ficlog,"%d%d ",i,k);            fscanf(ficpar," %lf",&param[i][j][k]);
           fprintf(ficres,"%1d%1d ",i,k);            if(mle==1){
           for(j=1; j <=ncovmodel; j++){              printf(" %lf",param[i][j][k]);
             printf("%f ",p[jk]);              fprintf(ficlog," %lf",param[i][j][k]);
             fprintf(ficlog,"%f ",p[jk]);            }
             fprintf(ficres,"%f ",p[jk]);            else
             jk++;               fprintf(ficlog," %lf",param[i][j][k]);
           }            fprintf(ficparo," %lf",param[i][j][k]);
           printf("\n");          }
           fprintf(ficlog,"\n");          fscanf(ficpar,"\n");
           fprintf(ficres,"\n");          numlinepar++;
         }          if(mle==1)
     }            printf("\n");
   }          fprintf(ficlog,"\n");
   if(mle!=0){          fprintf(ficparo,"\n");
     /* Computing hessian and covariance matrix */        }
     ftolhess=ftol; /* Usually correct */      }  
     hesscov(matcov, p, npar, delti, ftolhess, func);      fflush(ficlog);
   }  
   fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");      p=param[1][1];
   printf("# Scales (for hessian or gradient estimation)\n");     
   fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");      /* Reads comments: lines beginning with '#' */
   for(i=1,jk=1; i <=nlstate; i++){      while((c=getc(ficpar))=='#' && c!= EOF){
     for(j=1; j <=nlstate+ndeath; j++){        ungetc(c,ficpar);
       if (j!=i) {        fgets(line, MAXLINE, ficpar);
         fprintf(ficres,"%1d%1d",i,j);        numlinepar++;
         printf("%1d%1d",i,j);        puts(line);
         fprintf(ficlog,"%1d%1d",i,j);        fputs(line,ficparo);
         for(k=1; k<=ncovmodel;k++){        fputs(line,ficlog);
           printf(" %.5e",delti[jk]);      }
           fprintf(ficlog," %.5e",delti[jk]);      ungetc(c,ficpar);
           fprintf(ficres," %.5e",delti[jk]);  
           jk++;      for(i=1; i <=nlstate; i++){
         }        for(j=1; j <=nlstate+ndeath-1; j++){
         printf("\n");          fscanf(ficpar,"%1d%1d",&i1,&j1);
         fprintf(ficlog,"\n");          if ((i1-i)*(j1-j)!=0){
         fprintf(ficres,"\n");            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
       }            exit(1);
     }          }
   }          printf("%1d%1d",i,j);
              fprintf(ficparo,"%1d%1d",i1,j1);
   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");          fprintf(ficlog,"%1d%1d",i1,j1);
   if(mle==1)          for(k=1; k<=ncovmodel;k++){
     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");            fscanf(ficpar,"%le",&delti3[i][j][k]);
   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");            printf(" %le",delti3[i][j][k]);
   for(i=1,k=1;i<=npar;i++){            fprintf(ficparo," %le",delti3[i][j][k]);
     /*  if (k>nlstate) k=1;            fprintf(ficlog," %le",delti3[i][j][k]);
         i1=(i-1)/(ncovmodel*nlstate)+1;           }
         fprintf(ficres,"%s%d%d",alph[k],i1,tab[i]);          fscanf(ficpar,"\n");
         printf("%s%d%d",alph[k],i1,tab[i]);          numlinepar++;
     */          printf("\n");
     fprintf(ficres,"%3d",i);          fprintf(ficparo,"\n");
     if(mle==1)          fprintf(ficlog,"\n");
       printf("%3d",i);        }
     fprintf(ficlog,"%3d",i);      }
     for(j=1; j<=i;j++){      fflush(ficlog);
       fprintf(ficres," %.5e",matcov[i][j]);  
       if(mle==1)      delti=delti3[1][1];
         printf(" %.5e",matcov[i][j]);  
       fprintf(ficlog," %.5e",matcov[i][j]);  
     }      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
     fprintf(ficres,"\n");   
     if(mle==1)      /* Reads comments: lines beginning with '#' */
       printf("\n");      while((c=getc(ficpar))=='#' && c!= EOF){
     fprintf(ficlog,"\n");        ungetc(c,ficpar);
     k++;        fgets(line, MAXLINE, ficpar);
   }        numlinepar++;
            puts(line);
   while((c=getc(ficpar))=='#' && c!= EOF){        fputs(line,ficparo);
     ungetc(c,ficpar);        fputs(line,ficlog);
     fgets(line, MAXLINE, ficpar);      }
     puts(line);      ungetc(c,ficpar);
     fputs(line,ficparo);   
   }      matcov=matrix(1,npar,1,npar);
   ungetc(c,ficpar);      for(i=1; i <=npar; i++){
         fscanf(ficpar,"%s",&str);
   estepm=0;        if(mle==1)
   fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);          printf("%s",str);
   if (estepm==0 || estepm < stepm) estepm=stepm;        fprintf(ficlog,"%s",str);
   if (fage <= 2) {        fprintf(ficparo,"%s",str);
     bage = ageminpar;        for(j=1; j <=i; j++){
     fage = agemaxpar;          fscanf(ficpar," %le",&matcov[i][j]);
   }          if(mle==1){
                printf(" %.5le",matcov[i][j]);
   fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");          }
   fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);          fprintf(ficlog," %.5le",matcov[i][j]);
   fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);          fprintf(ficparo," %.5le",matcov[i][j]);
            }
   while((c=getc(ficpar))=='#' && c!= EOF){        fscanf(ficpar,"\n");
     ungetc(c,ficpar);        numlinepar++;
     fgets(line, MAXLINE, ficpar);        if(mle==1)
     puts(line);          printf("\n");
     fputs(line,ficparo);        fprintf(ficlog,"\n");
   }        fprintf(ficparo,"\n");
   ungetc(c,ficpar);      }
         for(i=1; i <=npar; i++)
   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);        for(j=i+1;j<=npar;j++)
   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);          matcov[i][j]=matcov[j][i];
   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);     
   printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);      if(mle==1)
   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);        printf("\n");
          fprintf(ficlog,"\n");
   while((c=getc(ficpar))=='#' && c!= EOF){     
     ungetc(c,ficpar);      fflush(ficlog);
     fgets(line, MAXLINE, ficpar);     
     puts(line);      /*-------- Rewriting parameter file ----------*/
     fputs(line,ficparo);      strcpy(rfileres,"r");    /* "Rparameterfile */
   }      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
   ungetc(c,ficpar);      strcat(rfileres,".");    /* */
        strcat(rfileres,optionfilext);    /* Other files have txt extension */
       if((ficres =fopen(rfileres,"w"))==NULL) {
   dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;        printf("Problem writing new parameter file: %s\n", fileres);goto end;
   dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
       }
   fscanf(ficpar,"pop_based=%d\n",&popbased);      fprintf(ficres,"#%s\n",version);
   fprintf(ficparo,"pop_based=%d\n",popbased);       }    /* End of mle != -3 */
   fprintf(ficres,"pop_based=%d\n",popbased);     
       /*-------- data file ----------*/
   while((c=getc(ficpar))=='#' && c!= EOF){    if((fic=fopen(datafile,"r"))==NULL)    {
     ungetc(c,ficpar);      printf("Problem while opening datafile: %s\n", datafile);goto end;
     fgets(line, MAXLINE, ficpar);      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
     puts(line);    }
     fputs(line,ficparo);  
   }    n= lastobs;
   ungetc(c,ficpar);    severity = vector(1,maxwav);
     outcome=imatrix(1,maxwav+1,1,n);
   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);    num=lvector(1,n);
   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);    moisnais=vector(1,n);
   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);    annais=vector(1,n);
   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);    moisdc=vector(1,n);
   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);    andc=vector(1,n);
   /* day and month of proj2 are not used but only year anproj2.*/    agedc=vector(1,n);
     cod=ivector(1,n);
   while((c=getc(ficpar))=='#' && c!= EOF){    weight=vector(1,n);
     ungetc(c,ficpar);    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
     fgets(line, MAXLINE, ficpar);    mint=matrix(1,maxwav,1,n);
     puts(line);    anint=matrix(1,maxwav,1,n);
     fputs(line,ficparo);    s=imatrix(1,maxwav+1,1,n);
   }    tab=ivector(1,NCOVMAX);
   ungetc(c,ficpar);    ncodemax=ivector(1,8);
   
   fscanf(ficpar,"popforecast=%d popfile=%s popfiledate=%lf/%lf/%lf last-popfiledate=%lf/%lf/%lf\n",&popforecast,popfile,&jpyram,&mpyram,&anpyram,&jpyram1,&mpyram1,&anpyram1);    i=1;
   fprintf(ficparo,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);    linei=0;
   fprintf(ficres,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
       linei=linei+1;
   /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
   /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/        if(line[j] == '\t')
           line[j] = ' ';
   replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */      }
   printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
         ;
   printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\      };
                model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\      line[j+1]=0;  /* Trims blanks at end of line */
                jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);      if(line[0]=='#'){
          fprintf(ficlog,"Comment line\n%s\n",line);
   /*------------ free_vector  -------------*/        printf("Comment line\n%s\n",line);
   /*  chdir(path); */        continue;
        }
   free_ivector(wav,1,imx);  
   free_imatrix(dh,1,lastpass-firstpass+1,1,imx);      for (j=maxwav;j>=1;j--){
   free_imatrix(bh,1,lastpass-firstpass+1,1,imx);        cutv(stra, strb,line,' ');
   free_imatrix(mw,1,lastpass-firstpass+1,1,imx);           errno=0;
   free_lvector(num,1,n);        lval=strtol(strb,&endptr,10);
   free_vector(agedc,1,n);        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
   /*free_matrix(covar,0,NCOVMAX,1,n);*/        if( strb[0]=='\0' || (*endptr != '\0')){
   /*free_matrix(covar,1,NCOVMAX,1,n);*/          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);
   fclose(ficparo);          exit(1);
   fclose(ficres);        }
         s[j][i]=lval;
        
   /*--------------- Prevalence limit  (stable prevalence) --------------*/        strcpy(line,stra);
           cutv(stra, strb,line,' ');
   strcpy(filerespl,"pl");        if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
   strcat(filerespl,fileres);        }
   if((ficrespl=fopen(filerespl,"w"))==NULL) {        else  if(iout=sscanf(strb,"%s.") != 0){
     printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;          month=99;
     fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;          year=9999;
   }        }else{
   printf("Computing stable prevalence: result on file '%s' \n", filerespl);          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);
   fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);          exit(1);
   fprintf(ficrespl,"#Stable prevalence \n");        }
   fprintf(ficrespl,"#Age ");        anint[j][i]= (double) year;
   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);        mint[j][i]= (double)month;
   fprintf(ficrespl,"\n");        strcpy(line,stra);
         } /* ENd Waves */
   prlim=matrix(1,nlstate,1,nlstate);     
       cutv(stra, strb,line,' ');
   agebase=ageminpar;      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
   agelim=agemaxpar;      }
   ftolpl=1.e-10;      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
   i1=cptcoveff;        month=99;
   if (cptcovn < 1){i1=1;}        year=9999;
       }else{
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){        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);
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){        exit(1);
       k=k+1;      }
       /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/      andc[i]=(double) year;
       fprintf(ficrespl,"\n#******");      moisdc[i]=(double) month;
       printf("\n#******");      strcpy(line,stra);
       fprintf(ficlog,"\n#******");     
       for(j=1;j<=cptcoveff;j++) {      cutv(stra, strb,line,' ');
         fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
         printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      }
         fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      else  if(iout=sscanf(strb,"%s.") != 0){
       }        month=99;
       fprintf(ficrespl,"******\n");        year=9999;
       printf("******\n");      }else{
       fprintf(ficlog,"******\n");        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);
                 exit(1);
       for (age=agebase; age<=agelim; age++){      }
         prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      annais[i]=(double)(year);
         fprintf(ficrespl,"%.0f ",age );      moisnais[i]=(double)(month);
         for(j=1;j<=cptcoveff;j++)      strcpy(line,stra);
           fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);     
         for(i=1; i<=nlstate;i++)      cutv(stra, strb,line,' ');
           fprintf(ficrespl," %.5f", prlim[i][i]);      errno=0;
         fprintf(ficrespl,"\n");      dval=strtod(strb,&endptr);
       }      if( strb[0]=='\0' || (*endptr != '\0')){
     }        printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
   }        exit(1);
   fclose(ficrespl);      }
       weight[i]=dval;
   /*------------- h Pij x at various ages ------------*/      strcpy(line,stra);
        
   strcpy(filerespij,"pij");  strcat(filerespij,fileres);      for (j=ncovcol;j>=1;j--){
   if((ficrespij=fopen(filerespij,"w"))==NULL) {        cutv(stra, strb,line,' ');
     printf("Problem with Pij resultfile: %s\n", filerespij);goto end;        errno=0;
     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;        lval=strtol(strb,&endptr,10);
   }        if( strb[0]=='\0' || (*endptr != '\0')){
   printf("Computing pij: result on file '%s' \n", filerespij);          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);
   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);          exit(1);
           }
   stepsize=(int) (stepm+YEARM-1)/YEARM;        if(lval <-1 || lval >1){
   /*if (stepm<=24) stepsize=2;*/          printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
    Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
   agelim=AGESUP;   for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
   hstepm=stepsize*YEARM; /* Every year of age */   For example, for multinomial values like 1, 2 and 3,\n \
   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */    build V1=0 V2=0 for the reference value (1),\n \
           V1=1 V2=0 for (2) \n \
   /* hstepm=1;   aff par mois*/   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
    output of IMaCh is often meaningless.\n \
   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");   Exiting.\n",lval,linei, i,line,j);
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){          exit(1);
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){        }
       k=k+1;        covar[j][i]=(double)(lval);
       fprintf(ficrespij,"\n#****** ");        strcpy(line,stra);
       for(j=1;j<=cptcoveff;j++)       }
         fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      lstra=strlen(stra);
       fprintf(ficrespij,"******\n");     
               if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */        stratrunc = &(stra[lstra-9]);
         nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */         num[i]=atol(stratrunc);
         nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */      }
       else
         /*        nhstepm=nhstepm*YEARM; aff par mois*/        num[i]=atol(stra);
       /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
         p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        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;}*/
         oldm=oldms;savm=savms;     
         hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        i=i+1;
         fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");    } /* End loop reading  data */
         for(i=1; i<=nlstate;i++)    fclose(fic);
           for(j=1; j<=nlstate+ndeath;j++)    /* printf("ii=%d", ij);
             fprintf(ficrespij," %1d-%1d",i,j);       scanf("%d",i);*/
         fprintf(ficrespij,"\n");    imx=i-1; /* Number of individuals */
         for (h=0; h<=nhstepm; h++){  
           fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );    /* for (i=1; i<=imx; i++){
           for(i=1; i<=nlstate;i++)      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
             for(j=1; j<=nlstate+ndeath;j++)      if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
               fprintf(ficrespij," %.5f", p3mat[i][j][h]);      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
           fprintf(ficrespij,"\n");      }*/
         }     /*  for (i=1; i<=imx; i++){
         free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);       if (s[4][i]==9)  s[4][i]=-1;
         fprintf(ficrespij,"\n");       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]));}*/
       }   
     }    /* for (i=1; i<=imx; i++) */
   }   
      /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
   varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax);       else weight[i]=1;*/
   
   fclose(ficrespij);    /* Calculation of the number of parameters from char model */
     Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
   probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);    Tprod=ivector(1,15);
     Tvaraff=ivector(1,15);
   /*---------- Forecasting ------------------*/    Tvard=imatrix(1,15,1,2);
   /*if((stepm == 1) && (strcmp(model,".")==0)){*/    Tage=ivector(1,15);      
   if(prevfcast==1){     
     /*    if(stepm ==1){*/    if (strlen(model) >1){ /* If there is at least 1 covariate */
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);      j=0, j1=0, k1=1, k2=1;
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/      j=nbocc(model,'+'); /* j=Number of '+' */
 /*      }  */      j1=nbocc(model,'*'); /* j1=Number of '*' */
 /*      else{ */      cptcovn=j+1;
 /*        erreur=108; */      cptcovprod=j1; /*Number of products */
 /*        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); */     
 /*        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); */      strcpy(modelsav,model);
 /*      } */      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
   }        printf("Error. Non available option model=%s ",model);
           fprintf(ficlog,"Error. Non available option model=%s ",model);
         goto end;
   /*---------- Health expectancies and variances ------------*/      }
      
   strcpy(filerest,"t");      /* This loop fills the array Tvar from the string 'model'.*/
   strcat(filerest,fileres);  
   if((ficrest=fopen(filerest,"w"))==NULL) {      for(i=(j+1); i>=1;i--){
     printf("Problem with total LE resultfile: %s\n", filerest);goto end;        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
     fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
   }        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
   printf("Computing Total LEs with variances: file '%s' \n", filerest);         /*scanf("%d",i);*/
   fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest);         if (strchr(strb,'*')) {  /* Model includes a product */
           cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
           if (strcmp(strc,"age")==0) { /* Vn*age */
   strcpy(filerese,"e");            cptcovprod--;
   strcat(filerese,fileres);            cutv(strb,stre,strd,'V');
   if((ficreseij=fopen(filerese,"w"))==NULL) {            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
     printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);            cptcovage++;
     fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);              Tage[cptcovage]=i;
   }              /*printf("stre=%s ", stre);*/
   printf("Computing Health Expectancies: result on file '%s' \n", filerese);          }
   fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);          else if (strcmp(strd,"age")==0) { /* or age*Vn */
             cptcovprod--;
   strcpy(fileresv,"v");            cutv(strb,stre,strc,'V');
   strcat(fileresv,fileres);            Tvar[i]=atoi(stre);
   if((ficresvij=fopen(fileresv,"w"))==NULL) {            cptcovage++;
     printf("Problem with variance resultfile: %s\n", fileresv);exit(0);            Tage[cptcovage]=i;
     fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);          }
   }          else {  /* Age is not in the model */
   printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
   fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);            Tvar[i]=ncovcol+k1;
             cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
   /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */            Tprod[k1]=i;
   prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);            Tvard[k1][1]=atoi(strc); /* m*/
   /*  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",\            Tvard[k1][2]=atoi(stre); /* n */
 ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);            Tvar[cptcovn+k2]=Tvard[k1][1];
   */            Tvar[cptcovn+k2+1]=Tvard[k1][2];
             for (k=1; k<=lastobs;k++)
   if (mobilav!=0) {              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            k1++;
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){            k2=k2+2;
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);          }
       printf(" Error in movingaverage mobilav=%d\n",mobilav);        }
     }        else { /* no more sum */
   }          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
          /*  scanf("%d",i);*/
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){        cutv(strd,strc,strb,'V');
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){        Tvar[i]=atoi(strc);
       k=k+1;         }
       fprintf(ficrest,"\n#****** ");        strcpy(modelsav,stra);  
       for(j=1;j<=cptcoveff;j++)         /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
         fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          scanf("%d",i);*/
       fprintf(ficrest,"******\n");      } /* end of loop + */
     } /* end model */
       fprintf(ficreseij,"\n#****** ");   
       for(j=1;j<=cptcoveff;j++)     /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
         fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
       fprintf(ficreseij,"******\n");  
     /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
       fprintf(ficresvij,"\n#****** ");    printf("cptcovprod=%d ", cptcovprod);
       for(j=1;j<=cptcoveff;j++)     fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
         fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
       fprintf(ficresvij,"******\n");    scanf("%d ",i);*/
   
       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      /*  if(mle==1){*/
       oldm=oldms;savm=savms;    if (weightopt != 1) { /* Maximisation without weights*/
       evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov);        for(i=1;i<=n;i++) weight[i]=1.0;
      }
       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      /*-calculation of age at interview from date of interview and age at death -*/
       oldm=oldms;savm=savms;    agev=matrix(1,maxwav,1,imx);
       varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav);  
       if(popbased==1){    for (i=1; i<=imx; i++) {
         varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav);      for(m=2; (m<= maxwav); m++) {
       }        if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
           anint[m][i]=9999;
            s[m][i]=-1;
       fprintf(ficrest,"#Total LEs with variances: e.. (std) ");        }
       for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
       fprintf(ficrest,"\n");          nberr++;
           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);
       epj=vector(1,nlstate+1);          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);
       for(age=bage; age <=fage ;age++){          s[m][i]=-1;
         prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);        }
         if (popbased==1) {        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
           if(mobilav ==0){          nberr++;
             for(i=1; i<=nlstate;i++)          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]);
               prlim[i][i]=probs[(int)age][i][k];          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]);
           }else{ /* mobilav */           s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
             for(i=1; i<=nlstate;i++)        }
               prlim[i][i]=mobaverage[(int)age][i][k];      }
           }    }
         }  
             for (i=1; i<=imx; i++)  {
         fprintf(ficrest," %4.0f",age);      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
         for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){      for(m=firstpass; (m<= lastpass); m++){
           for(i=1, epj[j]=0.;i <=nlstate;i++) {        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
             epj[j] += prlim[i][i]*eij[i][j][(int)age];          if (s[m][i] >= nlstate+1) {
             /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/            if(agedc[i]>0)
           }              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
           epj[nlstate+1] +=epj[j];                agev[m][i]=agedc[i];
         }            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
               else {
         for(i=1, vepp=0.;i <=nlstate;i++)                if ((int)andc[i]!=9999){
           for(j=1;j <=nlstate;j++)                  nbwarn++;
             vepp += vareij[i][j][(int)age];                  printf("Warning negative age at death: %ld line:%d\n",num[i],i);
         fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
         for(j=1;j <=nlstate;j++){                  agev[m][i]=-1;
           fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));                }
         }              }
         fprintf(ficrest,"\n");          }
       }          else if(s[m][i] !=9){ /* Standard case, age in fractional
       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);                                   years but with the precision of a month */
       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
       free_vector(epj,1,nlstate+1);            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
     }              agev[m][i]=1;
   }            else if(agev[m][i] <agemin){
   free_vector(weight,1,n);              agemin=agev[m][i];
   free_imatrix(Tvard,1,15,1,2);              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
   free_imatrix(s,1,maxwav+1,1,n);            }
   free_matrix(anint,1,maxwav,1,n);             else if(agev[m][i] >agemax){
   free_matrix(mint,1,maxwav,1,n);              agemax=agev[m][i];
   free_ivector(cod,1,n);              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
   free_ivector(tab,1,NCOVMAX);            }
   fclose(ficreseij);            /*agev[m][i]=anint[m][i]-annais[i];*/
   fclose(ficresvij);            /*     agev[m][i] = age[i]+2*m;*/
   fclose(ficrest);          }
   fclose(ficpar);          else { /* =9 */
               agev[m][i]=1;
   /*------- Variance of stable prevalence------*/               s[m][i]=-1;
           }
   strcpy(fileresvpl,"vpl");        }
   strcat(fileresvpl,fileres);        else /*= 0 Unknown */
   if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {          agev[m][i]=1;
     printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);      }
     exit(0);     
   }    }
   printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);    for (i=1; i<=imx; i++)  {
       for(m=firstpass; (m<=lastpass); m++){
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){        if (s[m][i] > (nlstate+ndeath)) {
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){          nberr++;
       k=k+1;          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);    
       fprintf(ficresvpl,"\n#****** ");          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);    
       for(j=1;j<=cptcoveff;j++)           goto end;
         fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        }
       fprintf(ficresvpl,"******\n");      }
           }
       varpl=matrix(1,nlstate,(int) bage, (int) fage);  
       oldm=oldms;savm=savms;    /*for (i=1; i<=imx; i++){
       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k);    for (m=firstpass; (m<lastpass); m++){
       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
     }  }
   }  
   }*/
   fclose(ficresvpl);  
   
   /*---------- End : free ----------------*/    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
   free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);  
   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);    agegomp=(int)agemin;
   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);    free_vector(severity,1,maxwav);
       free_imatrix(outcome,1,maxwav+1,1,n);
   free_matrix(covar,0,NCOVMAX,1,n);    free_vector(moisnais,1,n);
   free_matrix(matcov,1,npar,1,npar);    free_vector(annais,1,n);
   /*free_vector(delti,1,npar);*/    /* free_matrix(mint,1,maxwav,1,n);
   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);        free_matrix(anint,1,maxwav,1,n);*/
   free_matrix(agev,1,maxwav,1,imx);    free_vector(moisdc,1,n);
   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);    free_vector(andc,1,n);
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  
   free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);     
     wav=ivector(1,imx);
   free_ivector(ncodemax,1,8);    dh=imatrix(1,lastpass-firstpass+1,1,imx);
   free_ivector(Tvar,1,15);    bh=imatrix(1,lastpass-firstpass+1,1,imx);
   free_ivector(Tprod,1,15);    mw=imatrix(1,lastpass-firstpass+1,1,imx);
   free_ivector(Tvaraff,1,15);     
   free_ivector(Tage,1,15);    /* Concatenates waves */
   free_ivector(Tcode,1,100);    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
   
   fflush(fichtm);    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
   fflush(ficgp);  
       Tcode=ivector(1,100);
     nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
   if((nberr >0) || (nbwarn>0)){    ncodemax[1]=1;
     printf("End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);       
   }else{    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
     printf("End of Imach\n");                                   the estimations*/
     fprintf(ficlog,"End of Imach\n");    h=0;
   }    m=pow(2,cptcoveff);
   printf("See log file on %s\n",filelog);   
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */    for(k=1;k<=cptcoveff; k++){
   (void) gettimeofday(&end_time,&tzp);      for(i=1; i <=(m/pow(2,k));i++){
   tm = *localtime(&end_time.tv_sec);        for(j=1; j <= ncodemax[k]; j++){
   tmg = *gmtime(&end_time.tv_sec);          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
   strcpy(strtend,asctime(&tm));            h++;
   printf("Localtime at start %s\nLocaltime at end   %s",strstart, strtend);             if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
   fprintf(ficlog,"Localtime at start %s\nLocal time at end   %s\n",strstart, strtend);             /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));          }
         }
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      }
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));    }
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
   /*  printf("Total time was %d uSec.\n", total_usecs);*/       codtab[1][2]=1;codtab[2][2]=2; */
 /*   if(fileappend(fichtm,optionfilehtm)){ */    /* for(i=1; i <=m ;i++){
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);       for(k=1; k <=cptcovn; k++){
   fclose(fichtm);       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
   fclose(fichtmcov);       }
   fclose(ficgp);       printf("\n");
   fclose(ficlog);       }
   /*------ End -----------*/       scanf("%d",i);*/
      
   chdir(path);    /*------------ gnuplot -------------*/
   strcpy(plotcmd,GNUPLOTPROGRAM);    strcpy(optionfilegnuplot,optionfilefiname);
   strcat(plotcmd," ");    if(mle==-3)
   strcat(plotcmd,optionfilegnuplot);      strcat(optionfilegnuplot,"-mort");
   printf("Starting graphs with: %s",plotcmd);fflush(stdout);    strcat(optionfilegnuplot,".gp");
   if((outcmd=system(plotcmd)) != 0){  
     printf(" Problem with gnuplot\n");    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
   }      printf("Problem with file %s",optionfilegnuplot);
   printf(" Wait...");    }
   while (z[0] != 'q') {    else{
     /* chdir(path); */      fprintf(ficgp,"\n# %s\n", version);
     printf("\nType e to edit output files, g to graph again and q for exiting: ");      fprintf(ficgp,"# %s\n", optionfilegnuplot);
     scanf("%s",z);      fprintf(ficgp,"set missing 'NaNq'\n");
 /*     if (z[0] == 'c') system("./imach"); */    }
     if (z[0] == 'e') system(optionfilehtm);    /*  fclose(ficgp);*/
     else if (z[0] == 'g') system(plotcmd);    /*--------- index.htm --------*/
     else if (z[0] == 'q') exit(0);  
   }    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
   end:    if(mle==-3)
   while (z[0] != 'q') {      strcat(optionfilehtm,"-mort");
     printf("\nType  q for exiting: ");    strcat(optionfilehtm,".htm");
     scanf("%s",z);    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
   }      printf("Problem with %s \n",optionfilehtm), exit(0);
 }    }
   
     strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
     strcat(optionfilehtmcov,"-cov.htm");
     if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
       printf("Problem with %s \n",optionfilehtmcov), exit(0);
     }
     else{
     fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
   <hr size=\"2\" color=\"#EC5E5E\"> \n\
   Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
             optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
     }
   
     fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
   <hr size=\"2\" color=\"#EC5E5E\"> \n\
   Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
   \n\
   <hr  size=\"2\" color=\"#EC5E5E\">\
    <ul><li><h4>Parameter files</h4>\n\
    - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
    - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
    - Log file of the run: <a href=\"%s\">%s</a><br>\n\
    - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
    - Date and time at start: %s</ul>\n",\
             optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
             optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
             fileres,fileres,\
             filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
     fflush(fichtm);
   
     strcpy(pathr,path);
     strcat(pathr,optionfilefiname);
     chdir(optionfilefiname); /* Move to directory named optionfile */
    
     /* Calculates basic frequencies. Computes observed prevalence at single age
        and prints on file fileres'p'. */
     freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
   
     fprintf(fichtm,"\n");
     fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
   Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
   Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
             imx,agemin,agemax,jmin,jmax,jmean);
     pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
      
      
     /* For Powell, parameters are in a vector p[] starting at p[1]
        so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
     p=param[1][1]; /* *(*(*(param +1)+1)+0) */
   
     globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
   
     if (mle==-3){
       ximort=matrix(1,NDIM,1,NDIM);
       cens=ivector(1,n);
       ageexmed=vector(1,n);
       agecens=vector(1,n);
       dcwave=ivector(1,n);
    
       for (i=1; i<=imx; i++){
         dcwave[i]=-1;
         for (m=firstpass; m<=lastpass; m++)
           if (s[m][i]>nlstate) {
             dcwave[i]=m;
             /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
             break;
           }
       }
   
       for (i=1; i<=imx; i++) {
         if (wav[i]>0){
           ageexmed[i]=agev[mw[1][i]][i];
           j=wav[i];
           agecens[i]=1.;
   
           if (ageexmed[i]> 1 && wav[i] > 0){
             agecens[i]=agev[mw[j][i]][i];
             cens[i]= 1;
           }else if (ageexmed[i]< 1)
             cens[i]= -1;
           if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
             cens[i]=0 ;
         }
         else cens[i]=-1;
       }
      
       for (i=1;i<=NDIM;i++) {
         for (j=1;j<=NDIM;j++)
           ximort[i][j]=(i == j ? 1.0 : 0.0);
       }
      
       p[1]=0.0268; p[NDIM]=0.083;
       /*printf("%lf %lf", p[1], p[2]);*/
      
      
       printf("Powell\n");  fprintf(ficlog,"Powell\n");
       strcpy(filerespow,"pow-mort");
       strcat(filerespow,fileres);
       if((ficrespow=fopen(filerespow,"w"))==NULL) {
         printf("Problem with resultfile: %s\n", filerespow);
         fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
       }
       fprintf(ficrespow,"# Powell\n# iter -2*LL");
       /*  for (i=1;i<=nlstate;i++)
           for(j=1;j<=nlstate+ndeath;j++)
           if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
       */
       fprintf(ficrespow,"\n");
      
       powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
       fclose(ficrespow);
      
       hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
   
       for(i=1; i <=NDIM; i++)
         for(j=i+1;j<=NDIM;j++)
           matcov[i][j]=matcov[j][i];
      
       printf("\nCovariance matrix\n ");
       for(i=1; i <=NDIM; i++) {
         for(j=1;j<=NDIM;j++){
           printf("%f ",matcov[i][j]);
         }
         printf("\n ");
       }
      
       printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
       for (i=1;i<=NDIM;i++)
         printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
   
       lsurv=vector(1,AGESUP);
       lpop=vector(1,AGESUP);
       tpop=vector(1,AGESUP);
       lsurv[agegomp]=100000;
      
       for (k=agegomp;k<=AGESUP;k++) {
         agemortsup=k;
         if (p[1]*exp(p[2]*(k-agegomp))>1) break;
       }
      
       for (k=agegomp;k<agemortsup;k++)
         lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
      
       for (k=agegomp;k<agemortsup;k++){
         lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
         sumlpop=sumlpop+lpop[k];
       }
      
       tpop[agegomp]=sumlpop;
       for (k=agegomp;k<(agemortsup-3);k++){
         /*  tpop[k+1]=2;*/
         tpop[k+1]=tpop[k]-lpop[k];
       }
      
      
       printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
       for (k=agegomp;k<(agemortsup-2);k++)
         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]);
      
      
       replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
       printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
      
       printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                        stepm, weightopt,\
                        model,imx,p,matcov,agemortsup);
      
       free_vector(lsurv,1,AGESUP);
       free_vector(lpop,1,AGESUP);
       free_vector(tpop,1,AGESUP);
     } /* Endof if mle==-3 */
    
     else{ /* For mle >=1 */
    
       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
       printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
       for (k=1; k<=npar;k++)
         printf(" %d %8.5f",k,p[k]);
       printf("\n");
       globpr=1; /* to print the contributions */
       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
       printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
       for (k=1; k<=npar;k++)
         printf(" %d %8.5f",k,p[k]);
       printf("\n");
       if(mle>=1){ /* Could be 1 or 2 */
         mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
       }
      
       /*--------- results files --------------*/
       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);
      
      
       fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       for(i=1,jk=1; i <=nlstate; i++){
         for(k=1; k <=(nlstate+ndeath); k++){
           if (k != i) {
             printf("%d%d ",i,k);
             fprintf(ficlog,"%d%d ",i,k);
             fprintf(ficres,"%1d%1d ",i,k);
             for(j=1; j <=ncovmodel; j++){
               printf("%lf ",p[jk]);
               fprintf(ficlog,"%lf ",p[jk]);
               fprintf(ficres,"%lf ",p[jk]);
               jk++;
             }
             printf("\n");
             fprintf(ficlog,"\n");
             fprintf(ficres,"\n");
           }
         }
       }
       if(mle!=0){
         /* Computing hessian and covariance matrix */
         ftolhess=ftol; /* Usually correct */
         hesscov(matcov, p, npar, delti, ftolhess, func);
       }
       fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
       printf("# Scales (for hessian or gradient estimation)\n");
       fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
       for(i=1,jk=1; i <=nlstate; i++){
         for(j=1; j <=nlstate+ndeath; j++){
           if (j!=i) {
             fprintf(ficres,"%1d%1d",i,j);
             printf("%1d%1d",i,j);
             fprintf(ficlog,"%1d%1d",i,j);
             for(k=1; k<=ncovmodel;k++){
               printf(" %.5e",delti[jk]);
               fprintf(ficlog," %.5e",delti[jk]);
               fprintf(ficres," %.5e",delti[jk]);
               jk++;
             }
             printf("\n");
             fprintf(ficlog,"\n");
             fprintf(ficres,"\n");
           }
         }
       }
      
       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");
       if(mle>=1)
         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");
       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");
       /* # 121 Var(a12)\n\ */
       /* # 122 Cov(b12,a12) Var(b12)\n\ */
       /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
       /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
       /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
       /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
       /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
       /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
      
      
       /* Just to have a covariance matrix which will be more understandable
          even is we still don't want to manage dictionary of variables
       */
       for(itimes=1;itimes<=2;itimes++){
         jj=0;
         for(i=1; i <=nlstate; i++){
           for(j=1; j <=nlstate+ndeath; j++){
             if(j==i) continue;
             for(k=1; k<=ncovmodel;k++){
               jj++;
               ca[0]= k+'a'-1;ca[1]='\0';
               if(itimes==1){
                 if(mle>=1)
                   printf("#%1d%1d%d",i,j,k);
                 fprintf(ficlog,"#%1d%1d%d",i,j,k);
                 fprintf(ficres,"#%1d%1d%d",i,j,k);
               }else{
                 if(mle>=1)
                   printf("%1d%1d%d",i,j,k);
                 fprintf(ficlog,"%1d%1d%d",i,j,k);
                 fprintf(ficres,"%1d%1d%d",i,j,k);
               }
               ll=0;
               for(li=1;li <=nlstate; li++){
                 for(lj=1;lj <=nlstate+ndeath; lj++){
                   if(lj==li) continue;
                   for(lk=1;lk<=ncovmodel;lk++){
                     ll++;
                     if(ll<=jj){
                       cb[0]= lk +'a'-1;cb[1]='\0';
                       if(ll<jj){
                         if(itimes==1){
                           if(mle>=1)
                             printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                           fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                           fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                         }else{
                           if(mle>=1)
                             printf(" %.5e",matcov[jj][ll]);
                           fprintf(ficlog," %.5e",matcov[jj][ll]);
                           fprintf(ficres," %.5e",matcov[jj][ll]);
                         }
                       }else{
                         if(itimes==1){
                           if(mle>=1)
                             printf(" Var(%s%1d%1d)",ca,i,j);
                           fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                           fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                         }else{
                           if(mle>=1)
                             printf(" %.5e",matcov[jj][ll]);
                           fprintf(ficlog," %.5e",matcov[jj][ll]);
                           fprintf(ficres," %.5e",matcov[jj][ll]);
                         }
                       }
                     }
                   } /* end lk */
                 } /* end lj */
               } /* end li */
               if(mle>=1)
                 printf("\n");
               fprintf(ficlog,"\n");
               fprintf(ficres,"\n");
               numlinepar++;
             } /* end k*/
           } /*end j */
         } /* end i */
       } /* end itimes */
      
       fflush(ficlog);
       fflush(ficres);
      
       while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
         puts(line);
         fputs(line,ficparo);
       }
       ungetc(c,ficpar);
      
       estepm=0;
       fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
       if (estepm==0 || estepm < stepm) estepm=stepm;
       if (fage <= 2) {
         bage = ageminpar;
         fage = agemaxpar;
       }
      
       fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
       fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
       fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
      
       while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
         puts(line);
         fputs(line,ficparo);
       }
       ungetc(c,ficpar);
      
       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);
       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);
       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);
       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
       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);
      
       while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
         puts(line);
         fputs(line,ficparo);
       }
       ungetc(c,ficpar);
      
      
       dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
       dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
      
       fscanf(ficpar,"pop_based=%d\n",&popbased);
       fprintf(ficparo,"pop_based=%d\n",popbased);  
       fprintf(ficres,"pop_based=%d\n",popbased);  
      
       while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
         puts(line);
         fputs(line,ficparo);
       }
       ungetc(c,ficpar);
      
       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);
       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);
       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);
       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);
       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);
       /* day and month of proj2 are not used but only year anproj2.*/
      
      
      
       /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
       /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
      
       replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
       printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
      
       printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                    model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                    jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
        
      /*------------ free_vector  -------------*/
      /*  chdir(path); */
    
       free_ivector(wav,1,imx);
       free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
       free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
       free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
       free_lvector(num,1,n);
       free_vector(agedc,1,n);
       /*free_matrix(covar,0,NCOVMAX,1,n);*/
       /*free_matrix(covar,1,NCOVMAX,1,n);*/
       fclose(ficparo);
       fclose(ficres);
   
   
       /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
    
       strcpy(filerespl,"pl");
       strcat(filerespl,fileres);
       if((ficrespl=fopen(filerespl,"w"))==NULL) {
         printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
         fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
       }
       printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
       fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
       pstamp(ficrespl);
       fprintf(ficrespl,"# Period (stable) prevalence \n");
       fprintf(ficrespl,"#Age ");
       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
       fprintf(ficrespl,"\n");
    
       prlim=matrix(1,nlstate,1,nlstate);
   
       agebase=ageminpar;
       agelim=agemaxpar;
       ftolpl=1.e-10;
       i1=cptcoveff;
       if (cptcovn < 1){i1=1;}
   
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
           fprintf(ficrespl,"\n#******");
           printf("\n#******");
           fprintf(ficlog,"\n#******");
           for(j=1;j<=cptcoveff;j++) {
             fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           }
           fprintf(ficrespl,"******\n");
           printf("******\n");
           fprintf(ficlog,"******\n");
          
           for (age=agebase; age<=agelim; age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
             fprintf(ficrespl,"%.0f ",age );
             for(j=1;j<=cptcoveff;j++)
               fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             for(i=1; i<=nlstate;i++)
               fprintf(ficrespl," %.5f", prlim[i][i]);
             fprintf(ficrespl,"\n");
           }
         }
       }
       fclose(ficrespl);
   
       /*------------- h Pij x at various ages ------------*/
    
       strcpy(filerespij,"pij");  strcat(filerespij,fileres);
       if((ficrespij=fopen(filerespij,"w"))==NULL) {
         printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
         fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
       }
       printf("Computing pij: result on file '%s' \n", filerespij);
       fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
    
       stepsize=(int) (stepm+YEARM-1)/YEARM;
       /*if (stepm<=24) stepsize=2;*/
   
       agelim=AGESUP;
       hstepm=stepsize*YEARM; /* Every year of age */
       hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
   
       /* hstepm=1;   aff par mois*/
       pstamp(ficrespij);
       fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           fprintf(ficrespij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrespij,"******\n");
          
           for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
             nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
   
             /*      nhstepm=nhstepm*YEARM; aff par mois*/
   
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             oldm=oldms;savm=savms;
             hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
             fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
             for(i=1; i<=nlstate;i++)
               for(j=1; j<=nlstate+ndeath;j++)
                 fprintf(ficrespij," %1d-%1d",i,j);
             fprintf(ficrespij,"\n");
             for (h=0; h<=nhstepm; h++){
               fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
               for(i=1; i<=nlstate;i++)
                 for(j=1; j<=nlstate+ndeath;j++)
                   fprintf(ficrespij," %.5f", p3mat[i][j][h]);
               fprintf(ficrespij,"\n");
             }
             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             fprintf(ficrespij,"\n");
           }
         }
       }
   
       varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
   
       fclose(ficrespij);
   
       probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
       for(i=1;i<=AGESUP;i++)
         for(j=1;j<=NCOVMAX;j++)
           for(k=1;k<=NCOVMAX;k++)
             probs[i][j][k]=0.;
   
       /*---------- Forecasting ------------------*/
       /*if((stepm == 1) && (strcmp(model,".")==0)){*/
       if(prevfcast==1){
         /*    if(stepm ==1){*/
         prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
         /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
         /*      }  */
         /*      else{ */
         /*        erreur=108; */
         /*        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); */
         /*        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); */
         /*      } */
       }
    
   
       /*---------- Health expectancies and variances ------------*/
   
       strcpy(filerest,"t");
       strcat(filerest,fileres);
       if((ficrest=fopen(filerest,"w"))==NULL) {
         printf("Problem with total LE resultfile: %s\n", filerest);goto end;
         fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
       }
       printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
       fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
   
   
       strcpy(filerese,"e");
       strcat(filerese,fileres);
       if((ficreseij=fopen(filerese,"w"))==NULL) {
         printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
         fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
       }
       printf("Computing Health Expectancies: result on file '%s' \n", filerese);
       fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
   
       strcpy(fileresstde,"stde");
       strcat(fileresstde,fileres);
       if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
         printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
         fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
       }
       printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
       fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
   
       strcpy(filerescve,"cve");
       strcat(filerescve,fileres);
       if((ficrescveij=fopen(filerescve,"w"))==NULL) {
         printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
         fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
       }
       printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
       fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
   
       strcpy(fileresv,"v");
       strcat(fileresv,fileres);
       if((ficresvij=fopen(fileresv,"w"))==NULL) {
         printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
         fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
       }
       printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
       fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
   
       /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
       prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
       /*  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",\
           ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
       */
   
       if (mobilav!=0) {
         mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
           fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
           printf(" Error in movingaverage mobilav=%d\n",mobilav);
         }
       }
   
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           fprintf(ficrest,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrest,"******\n");
   
           fprintf(ficreseij,"\n#****** ");
           fprintf(ficresstdeij,"\n#****** ");
           fprintf(ficrescveij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++) {
             fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           }
           fprintf(ficreseij,"******\n");
           fprintf(ficresstdeij,"******\n");
           fprintf(ficrescveij,"******\n");
   
           fprintf(ficresvij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficresvij,"******\n");
   
           eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
           evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
           cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
    
           vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);
           if(popbased==1){
             varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);
           }
   
           pstamp(ficrest);
           fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");
           for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
           fprintf(ficrest,"\n");
   
           epj=vector(1,nlstate+1);
           for(age=bage; age <=fage ;age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
             if (popbased==1) {
               if(mobilav ==0){
                 for(i=1; i<=nlstate;i++)
                   prlim[i][i]=probs[(int)age][i][k];
               }else{ /* mobilav */
                 for(i=1; i<=nlstate;i++)
                   prlim[i][i]=mobaverage[(int)age][i][k];
               }
             }
          
             fprintf(ficrest," %4.0f",age);
             for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
               for(i=1, epj[j]=0.;i <=nlstate;i++) {
                 epj[j] += prlim[i][i]*eij[i][j][(int)age];
                 /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
               }
               epj[nlstate+1] +=epj[j];
             }
   
             for(i=1, vepp=0.;i <=nlstate;i++)
               for(j=1;j <=nlstate;j++)
                 vepp += vareij[i][j][(int)age];
             fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
             for(j=1;j <=nlstate;j++){
               fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
             }
             fprintf(ficrest,"\n");
           }
           free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
           free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
           free_vector(epj,1,nlstate+1);
         }
       }
       free_vector(weight,1,n);
       free_imatrix(Tvard,1,15,1,2);
       free_imatrix(s,1,maxwav+1,1,n);
       free_matrix(anint,1,maxwav,1,n);
       free_matrix(mint,1,maxwav,1,n);
       free_ivector(cod,1,n);
       free_ivector(tab,1,NCOVMAX);
       fclose(ficreseij);
       fclose(ficresstdeij);
       fclose(ficrescveij);
       fclose(ficresvij);
       fclose(ficrest);
       fclose(ficpar);
    
       /*------- Variance of period (stable) prevalence------*/  
   
       strcpy(fileresvpl,"vpl");
       strcat(fileresvpl,fileres);
       if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
         printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
         exit(0);
       }
       printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
   
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           fprintf(ficresvpl,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficresvpl,"******\n");
        
           varpl=matrix(1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
           varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
           free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
         }
       }
   
       fclose(ficresvpl);
   
       /*---------- End : free ----------------*/
       if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
   
     }  /* mle==-3 arrives here for freeing */
     free_matrix(prlim,1,nlstate,1,nlstate);
       free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(covar,0,NCOVMAX,1,n);
       free_matrix(matcov,1,npar,1,npar);
       /*free_vector(delti,1,npar);*/
       free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
       free_matrix(agev,1,maxwav,1,imx);
       free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
   
       free_ivector(ncodemax,1,8);
       free_ivector(Tvar,1,15);
       free_ivector(Tprod,1,15);
       free_ivector(Tvaraff,1,15);
       free_ivector(Tage,1,15);
       free_ivector(Tcode,1,100);
   
       free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
       free_imatrix(codtab,1,100,1,10);
     fflush(fichtm);
     fflush(ficgp);
    
   
     if((nberr >0) || (nbwarn>0)){
       printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
       fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
     }else{
       printf("End of Imach\n");
       fprintf(ficlog,"End of Imach\n");
     }
     printf("See log file on %s\n",filelog);
     /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
     (void) gettimeofday(&end_time,&tzp);
     tm = *localtime(&end_time.tv_sec);
     tmg = *gmtime(&end_time.tv_sec);
     strcpy(strtend,asctime(&tm));
     printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);
     fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);
     printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
   
     printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     /*  printf("Total time was %d uSec.\n", total_usecs);*/
   /*   if(fileappend(fichtm,optionfilehtm)){ */
     fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     fclose(fichtm);
     fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     fclose(fichtmcov);
     fclose(ficgp);
     fclose(ficlog);
     /*------ End -----------*/
   
   
      printf("Before Current directory %s!\n",pathcd);
      if(chdir(pathcd) != 0)
       printf("Can't move to directory %s!\n",path);
     if(getcwd(pathcd,MAXLINE) > 0)
       printf("Current directory %s!\n",pathcd);
     /*strcat(plotcmd,CHARSEPARATOR);*/
     sprintf(plotcmd,"gnuplot");
   #ifndef UNIX
     sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
   #endif
     if(!stat(plotcmd,&info)){
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       if(!stat(getenv("GNUPLOTBIN"),&info)){
         printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #ifdef UNIX
       strcpy(plotcmd,GNUPLOTPROGRAM);
       if(!stat(plotcmd,&info)){
         printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #endif
     }else
       strcpy(pplotcmd,plotcmd);
    
     sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
     printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
   
     if((outcmd=system(plotcmd)) != 0){
       printf("\n Problem with gnuplot\n");
     }
     printf(" Wait...");
     while (z[0] != 'q') {
       /* chdir(path); */
       printf("\nType e to edit output files, g to graph again and q for exiting: ");
       scanf("%s",z);
   /*     if (z[0] == 'c') system("./imach"); */
       if (z[0] == 'e') {
         printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
         system(optionfilehtm);
       }
       else if (z[0] == 'g') system(plotcmd);
       else if (z[0] == 'q') exit(0);
     }
     end:
     while (z[0] != 'q') {
       printf("\nType  q for exiting: ");
       scanf("%s",z);
     }
   }
   
   
   

Removed from v.1.92  
changed lines
  Added in v.1.125


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