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

version 1.95, 2003/07/08 07:54:34 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.95  2003/07/08 07:54:34  brouard    Revision 1.125  2006/04/04 15:20:31  lievre
   * imach.c (Repository):    Errors in calculation of health expectancies. Age was not initialized.
   (Repository): Using imachwizard code to output a more meaningful covariance    Forecasting file added.
   matrix (cov(a12,c31) instead of numbers.  
     Revision 1.124  2006/03/22 17:13:53  lievre
   Revision 1.94  2003/06/27 13:00:02  brouard    Parameters are printed with %lf instead of %f (more numbers after the comma).
   Just cleaning    The log-likelihood is printed in the log file
   
   Revision 1.93  2003/06/25 16:33:55  brouard    Revision 1.123  2006/03/20 10:52:43  brouard
   (Module): On windows (cygwin) function asctime_r doesn't    * imach.c (Module): <title> changed, corresponds to .htm file
   exist so I changed back to asctime which exists.    name. <head> headers where missing.
   (Module): Version 0.96b  
     * imach.c (Module): Weights can have a decimal point as for
   Revision 1.92  2003/06/25 16:30:45  brouard    English (a comma might work with a correct LC_NUMERIC environment,
   (Module): On windows (cygwin) function asctime_r doesn't    otherwise the weight is truncated).
   exist so I changed back to asctime which exists.    Modification of warning when the covariates values are not 0 or
     1.
   Revision 1.91  2003/06/25 15:30:29  brouard    Version 0.98g
   * imach.c (Repository): Duplicated warning errors corrected.  
   (Repository): Elapsed time after each iteration is now output. It    Revision 1.122  2006/03/20 09:45:41  brouard
   helps to forecast when convergence will be reached. Elapsed time    (Module): Weights can have a decimal point as for
   is stamped in powell.  We created a new html file for the graphs    English (a comma might work with a correct LC_NUMERIC environment,
   concerning matrix of covariance. It has extension -cov.htm.    otherwise the weight is truncated).
     Modification of warning when the covariates values are not 0 or
   Revision 1.90  2003/06/24 12:34:15  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.121  2006/03/16 17:45:01  lievre
     * imach.c (Module): Comments concerning covariates added
   Revision 1.89  2003/06/24 12:30:52  brouard  
   (Module): Some bugs corrected for windows. Also, when    * imach.c (Module): refinements in the computation of lli if
   mle=-1 a template is output in file "or"mypar.txt with the design    status=-2 in order to have more reliable computation if stepm is
   of the covariance matrix to be input.    not 1 month. Version 0.98f
   
   Revision 1.88  2003/06/23 17:54:56  brouard    Revision 1.120  2006/03/16 15:10:38  lievre
   * 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.    (Module): refinements in the computation of lli if
     status=-2 in order to have more reliable computation if stepm is
   Revision 1.87  2003/06/18 12:26:01  brouard    not 1 month. Version 0.98f
   Version 0.96  
     Revision 1.119  2006/03/15 17:42:26  brouard
   Revision 1.86  2003/06/17 20:04:08  brouard    (Module): Bug if status = -2, the loglikelihood was
   (Module): Change position of html and gnuplot routines and added    computed as likelihood omitting the logarithm. Version O.98e
   routine fileappend.  
     Revision 1.118  2006/03/14 18:20:07  brouard
   Revision 1.85  2003/06/17 13:12:43  brouard    (Module): varevsij Comments added explaining the second
   * imach.c (Repository): Check when date of death was earlier that    table of variances if popbased=1 .
   current date of interview. It may happen when the death was just    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   prior to the death. In this case, dh was negative and likelihood    (Module): Function pstamp added
   was wrong (infinity). We still send an "Error" but patch by    (Module): Version 0.98d
   assuming that the date of death was just one stepm after the  
   interview.    Revision 1.117  2006/03/14 17:16:22  brouard
   (Repository): Because some people have very long ID (first column)    (Module): varevsij Comments added explaining the second
   we changed int to long in num[] and we added a new lvector for    table of variances if popbased=1 .
   memory allocation. But we also truncated to 8 characters (left    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   truncation)    (Module): Function pstamp added
   (Repository): No more line truncation errors.    (Module): Version 0.98d
   
   Revision 1.84  2003/06/13 21:44:43  brouard    Revision 1.116  2006/03/06 10:29:27  brouard
   * imach.c (Repository): Replace "freqsummary" at a correct    (Module): Variance-covariance wrong links and
   place. It differs from routine "prevalence" which may be called    varian-covariance of ej. is needed (Saito).
   many times. Probs is memory consuming and must be used with  
   parcimony.    Revision 1.115  2006/02/27 12:17:45  brouard
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    (Module): One freematrix added in mlikeli! 0.98c
   
   Revision 1.83  2003/06/10 13:39:11  lievre    Revision 1.114  2006/02/26 12:57:58  brouard
   *** empty log message ***    (Module): Some improvements in processing parameter
     filename with strsep.
   Revision 1.82  2003/06/05 15:57:20  brouard  
   Add log in  imach.c and  fullversion number is now printed.    Revision 1.113  2006/02/24 14:20:24  brouard
     (Module): Memory leaks checks with valgrind and:
 */    datafile was not closed, some imatrix were not freed and on matrix
 /*    allocation too.
    Interpolated Markov Chain  
     Revision 1.112  2006/01/30 09:55:26  brouard
   Short summary of the programme:    (Module): Back to gnuplot.exe instead of wgnuplot.exe
     
   This program computes Healthy Life Expectancies from    Revision 1.111  2006/01/25 20:38:18  brouard
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    (Module): Lots of cleaning and bugs added (Gompertz)
   first survey ("cross") where individuals from different ages are    (Module): Comments can be added in data file. Missing date values
   interviewed on their health status or degree of disability (in the    can be a simple dot '.'.
   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.110  2006/01/25 00:51:50  brouard
   (if any) in individual health status.  Health expectancies are    (Module): Lots of cleaning and bugs added (Gompertz)
   computed from the time spent in each health state according to a  
   model. More health states you consider, more time is necessary to reach the    Revision 1.109  2006/01/24 19:37:15  brouard
   Maximum Likelihood of the parameters involved in the model.  The    (Module): Comments (lines starting with a #) are allowed in data.
   simplest model is the multinomial logistic model where pij is the  
   probability to be observed in state j at the second wave    Revision 1.108  2006/01/19 18:05:42  lievre
   conditional to be observed in state i at the first wave. Therefore    Gnuplot problem appeared...
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    To be fixed
   'age' is age and 'sex' is a covariate. If you want to have a more  
   complex model than "constant and age", you should modify the program    Revision 1.107  2006/01/19 16:20:37  brouard
   where the markup *Covariates have to be included here again* invites    Test existence of gnuplot in imach path
   you to do it.  More covariates you add, slower the  
   convergence.    Revision 1.106  2006/01/19 13:24:36  brouard
     Some cleaning and links added in html output
   The advantage of this computer programme, compared to a simple  
   multinomial logistic model, is clear when the delay between waves is not    Revision 1.105  2006/01/05 20:23:19  lievre
   identical for each individual. Also, if a individual missed an    *** empty log message ***
   intermediate interview, the information is lost, but taken into  
   account using an interpolation or extrapolation.      Revision 1.104  2005/09/30 16:11:43  lievre
     (Module): sump fixed, loop imx fixed, and simplifications.
   hPijx is the probability to be observed in state i at age x+h    (Module): If the status is missing at the last wave but we know
   conditional to the observed state i at age x. The delay 'h' can be    that the person is alive, then we can code his/her status as -2
   split into an exact number (nh*stepm) of unobserved intermediate    (instead of missing=-1 in earlier versions) and his/her
   states. This elementary transition (by month, quarter,    contributions to the likelihood is 1 - Prob of dying from last
   semester or year) is modelled as a multinomial logistic.  The hPx    health status (= 1-p13= p11+p12 in the easiest case of somebody in
   matrix is simply the matrix product of nh*stepm elementary matrices    the healthy state at last known wave). Version is 0.98
   and the contribution of each individual to the likelihood is simply  
   hPijx.    Revision 1.103  2005/09/30 15:54:49  lievre
     (Module): sump fixed, loop imx fixed, and simplifications.
   Also this programme outputs the covariance matrix of the parameters but also  
   of the life expectancies. It also computes the stable prevalence.     Revision 1.102  2004/09/15 17:31:30  brouard
       Add the possibility to read data file including tab characters.
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).  
            Institut national d'études démographiques, Paris.    Revision 1.101  2004/09/15 10:38:38  brouard
   This software have been partly granted by Euro-REVES, a concerted action    Fix on curr_time
   from the European Union.  
   It is copyrighted identically to a GNU software product, ie programme and    Revision 1.100  2004/07/12 18:29:06  brouard
   software can be distributed freely for non commercial use. Latest version    Add version for Mac OS X. Just define UNIX in Makefile
   can be accessed at http://euroreves.ined.fr/imach .  
     Revision 1.99  2004/06/05 08:57:40  brouard
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    *** empty log message ***
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so  
       Revision 1.98  2004/05/16 15:05:56  brouard
   **********************************************************************/    New version 0.97 . First attempt to estimate force of mortality
 /*    directly from the data i.e. without the need of knowing the health
   main    state at each age, but using a Gompertz model: log u =a + b*age .
   read parameterfile    This is the basic analysis of mortality and should be done before any
   read datafile    other analysis, in order to test if the mortality estimated from the
   concatwav    cross-longitudinal survey is different from the mortality estimated
   freqsummary    from other sources like vital statistic data.
   if (mle >= 1)  
     mlikeli    The same imach parameter file can be used but the option for mle should be -3.
   print results files  
   if mle==1     Agnès, who wrote this part of the code, tried to keep most of the
      computes hessian    former routines in order to include the new code within the former code.
   read end of parameter file: agemin, agemax, bage, fage, estepm  
       begin-prev-date,...    The output is very simple: only an estimate of the intercept and of
   open gnuplot file    the slope with 95% confident intervals.
   open html file  
   stable prevalence    Current limitations:
    for age prevalim()    A) Even if you enter covariates, i.e. with the
   h Pij x    model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   variance of p varprob    B) There is no computation of Life Expectancy nor Life Table.
   forecasting if prevfcast==1 prevforecast call prevalence()  
   health expectancies    Revision 1.97  2004/02/20 13:25:42  lievre
   Variance-covariance of DFLE    Version 0.96d. Population forecasting command line is (temporarily)
   prevalence()    suppressed.
    movingaverage()  
   varevsij()     Revision 1.96  2003/07/15 15:38:55  brouard
   if popbased==1 varevsij(,popbased)    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   total life expectancies    rewritten within the same printf. Workaround: many printfs.
   Variance of stable prevalence  
  end    Revision 1.95  2003/07/08 07:54:34  brouard
 */    * imach.c (Repository):
     (Repository): Using imachwizard code to output a more meaningful covariance
     matrix (cov(a12,c31) instead of numbers.
   
      Revision 1.94  2003/06/27 13:00:02  brouard
 #include <math.h>    Just cleaning
 #include <stdio.h>  
 #include <stdlib.h>    Revision 1.93  2003/06/25 16:33:55  brouard
 #include <unistd.h>    (Module): On windows (cygwin) function asctime_r doesn't
     exist so I changed back to asctime which exists.
 #include <sys/time.h>    (Module): Version 0.96b
 #include <time.h>  
 #include "timeval.h"    Revision 1.92  2003/06/25 16:30:45  brouard
     (Module): On windows (cygwin) function asctime_r doesn't
 /* #include <libintl.h> */    exist so I changed back to asctime which exists.
 /* #define _(String) gettext (String) */  
     Revision 1.91  2003/06/25 15:30:29  brouard
 #define MAXLINE 256    * imach.c (Repository): Duplicated warning errors corrected.
 #define GNUPLOTPROGRAM "gnuplot"    (Repository): Elapsed time after each iteration is now output. It
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/    helps to forecast when convergence will be reached. Elapsed time
 #define FILENAMELENGTH 132    is stamped in powell.  We created a new html file for the graphs
 /*#define DEBUG*/    concerning matrix of covariance. It has extension -cov.htm.
 /*#define windows*/  
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */    Revision 1.90  2003/06/24 12:34:15  brouard
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */    (Module): Some bugs corrected for windows. Also, when
     mle=-1 a template is output in file "or"mypar.txt with the design
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */    of the covariance matrix to be input.
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  
     Revision 1.89  2003/06/24 12:30:52  brouard
 #define NINTERVMAX 8    (Module): Some bugs corrected for windows. Also, when
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */    mle=-1 a template is output in file "or"mypar.txt with the design
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */    of the covariance matrix to be input.
 #define NCOVMAX 8 /* Maximum number of covariates */  
 #define MAXN 20000    Revision 1.88  2003/06/23 17:54:56  brouard
 #define YEARM 12. /* Number of months per year */    * 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.
 #define AGESUP 130  
 #define AGEBASE 40    Revision 1.87  2003/06/18 12:26:01  brouard
 #ifdef unix    Version 0.96
 #define DIRSEPARATOR '/'  
 #define ODIRSEPARATOR '\\'    Revision 1.86  2003/06/17 20:04:08  brouard
 #else    (Module): Change position of html and gnuplot routines and added
 #define DIRSEPARATOR '\\'    routine fileappend.
 #define ODIRSEPARATOR '/'  
 #endif    Revision 1.85  2003/06/17 13:12:43  brouard
     * imach.c (Repository): Check when date of death was earlier that
 /* $Id$ */    current date of interview. It may happen when the death was just
 /* $State$ */    prior to the death. In this case, dh was negative and likelihood
     was wrong (infinity). We still send an "Error" but patch by
 char version[]="Imach version 0.96b, June 2003, INED-EUROREVES ";    assuming that the date of death was just one stepm after the
 char fullversion[]="$Revision$ $Date$";     interview.
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */    (Repository): Because some people have very long ID (first column)
 int nvar;    we changed int to long in num[] and we added a new lvector for
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;    memory allocation. But we also truncated to 8 characters (left
 int npar=NPARMAX;    truncation)
 int nlstate=2; /* Number of live states */    (Repository): No more line truncation errors.
 int ndeath=1; /* Number of dead states */  
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */    Revision 1.84  2003/06/13 21:44:43  brouard
 int popbased=0;    * imach.c (Repository): Replace "freqsummary" at a correct
     place. It differs from routine "prevalence" which may be called
 int *wav; /* Number of waves for this individuual 0 is possible */    many times. Probs is memory consuming and must be used with
 int maxwav; /* Maxim number of waves */    parcimony.
 int jmin, jmax; /* min, max spacing between 2 waves */    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
 int gipmx, gsw; /* Global variables on the number of contributions   
                    to the likelihood and the sum of weights (done by funcone)*/    Revision 1.83  2003/06/10 13:39:11  lievre
 int mle, weightopt;    *** empty log message ***
 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 */    Revision 1.82  2003/06/05 15:57:20  brouard
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between    Add log in  imach.c and  fullversion number is now printed.
            * 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 */     Interpolated Markov Chain
 FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;  
 FILE *ficlog, *ficrespow;    Short summary of the programme:
 int globpr; /* Global variable for printing or not */   
 double fretone; /* Only one call to likelihood */    This program computes Healthy Life Expectancies from
 long ipmx; /* Number of contributions */    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
 double sw; /* Sum of weights */    first survey ("cross") where individuals from different ages are
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */    interviewed on their health status or degree of disability (in the
 FILE *ficresilk;    case of a health survey which is our main interest) -2- at least a
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;    second wave of interviews ("longitudinal") which measure each change
 FILE *ficresprobmorprev;    (if any) in individual health status.  Health expectancies are
 FILE *fichtm, *fichtmcov; /* Html File */    computed from the time spent in each health state according to a
 FILE *ficreseij;    model. More health states you consider, more time is necessary to reach the
 char filerese[FILENAMELENGTH];    Maximum Likelihood of the parameters involved in the model.  The
 FILE  *ficresvij;    simplest model is the multinomial logistic model where pij is the
 char fileresv[FILENAMELENGTH];    probability to be observed in state j at the second wave
 FILE  *ficresvpl;    conditional to be observed in state i at the first wave. Therefore
 char fileresvpl[FILENAMELENGTH];    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
 char title[MAXLINE];    'age' is age and 'sex' is a covariate. If you want to have a more
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];    complex model than "constant and age", you should modify the program
 char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH];    where the markup *Covariates have to be included here again* invites
 char tmpout[FILENAMELENGTH];     you to do it.  More covariates you add, slower the
 char command[FILENAMELENGTH];    convergence.
 int  outcmd=0;  
     The advantage of this computer programme, compared to a simple
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];    multinomial logistic model, is clear when the delay between waves is not
     identical for each individual. Also, if a individual missed an
 char filelog[FILENAMELENGTH]; /* Log file */    intermediate interview, the information is lost, but taken into
 char filerest[FILENAMELENGTH];    account using an interpolation or extrapolation.  
 char fileregp[FILENAMELENGTH];  
 char popfile[FILENAMELENGTH];    hPijx is the probability to be observed in state i at age x+h
     conditional to the observed state i at age x. The delay 'h' can be
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;    split into an exact number (nh*stepm) of unobserved intermediate
     states. This elementary transition (by month, quarter,
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;    semester or year) is modelled as a multinomial logistic.  The hPx
 struct timezone tzp;    matrix is simply the matrix product of nh*stepm elementary matrices
 extern int gettimeofday();    and the contribution of each individual to the likelihood is simply
 struct tm tmg, tm, tmf, *gmtime(), *localtime();    hPijx.
 long time_value;  
 extern long time();    Also this programme outputs the covariance matrix of the parameters but also
 char strcurr[80], strfor[80];    of the life expectancies. It also computes the period (stable) prevalence.
    
 #define NR_END 1    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 #define FREE_ARG char*             Institut national d'études démographiques, Paris.
 #define FTOL 1.0e-10    This software have been partly granted by Euro-REVES, a concerted action
     from the European Union.
 #define NRANSI     It is copyrighted identically to a GNU software product, ie programme and
 #define ITMAX 200     software can be distributed freely for non commercial use. Latest version
     can be accessed at http://euroreves.ined.fr/imach .
 #define TOL 2.0e-4   
     Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 #define CGOLD 0.3819660     or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 #define ZEPS 1.0e-10    
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);     **********************************************************************/
   /*
 #define GOLD 1.618034     main
 #define GLIMIT 100.0     read parameterfile
 #define TINY 1.0e-20     read datafile
     concatwav
 static double maxarg1,maxarg2;    freqsummary
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))    if (mle >= 1)
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))      mlikeli
       print results files
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))    if mle==1
 #define rint(a) floor(a+0.5)       computes hessian
     read end of parameter file: agemin, agemax, bage, fage, estepm
 static double sqrarg;        begin-prev-date,...
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)    open gnuplot file
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}     open html file
     period (stable) prevalence
 int imx;      for age prevalim()
 int stepm;    h Pij x
 /* Stepm, step in month: minimum step interpolation*/    variance of p varprob
     forecasting if prevfcast==1 prevforecast call prevalence()
 int estepm;    health expectancies
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/    Variance-covariance of DFLE
     prevalence()
 int m,nb;     movingaverage()
 long *num;    varevsij()
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage;    if popbased==1 varevsij(,popbased)
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;    total life expectancies
 double **pmmij, ***probs;    Variance of period (stable) prevalence
 double dateintmean=0;   end
   */
 double *weight;  
 int **s; /* Status */  
 double *agedc, **covar, idx;  
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;   
   #include <math.h>
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  #include <stdio.h>
 double ftolhess; /* Tolerance for computing hessian */  #include <stdlib.h>
   #include <string.h>
 /**************** split *************************/  #include <unistd.h>
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  
 {  #include <limits.h>
   char  *ss;                            /* pointer */  #include <sys/types.h>
   int   l1, l2;                         /* length counters */  #include <sys/stat.h>
   #include <errno.h>
   l1 = strlen(path );                   /* length of path */  extern int errno;
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  /* #include <sys/time.h> */
   if ( ss == NULL ) {                   /* no directory, so use current */  #include <time.h>
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  #include "timeval.h"
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  
     /* get current working directory */  /* #include <libintl.h> */
     /*    extern  char* getcwd ( char *buf , int len);*/  /* #define _(String) gettext (String) */
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  
       return( GLOCK_ERROR_GETCWD );  #define MAXLINE 256
     }  
     strcpy( name, path );               /* we've got it */  #define GNUPLOTPROGRAM "gnuplot"
   } else {                              /* strip direcotry from path */  /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
     ss++;                               /* after this, the filename */  #define FILENAMELENGTH 132
     l2 = strlen( ss );                  /* length of filename */  
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
     strcpy( name, ss );         /* save file name */  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  
     dirc[l1-l2] = 0;                    /* add zero */  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
   }  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
   l1 = strlen( dirc );                  /* length of directory */  
   /*#ifdef windows  #define NINTERVMAX 8
   if ( dirc[l1-1] != '\\' ) { dirc[l1] = '\\'; dirc[l1+1] = 0; }  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 #else  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
   if ( dirc[l1-1] != '/' ) { dirc[l1] = '/'; dirc[l1+1] = 0; }  #define NCOVMAX 8 /* Maximum number of covariates */
 #endif  #define MAXN 20000
   */  #define YEARM 12. /* Number of months per year */
   ss = strrchr( name, '.' );            /* find last / */  #define AGESUP 130
   ss++;  #define AGEBASE 40
   strcpy(ext,ss);                       /* save extension */  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
   l1= strlen( name);  #ifdef UNIX
   l2= strlen(ss)+1;  #define DIRSEPARATOR '/'
   strncpy( finame, name, l1-l2);  #define CHARSEPARATOR "/"
   finame[l1-l2]= 0;  #define ODIRSEPARATOR '\\'
   return( 0 );                          /* we're done */  #else
 }  #define DIRSEPARATOR '\\'
   #define CHARSEPARATOR "\\"
   #define ODIRSEPARATOR '/'
 /******************************************/  #endif
   
 void replace_back_to_slash(char *s, char*t)  /* $Id$ */
 {  /* $State$ */
   int i;  
   int lg=0;  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
   i=0;  char fullversion[]="$Revision$ $Date$";
   lg=strlen(t);  char strstart[80];
   for(i=0; i<= lg; i++) {  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
     (s[i] = t[i]);  int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
     if (t[i]== '\\') s[i]='/';  int nvar;
   }  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 }  int npar=NPARMAX;
   int nlstate=2; /* Number of live states */
 int nbocc(char *s, char occ)  int ndeath=1; /* Number of dead states */
 {  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
   int i,j=0;  int popbased=0;
   int lg=20;  
   i=0;  int *wav; /* Number of waves for this individuual 0 is possible */
   lg=strlen(s);  int maxwav; /* Maxim number of waves */
   for(i=0; i<= lg; i++) {  int jmin, jmax; /* min, max spacing between 2 waves */
   if  (s[i] == occ ) j++;  int ijmin, ijmax; /* Individuals having jmin and jmax */
   }  int gipmx, gsw; /* Global variables on the number of contributions
   return j;                     to the likelihood and the sum of weights (done by funcone)*/
 }  int mle, weightopt;
   int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 void cutv(char *u,char *v, char*t, char occ)  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 {  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
   /* cuts string t into u and v where u is ended by char occ excluding it             * wave mi and wave mi+1 is not an exact multiple of stepm. */
      and v is after occ excluding it too : ex cutv(u,v,"abcdef2ghi2j",2)  double jmean; /* Mean space between 2 waves */
      gives u="abcedf" and v="ghi2j" */  double **oldm, **newm, **savm; /* Working pointers to matrices */
   int i,lg,j,p=0;  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
   i=0;  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
   for(j=0; j<=strlen(t)-1; j++) {  FILE *ficlog, *ficrespow;
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;  int globpr; /* Global variable for printing or not */
   }  double fretone; /* Only one call to likelihood */
   long ipmx; /* Number of contributions */
   lg=strlen(t);  double sw; /* Sum of weights */
   for(j=0; j<p; j++) {  char filerespow[FILENAMELENGTH];
     (u[j] = t[j]);  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
   }  FILE *ficresilk;
      u[p]='\0';  FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
   FILE *ficresprobmorprev;
    for(j=0; j<= lg; j++) {  FILE *fichtm, *fichtmcov; /* Html File */
     if (j>=(p+1))(v[j-p-1] = t[j]);  FILE *ficreseij;
   }  char filerese[FILENAMELENGTH];
 }  FILE *ficresstdeij;
   char fileresstde[FILENAMELENGTH];
 /********************** nrerror ********************/  FILE *ficrescveij;
   char filerescve[FILENAMELENGTH];
 void nrerror(char error_text[])  FILE  *ficresvij;
 {  char fileresv[FILENAMELENGTH];
   fprintf(stderr,"ERREUR ...\n");  FILE  *ficresvpl;
   fprintf(stderr,"%s\n",error_text);  char fileresvpl[FILENAMELENGTH];
   exit(EXIT_FAILURE);  char title[MAXLINE];
 }  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 /*********************** vector *******************/  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 double *vector(int nl, int nh)  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
 {  char command[FILENAMELENGTH];
   double *v;  int  outcmd=0;
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));  
   if (!v) nrerror("allocation failure in vector");  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
   return v-nl+NR_END;  
 }  char filelog[FILENAMELENGTH]; /* Log file */
   char filerest[FILENAMELENGTH];
 /************************ free vector ******************/  char fileregp[FILENAMELENGTH];
 void free_vector(double*v, int nl, int nh)  char popfile[FILENAMELENGTH];
 {  
   free((FREE_ARG)(v+nl-NR_END));  char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 }  
   struct timeval start_time, end_time, curr_time, last_time, forecast_time;
 /************************ivector *******************************/  struct timezone tzp;
 int *ivector(long nl,long nh)  extern int gettimeofday();
 {  struct tm tmg, tm, tmf, *gmtime(), *localtime();
   int *v;  long time_value;
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));  extern long time();
   if (!v) nrerror("allocation failure in ivector");  char strcurr[80], strfor[80];
   return v-nl+NR_END;  
 }  char *endptr;
   long lval;
 /******************free ivector **************************/  double dval;
 void free_ivector(int *v, long nl, long nh)  
 {  #define NR_END 1
   free((FREE_ARG)(v+nl-NR_END));  #define FREE_ARG char*
 }  #define FTOL 1.0e-10
   
 /************************lvector *******************************/  #define NRANSI
 long *lvector(long nl,long nh)  #define ITMAX 200
 {  
   long *v;  #define TOL 2.0e-4
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));  
   if (!v) nrerror("allocation failure in ivector");  #define CGOLD 0.3819660
   return v-nl+NR_END;  #define ZEPS 1.0e-10
 }  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
   
 /******************free lvector **************************/  #define GOLD 1.618034
 void free_lvector(long *v, long nl, long nh)  #define GLIMIT 100.0
 {  #define TINY 1.0e-20
   free((FREE_ARG)(v+nl-NR_END));  
 }  static double maxarg1,maxarg2;
   #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 /******************* imatrix *******************************/  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 int **imatrix(long nrl, long nrh, long ncl, long nch)    
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */   #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 {   #define rint(a) floor(a+0.5)
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;   
   int **m;   static double sqrarg;
     #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
   /* allocate pointers to rows */   #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));   int agegomp= AGEGOMP;
   if (!m) nrerror("allocation failure 1 in matrix()");   
   m += NR_END;   int imx;
   m -= nrl;   int stepm=1;
     /* Stepm, step in month: minimum step interpolation*/
     
   /* allocate rows and set pointers to them */   int estepm;
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));   /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");   
   m[nrl] += NR_END;   int m,nb;
   m[nrl] -= ncl;   long *num;
     int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;   double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
     double **pmmij, ***probs;
   /* return pointer to array of pointers to rows */   double *ageexmed,*agecens;
   return m;   double dateintmean=0;
 }   
   double *weight;
 /****************** free_imatrix *************************/  int **s; /* Status */
 void free_imatrix(m,nrl,nrh,ncl,nch)  double *agedc, **covar, idx;
       int **m;  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
       long nch,ncl,nrh,nrl;   double *lsurv, *lpop, *tpop;
      /* free an int matrix allocated by imatrix() */   
 {   double ftol=FTOL; /* Tolerance for computing Max Likelihood */
   free((FREE_ARG) (m[nrl]+ncl-NR_END));   double ftolhess; /* Tolerance for computing hessian */
   free((FREE_ARG) (m+nrl-NR_END));   
 }   /**************** split *************************/
   static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
 /******************* matrix *******************************/  {
 double **matrix(long nrl, long nrh, long ncl, long nch)    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 {       the name of the file (name), its extension only (ext) and its first part of the name (finame)
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;    */
   double **m;    char  *ss;                            /* pointer */
     int   l1, l2;                         /* length counters */
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  
   if (!m) nrerror("allocation failure 1 in matrix()");    l1 = strlen(path );                   /* length of path */
   m += NR_END;    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
   m -= nrl;    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
     if ( ss == NULL ) {                   /* no directory, so determine current directory */
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));      strcpy( name, path );               /* we got the fullname name because no directory */
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
   m[nrl] += NR_END;        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
   m[nrl] -= ncl;      /* get current working directory */
       /*    extern  char* getcwd ( char *buf , int len);*/
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
   return m;        return( GLOCK_ERROR_GETCWD );
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])       }
    */      /* got dirc from getcwd*/
 }      printf(" DIRC = %s \n",dirc);
     } else {                              /* strip direcotry from path */
 /*************************free matrix ************************/      ss++;                               /* after this, the filename */
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)      l2 = strlen( ss );                  /* length of filename */
 {      if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
   free((FREE_ARG)(m[nrl]+ncl-NR_END));      strcpy( name, ss );         /* save file name */
   free((FREE_ARG)(m+nrl-NR_END));      strncpy( dirc, path, l1 - l2 );     /* now the directory */
 }      dirc[l1-l2] = 0;                    /* add zero */
       printf(" DIRC2 = %s \n",dirc);
 /******************* ma3x *******************************/    }
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)    /* We add a separator at the end of dirc if not exists */
 {    l1 = strlen( dirc );                  /* length of directory */
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;    if( dirc[l1-1] != DIRSEPARATOR ){
   double ***m;      dirc[l1] =  DIRSEPARATOR;
       dirc[l1+1] = 0;
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));      printf(" DIRC3 = %s \n",dirc);
   if (!m) nrerror("allocation failure 1 in matrix()");    }
   m += NR_END;    ss = strrchr( name, '.' );            /* find last / */
   m -= nrl;    if (ss >0){
       ss++;
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));      strcpy(ext,ss);                     /* save extension */
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");      l1= strlen( name);
   m[nrl] += NR_END;      l2= strlen(ss)+1;
   m[nrl] -= ncl;      strncpy( finame, name, l1-l2);
       finame[l1-l2]= 0;
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    }
   
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));    return( 0 );                          /* we're done */
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");  }
   m[nrl][ncl] += NR_END;  
   m[nrl][ncl] -= nll;  
   for (j=ncl+1; j<=nch; j++)   /******************************************/
     m[nrl][j]=m[nrl][j-1]+nlay;  
     void replace_back_to_slash(char *s, char*t)
   for (i=nrl+1; i<=nrh; i++) {  {
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;    int i;
     for (j=ncl+1; j<=nch; j++)     int lg=0;
       m[i][j]=m[i][j-1]+nlay;    i=0;
   }    lg=strlen(t);
   return m;     for(i=0; i<= lg; i++) {
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])      (s[i] = t[i]);
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)      if (t[i]== '\\') s[i]='/';
   */    }
 }  }
   
 /*************************free ma3x ************************/  int nbocc(char *s, char occ)
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)  {
 {    int i,j=0;
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    int lg=20;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    i=0;
   free((FREE_ARG)(m+nrl-NR_END));    lg=strlen(s);
 }    for(i=0; i<= lg; i++) {
     if  (s[i] == occ ) j++;
 /*************** function subdirf ***********/    }
 char *subdirf(char fileres[])    return j;
 {  }
   /* Caution optionfilefiname is hidden */  
   strcpy(tmpout,optionfilefiname);  void cutv(char *u,char *v, char*t, char occ)
   strcat(tmpout,"/"); /* Add to the right */  {
   strcat(tmpout,fileres);    /* cuts string t into u and v where u ends before first occurence of char 'occ'
   return tmpout;       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
 }       gives u="abcedf" and v="ghi2j" */
     int i,lg,j,p=0;
 /*************** function subdirf2 ***********/    i=0;
 char *subdirf2(char fileres[], char *preop)    for(j=0; j<=strlen(t)-1; j++) {
 {      if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
       }
   /* Caution optionfilefiname is hidden */  
   strcpy(tmpout,optionfilefiname);    lg=strlen(t);
   strcat(tmpout,"/");    for(j=0; j<p; j++) {
   strcat(tmpout,preop);      (u[j] = t[j]);
   strcat(tmpout,fileres);    }
   return tmpout;       u[p]='\0';
 }  
      for(j=0; j<= lg; j++) {
 /*************** function subdirf3 ***********/      if (j>=(p+1))(v[j-p-1] = t[j]);
 char *subdirf3(char fileres[], char *preop, char *preop2)    }
 {  }
     
   /* Caution optionfilefiname is hidden */  /********************** nrerror ********************/
   strcpy(tmpout,optionfilefiname);  
   strcat(tmpout,"/");  void nrerror(char error_text[])
   strcat(tmpout,preop);  {
   strcat(tmpout,preop2);    fprintf(stderr,"ERREUR ...\n");
   strcat(tmpout,fileres);    fprintf(stderr,"%s\n",error_text);
   return tmpout;    exit(EXIT_FAILURE);
 }  }
   /*********************** vector *******************/
 /***************** f1dim *************************/  double *vector(int nl, int nh)
 extern int ncom;   {
 extern double *pcom,*xicom;    double *v;
 extern double (*nrfunc)(double []);     v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
      if (!v) nrerror("allocation failure in vector");
 double f1dim(double x)     return v-nl+NR_END;
 {   }
   int j;   
   double f;  /************************ free vector ******************/
   double *xt;   void free_vector(double*v, int nl, int nh)
    {
   xt=vector(1,ncom);     free((FREE_ARG)(v+nl-NR_END));
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];   }
   f=(*nrfunc)(xt);   
   free_vector(xt,1,ncom);   /************************ivector *******************************/
   return f;   int *ivector(long nl,long nh)
 }   {
     int *v;
 /*****************brent *************************/    v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)     if (!v) nrerror("allocation failure in ivector");
 {     return v-nl+NR_END;
   int iter;   }
   double a,b,d,etemp;  
   double fu,fv,fw,fx;  /******************free ivector **************************/
   double ftemp;  void free_ivector(int *v, long nl, long nh)
   double p,q,r,tol1,tol2,u,v,w,x,xm;   {
   double e=0.0;     free((FREE_ARG)(v+nl-NR_END));
    }
   a=(ax < cx ? ax : cx);   
   b=(ax > cx ? ax : cx);   /************************lvector *******************************/
   x=w=v=bx;   long *lvector(long nl,long nh)
   fw=fv=fx=(*f)(x);   {
   for (iter=1;iter<=ITMAX;iter++) {     long *v;
     xm=0.5*(a+b);     v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     if (!v) nrerror("allocation failure in ivector");
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/    return v-nl+NR_END;
     printf(".");fflush(stdout);  }
     fprintf(ficlog,".");fflush(ficlog);  
 #ifdef DEBUG  /******************free lvector **************************/
     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);  void free_lvector(long *v, long nl, long nh)
     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)))) { */    free((FREE_ARG)(v+nl-NR_END));
 #endif  }
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){   
       *xmin=x;   /******************* imatrix *******************************/
       return fx;   int **imatrix(long nrl, long nrh, long ncl, long nch)
     }        /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
     ftemp=fu;  {
     if (fabs(e) > tol1) {     long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
       r=(x-w)*(fx-fv);     int **m;
       q=(x-v)*(fx-fw);    
       p=(x-v)*q-(x-w)*r;     /* allocate pointers to rows */
       q=2.0*(q-r);     m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
       if (q > 0.0) p = -p;     if (!m) nrerror("allocation failure 1 in matrix()");
       q=fabs(q);     m += NR_END;
       etemp=e;     m -= nrl;
       e=d;    
       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));     /* allocate rows and set pointers to them */
       else {     m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
         d=p/q;     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
         u=x+d;     m[nrl] += NR_END;
         if (u-a < tol2 || b-u < tol2)     m[nrl] -= ncl;
           d=SIGN(tol1,xm-x);    
       }     for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
     } else {    
       d=CGOLD*(e=(x >= xm ? a-x : b-x));     /* return pointer to array of pointers to rows */
     }     return m;
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));   }
     fu=(*f)(u);   
     if (fu <= fx) {   /****************** free_imatrix *************************/
       if (u >= x) a=x; else b=x;   void free_imatrix(m,nrl,nrh,ncl,nch)
       SHFT(v,w,x,u)         int **m;
         SHFT(fv,fw,fx,fu)         long nch,ncl,nrh,nrl;
         } else {        /* free an int matrix allocated by imatrix() */
           if (u < x) a=u; else b=u;   {
           if (fu <= fw || w == x) {     free((FREE_ARG) (m[nrl]+ncl-NR_END));
             v=w;     free((FREE_ARG) (m+nrl-NR_END));
             w=u;   }
             fv=fw;   
             fw=fu;   /******************* matrix *******************************/
           } else if (fu <= fv || v == x || v == w) {   double **matrix(long nrl, long nrh, long ncl, long nch)
             v=u;   {
             fv=fu;     long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
           }     double **m;
         }   
   }     m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   nrerror("Too many iterations in brent");     if (!m) nrerror("allocation failure 1 in matrix()");
   *xmin=x;     m += NR_END;
   return fx;     m -= nrl;
 }   
     m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 /****************** mnbrak ***********************/    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     m[nrl] += NR_END;
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,     m[nrl] -= ncl;
             double (*func)(double))   
 {     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   double ulim,u,r,q, dum;    return m;
   double fu;     /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
       */
   *fa=(*func)(*ax);   }
   *fb=(*func)(*bx);   
   if (*fb > *fa) {   /*************************free matrix ************************/
     SHFT(dum,*ax,*bx,dum)   void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
       SHFT(dum,*fb,*fa,dum)   {
       }     free((FREE_ARG)(m[nrl]+ncl-NR_END));
   *cx=(*bx)+GOLD*(*bx-*ax);     free((FREE_ARG)(m+nrl-NR_END));
   *fc=(*func)(*cx);   }
   while (*fb > *fc) {   
     r=(*bx-*ax)*(*fb-*fc);   /******************* ma3x *******************************/
     q=(*bx-*cx)*(*fb-*fa);   double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/   {
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));     long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
     ulim=(*bx)+GLIMIT*(*cx-*bx);     double ***m;
     if ((*bx-u)*(u-*cx) > 0.0) {   
       fu=(*func)(u);     m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
     } else if ((*cx-u)*(u-ulim) > 0.0) {     if (!m) nrerror("allocation failure 1 in matrix()");
       fu=(*func)(u);     m += NR_END;
       if (fu < *fc) {     m -= nrl;
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))   
           SHFT(*fb,*fc,fu,(*func)(u))     m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
           }     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {     m[nrl] += NR_END;
       u=ulim;     m[nrl] -= ncl;
       fu=(*func)(u);   
     } else {     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
       u=(*cx)+GOLD*(*cx-*bx);   
       fu=(*func)(u);     m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
     }     if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
     SHFT(*ax,*bx,*cx,u)     m[nrl][ncl] += NR_END;
       SHFT(*fa,*fb,*fc,fu)     m[nrl][ncl] -= nll;
       }     for (j=ncl+1; j<=nch; j++)
 }       m[nrl][j]=m[nrl][j-1]+nlay;
    
 /*************** linmin ************************/    for (i=nrl+1; i<=nrh; i++) {
       m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 int ncom;       for (j=ncl+1; j<=nch; j++)
 double *pcom,*xicom;        m[i][j]=m[i][j-1]+nlay;
 double (*nrfunc)(double []);     }
      return m;
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))     /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 {              &(m[i][j][k]) <=> *((*(m+i) + j)+k)
   double brent(double ax, double bx, double cx,     */
                double (*f)(double), double tol, double *xmin);   }
   double f1dim(double x);   
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,   /*************************free ma3x ************************/
               double *fc, double (*func)(double));   void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
   int j;   {
   double xx,xmin,bx,ax;     free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
   double fx,fb,fa;    free((FREE_ARG)(m[nrl]+ncl-NR_END));
      free((FREE_ARG)(m+nrl-NR_END));
   ncom=n;   }
   pcom=vector(1,n);   
   xicom=vector(1,n);   /*************** function subdirf ***********/
   nrfunc=func;   char *subdirf(char fileres[])
   for (j=1;j<=n;j++) {   {
     pcom[j]=p[j];     /* Caution optionfilefiname is hidden */
     xicom[j]=xi[j];     strcpy(tmpout,optionfilefiname);
   }     strcat(tmpout,"/"); /* Add to the right */
   ax=0.0;     strcat(tmpout,fileres);
   xx=1.0;     return tmpout;
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);   }
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);   
 #ifdef DEBUG  /*************** function subdirf2 ***********/
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  char *subdirf2(char fileres[], char *preop)
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  {
 #endif   
   for (j=1;j<=n;j++) {     /* Caution optionfilefiname is hidden */
     xi[j] *= xmin;     strcpy(tmpout,optionfilefiname);
     p[j] += xi[j];     strcat(tmpout,"/");
   }     strcat(tmpout,preop);
   free_vector(xicom,1,n);     strcat(tmpout,fileres);
   free_vector(pcom,1,n);     return tmpout;
 }   }
   
 char *asc_diff_time(long time_sec, char ascdiff[])  /*************** function subdirf3 ***********/
 {  char *subdirf3(char fileres[], char *preop, char *preop2)
   long sec_left, days, hours, minutes;  {
   days = (time_sec) / (60*60*24);   
   sec_left = (time_sec) % (60*60*24);    /* Caution optionfilefiname is hidden */
   hours = (sec_left) / (60*60) ;    strcpy(tmpout,optionfilefiname);
   sec_left = (sec_left) %(60*60);    strcat(tmpout,"/");
   minutes = (sec_left) /60;    strcat(tmpout,preop);
   sec_left = (sec_left) % (60);    strcat(tmpout,preop2);
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);      strcat(tmpout,fileres);
   return ascdiff;    return tmpout;
 }  }
   
 /*************** powell ************************/  /***************** f1dim *************************/
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,   extern int ncom;
             double (*func)(double []))   extern double *pcom,*xicom;
 {   extern double (*nrfunc)(double []);
   void linmin(double p[], double xi[], int n, double *fret,    
               double (*func)(double []));   double f1dim(double x)
   int i,ibig,j;   {
   double del,t,*pt,*ptt,*xit;    int j;
   double fp,fptt;    double f;
   double *xits;    double *xt;
   int niterf, itmp;   
     xt=vector(1,ncom);
   pt=vector(1,n);     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
   ptt=vector(1,n);     f=(*nrfunc)(xt);
   xit=vector(1,n);     free_vector(xt,1,ncom);
   xits=vector(1,n);     return f;
   *fret=(*func)(p);   }
   for (j=1;j<=n;j++) pt[j]=p[j];   
   for (*iter=1;;++(*iter)) {   /*****************brent *************************/
     fp=(*fret);   double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
     ibig=0;   {
     del=0.0;     int iter;
     last_time=curr_time;    double a,b,d,etemp;
     (void) gettimeofday(&curr_time,&tzp);    double fu,fv,fw,fx;
     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);    double ftemp;
     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);    double p,q,r,tol1,tol2,u,v,w,x,xm;
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);    double e=0.0;
     for (i=1;i<=n;i++) {   
       printf(" %d %.12f",i, p[i]);    a=(ax < cx ? ax : cx);
       fprintf(ficlog," %d %.12lf",i, p[i]);    b=(ax > cx ? ax : cx);
       fprintf(ficrespow," %.12lf", p[i]);    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);
     fprintf(ficrespow,"\n");fflush(ficrespow);      tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
     if(*iter <=3){      /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
       tm = *localtime(&curr_time.tv_sec);      printf(".");fflush(stdout);
       strcpy(strcurr,asctime(&tmf));      fprintf(ficlog,".");fflush(ficlog);
 /*       asctime_r(&tm,strcurr); */  #ifdef DEBUG
       forecast_time=curr_time;      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);
       itmp = strlen(strcurr);      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(strcurr[itmp-1]=='\n')      /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
         strcurr[itmp-1]='\0';  #endif
       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);      if (fabs(x-xm) <= (tol2-0.5*(b-a))){
       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);        *xmin=x;
       for(niterf=10;niterf<=30;niterf+=10){        return fx;
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);      }
         tmf = *localtime(&forecast_time.tv_sec);      ftemp=fu;
 /*      asctime_r(&tmf,strfor); */      if (fabs(e) > tol1) {
         strcpy(strfor,asctime(&tmf));        r=(x-w)*(fx-fv);
         itmp = strlen(strfor);        q=(x-v)*(fx-fw);
         if(strfor[itmp-1]=='\n')        p=(x-v)*q-(x-w)*r;
         strfor[itmp-1]='\0';        q=2.0*(q-r);
         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);        if (q > 0.0) p = -p;
         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);        q=fabs(q);
       }        etemp=e;
     }        e=d;
     for (i=1;i<=n;i++) {         if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
       for (j=1;j<=n;j++) xit[j]=xi[j][i];           d=CGOLD*(e=(x >= xm ? a-x : b-x));
       fptt=(*fret);         else {
 #ifdef DEBUG          d=p/q;
       printf("fret=%lf \n",*fret);          u=x+d;
       fprintf(ficlog,"fret=%lf \n",*fret);          if (u-a < tol2 || b-u < tol2)
 #endif            d=SIGN(tol1,xm-x);
       printf("%d",i);fflush(stdout);        }
       fprintf(ficlog,"%d",i);fflush(ficlog);      } else {
       linmin(p,xit,n,fret,func);         d=CGOLD*(e=(x >= xm ? a-x : b-x));
       if (fabs(fptt-(*fret)) > del) {       }
         del=fabs(fptt-(*fret));       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
         ibig=i;       fu=(*f)(u);
       }       if (fu <= fx) {
 #ifdef DEBUG        if (u >= x) a=x; else b=x;
       printf("%d %.12e",i,(*fret));        SHFT(v,w,x,u)
       fprintf(ficlog,"%d %.12e",i,(*fret));          SHFT(fv,fw,fx,fu)
       for (j=1;j<=n;j++) {          } else {
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);            if (u < x) a=u; else b=u;
         printf(" x(%d)=%.12e",j,xit[j]);            if (fu <= fw || w == x) {
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);              v=w;
       }              w=u;
       for(j=1;j<=n;j++) {              fv=fw;
         printf(" p=%.12e",p[j]);              fw=fu;
         fprintf(ficlog," p=%.12e",p[j]);            } else if (fu <= fv || v == x || v == w) {
       }              v=u;
       printf("\n");              fv=fu;
       fprintf(ficlog,"\n");            }
 #endif          }
     }     }
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {    nrerror("Too many iterations in brent");
 #ifdef DEBUG    *xmin=x;
       int k[2],l;    return fx;
       k[0]=1;  }
       k[1]=-1;  
       printf("Max: %.12e",(*func)(p));  /****************** mnbrak ***********************/
       fprintf(ficlog,"Max: %.12e",(*func)(p));  
       for (j=1;j<=n;j++) {  void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
         printf(" %.12e",p[j]);              double (*func)(double))
         fprintf(ficlog," %.12e",p[j]);  {
       }    double ulim,u,r,q, dum;
       printf("\n");    double fu;
       fprintf(ficlog,"\n");   
       for(l=0;l<=1;l++) {    *fa=(*func)(*ax);
         for (j=1;j<=n;j++) {    *fb=(*func)(*bx);
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];    if (*fb > *fa) {
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);      SHFT(dum,*ax,*bx,dum)
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        SHFT(dum,*fb,*fa,dum)
         }        }
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));    *cx=(*bx)+GOLD*(*bx-*ax);
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));    *fc=(*func)(*cx);
       }    while (*fb > *fc) {
 #endif      r=(*bx-*ax)*(*fb-*fc);
       q=(*bx-*cx)*(*fb-*fa);
       u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
       free_vector(xit,1,n);         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
       free_vector(xits,1,n);       ulim=(*bx)+GLIMIT*(*cx-*bx);
       free_vector(ptt,1,n);       if ((*bx-u)*(u-*cx) > 0.0) {
       free_vector(pt,1,n);         fu=(*func)(u);
       return;       } else if ((*cx-u)*(u-ulim) > 0.0) {
     }         fu=(*func)(u);
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");         if (fu < *fc) {
     for (j=1;j<=n;j++) {           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
       ptt[j]=2.0*p[j]-pt[j];             SHFT(*fb,*fc,fu,(*func)(u))
       xit[j]=p[j]-pt[j];             }
       pt[j]=p[j];       } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
     }         u=ulim;
     fptt=(*func)(ptt);         fu=(*func)(u);
     if (fptt < fp) {       } else {
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);         u=(*cx)+GOLD*(*cx-*bx);
       if (t < 0.0) {         fu=(*func)(u);
         linmin(p,xit,n,fret,func);       }
         for (j=1;j<=n;j++) {       SHFT(*ax,*bx,*cx,u)
           xi[j][ibig]=xi[j][n];         SHFT(*fa,*fb,*fc,fu)
           xi[j][n]=xit[j];         }
         }  }
 #ifdef DEBUG  
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);  /*************** linmin ************************/
         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++){  int ncom;
           printf(" %.12e",xit[j]);  double *pcom,*xicom;
           fprintf(ficlog," %.12e",xit[j]);  double (*nrfunc)(double []);
         }   
         printf("\n");  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
         fprintf(ficlog,"\n");  {
 #endif    double brent(double ax, double bx, double cx,
       }                 double (*f)(double), double tol, double *xmin);
     }     double f1dim(double x);
   }     void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
 }                 double *fc, double (*func)(double));
     int j;
 /**** Prevalence limit (stable prevalence)  ****************/    double xx,xmin,bx,ax;
     double fx,fb,fa;
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)   
 {    ncom=n;
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit    pcom=vector(1,n);
      matrix by transitions matrix until convergence is reached */    xicom=vector(1,n);
     nrfunc=func;
   int i, ii,j,k;    for (j=1;j<=n;j++) {
   double min, max, maxmin, maxmax,sumnew=0.;      pcom[j]=p[j];
   double **matprod2();      xicom[j]=xi[j];
   double **out, cov[NCOVMAX], **pmij();    }
   double **newm;    ax=0.0;
   double agefin, delaymax=50 ; /* Max number of years to converge */    xx=1.0;
     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
   for (ii=1;ii<=nlstate+ndeath;ii++)    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
     for (j=1;j<=nlstate+ndeath;j++){  #ifdef DEBUG
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);    printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
     }    fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   #endif
    cov[1]=1.;    for (j=1;j<=n;j++) {
        xi[j] *= xmin;
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */      p[j] += xi[j];
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){    }
     newm=savm;    free_vector(xicom,1,n);
     /* Covariates have to be included here again */    free_vector(pcom,1,n);
      cov[2]=agefin;  }
     
       for (k=1; k<=cptcovn;k++) {  char *asc_diff_time(long time_sec, char ascdiff[])
         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];  {
         /*      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]]);*/    long sec_left, days, hours, minutes;
       }    days = (time_sec) / (60*60*24);
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];    sec_left = (time_sec) % (60*60*24);
       for (k=1; k<=cptcovprod;k++)    hours = (sec_left) / (60*60) ;
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];    sec_left = (sec_left) %(60*60);
     minutes = (sec_left) /60;
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/    sec_left = (sec_left) % (60);
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/    sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/    return ascdiff;
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);  }
   
     savm=oldm;  /*************** powell ************************/
     oldm=newm;  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
     maxmax=0.;              double (*func)(double []))
     for(j=1;j<=nlstate;j++){  {
       min=1.;    void linmin(double p[], double xi[], int n, double *fret,
       max=0.;                double (*func)(double []));
       for(i=1; i<=nlstate; i++) {    int i,ibig,j;
         sumnew=0;    double del,t,*pt,*ptt,*xit;
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];    double fp,fptt;
         prlim[i][j]= newm[i][j]/(1-sumnew);    double *xits;
         max=FMAX(max,prlim[i][j]);    int niterf, itmp;
         min=FMIN(min,prlim[i][j]);  
       }    pt=vector(1,n);
       maxmin=max-min;    ptt=vector(1,n);
       maxmax=FMAX(maxmax,maxmin);    xit=vector(1,n);
     }    xits=vector(1,n);
     if(maxmax < ftolpl){    *fret=(*func)(p);
       return prlim;    for (j=1;j<=n;j++) pt[j]=p[j];
     }    for (*iter=1;;++(*iter)) {
   }      fp=(*fret);
 }      ibig=0;
       del=0.0;
 /*************** transition probabilities ***************/       last_time=curr_time;
       (void) gettimeofday(&curr_time,&tzp);
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )      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); fflush(ficlog);
   double s1, s2;  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
   /*double t34;*/     for (i=1;i<=n;i++) {
   int i,j,j1, nc, ii, jj;        printf(" %d %.12f",i, p[i]);
         fprintf(ficlog," %d %.12lf",i, p[i]);
     for(i=1; i<= nlstate; i++){        fprintf(ficrespow," %.12lf", p[i]);
     for(j=1; j<i;j++){      }
       for (nc=1, s2=0.;nc <=ncovmodel; nc++){      printf("\n");
         /*s2 += param[i][j][nc]*cov[nc];*/      fprintf(ficlog,"\n");
         s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];      fprintf(ficrespow,"\n");fflush(ficrespow);
         /*printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2);*/      if(*iter <=3){
       }        tm = *localtime(&curr_time.tv_sec);
       ps[i][j]=s2;        strcpy(strcurr,asctime(&tm));
       /*printf("s1=%.17e, s2=%.17e\n",s1,s2);*/  /*       asctime_r(&tm,strcurr); */
     }        forecast_time=curr_time;
     for(j=i+1; j<=nlstate+ndeath;j++){        itmp = strlen(strcurr);
       for (nc=1, s2=0.;nc <=ncovmodel; nc++){        if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
         s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];          strcurr[itmp-1]='\0';
         /*printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2);*/        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       }        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       ps[i][j]=s2;        for(niterf=10;niterf<=30;niterf+=10){
     }          forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
   }          tmf = *localtime(&forecast_time.tv_sec);
     /*ps[3][2]=1;*/  /*      asctime_r(&tmf,strfor); */
           strcpy(strfor,asctime(&tmf));
   for(i=1; i<= nlstate; i++){          itmp = strlen(strfor);
      s1=0;          if(strfor[itmp-1]=='\n')
     for(j=1; j<i; j++)          strfor[itmp-1]='\0';
       s1+=exp(ps[i][j]);          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);
     for(j=i+1; j<=nlstate+ndeath; j++)          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);
       s1+=exp(ps[i][j]);        }
     ps[i][i]=1./(s1+1.);      }
     for(j=1; j<i; j++)      for (i=1;i<=n;i++) {
       ps[i][j]= exp(ps[i][j])*ps[i][i];        for (j=1;j<=n;j++) xit[j]=xi[j][i];
     for(j=i+1; j<=nlstate+ndeath; j++)        fptt=(*fret);
       ps[i][j]= exp(ps[i][j])*ps[i][i];  #ifdef DEBUG
     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */        printf("fret=%lf \n",*fret);
   } /* end i */        fprintf(ficlog,"fret=%lf \n",*fret);
   #endif
   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){        printf("%d",i);fflush(stdout);
     for(jj=1; jj<= nlstate+ndeath; jj++){        fprintf(ficlog,"%d",i);fflush(ficlog);
       ps[ii][jj]=0;        linmin(p,xit,n,fret,func);
       ps[ii][ii]=1;        if (fabs(fptt-(*fret)) > del) {
     }          del=fabs(fptt-(*fret));
   }          ibig=i;
         }
   #ifdef DEBUG
   /*   for(ii=1; ii<= nlstate+ndeath; ii++){        printf("%d %.12e",i,(*fret));
     for(jj=1; jj<= nlstate+ndeath; jj++){        fprintf(ficlog,"%d %.12e",i,(*fret));
      printf("%lf ",ps[ii][jj]);        for (j=1;j<=n;j++) {
    }          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
     printf("\n ");          printf(" x(%d)=%.12e",j,xit[j]);
     }          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
     printf("\n ");printf("%lf ",cov[2]);*/        }
 /*        for(j=1;j<=n;j++) {
   for(i=1; i<= npar; i++) printf("%f ",x[i]);          printf(" p=%.12e",p[j]);
   goto end;*/          fprintf(ficlog," p=%.12e",p[j]);
     return ps;        }
 }        printf("\n");
         fprintf(ficlog,"\n");
 /**************** Product of 2 matrices ******************/  #endif
       }
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 {  #ifdef DEBUG
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times        int k[2],l;
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */        k[0]=1;
   /* in, b, out are matrice of pointers which should have been initialized         k[1]=-1;
      before: only the contents of out is modified. The function returns        printf("Max: %.12e",(*func)(p));
      a pointer to pointers identical to out */        fprintf(ficlog,"Max: %.12e",(*func)(p));
   long i, j, k;        for (j=1;j<=n;j++) {
   for(i=nrl; i<= nrh; i++)          printf(" %.12e",p[j]);
     for(k=ncolol; k<=ncoloh; k++)          fprintf(ficlog," %.12e",p[j]);
       for(j=ncl,out[i][k]=0.; j<=nch; j++)        }
         out[i][k] +=in[i][j]*b[j][k];        printf("\n");
         fprintf(ficlog,"\n");
   return out;        for(l=0;l<=1;l++) {
 }          for (j=1;j<=n;j++) {
             ptt[j]=p[j]+(p[j]-pt[j])*k[l];
             printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 /************* Higher Matrix Product ***************/            fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
           }
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )          printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 {          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
   /* Computes the transition matrix starting at age 'age' over         }
      'nhstepm*hstepm*stepm' months (i.e. until  #endif
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying   
      nhstepm*hstepm matrices.   
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step         free_vector(xit,1,n);
      (typically every 2 years instead of every month which is too big         free_vector(xits,1,n);
      for the memory).        free_vector(ptt,1,n);
      Model is determined by parameters x and covariates have to be         free_vector(pt,1,n);
      included manually here.         return;
       }
      */      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
       for (j=1;j<=n;j++) {
   int i, j, d, h, k;        ptt[j]=2.0*p[j]-pt[j];
   double **out, cov[NCOVMAX];        xit[j]=p[j]-pt[j];
   double **newm;        pt[j]=p[j];
       }
   /* Hstepm could be zero and should return the unit matrix */      fptt=(*func)(ptt);
   for (i=1;i<=nlstate+ndeath;i++)      if (fptt < fp) {
     for (j=1;j<=nlstate+ndeath;j++){        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
       oldm[i][j]=(i==j ? 1.0 : 0.0);        if (t < 0.0) {
       po[i][j][0]=(i==j ? 1.0 : 0.0);          linmin(p,xit,n,fret,func);
     }          for (j=1;j<=n;j++) {
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */            xi[j][ibig]=xi[j][n];
   for(h=1; h <=nhstepm; h++){            xi[j][n]=xit[j];
     for(d=1; d <=hstepm; d++){          }
       newm=savm;  #ifdef DEBUG
       /* Covariates have to be included here again */          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
       cov[1]=1.;          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;          for(j=1;j<=n;j++){
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];            printf(" %.12e",xit[j]);
       for (k=1; k<=cptcovage;k++)            fprintf(ficlog," %.12e",xit[j]);
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          }
       for (k=1; k<=cptcovprod;k++)          printf("\n");
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];          fprintf(ficlog,"\n");
   #endif
         }
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/      }
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/    }
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,   }
                    pmij(pmmij,cov,ncovmodel,x,nlstate));  
       savm=oldm;  /**** Prevalence limit (stable or period prevalence)  ****************/
       oldm=newm;  
     }  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
     for(i=1; i<=nlstate+ndeath; i++)  {
       for(j=1;j<=nlstate+ndeath;j++) {    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
         po[i][j][h]=newm[i][j];       matrix by transitions matrix until convergence is reached */
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);  
          */    int i, ii,j,k;
       }    double min, max, maxmin, maxmax,sumnew=0.;
   } /* end h */    double **matprod2();
   return po;    double **out, cov[NCOVMAX], **pmij();
 }    double **newm;
     double agefin, delaymax=50 ; /* Max number of years to converge */
   
 /*************** log-likelihood *************/    for (ii=1;ii<=nlstate+ndeath;ii++)
 double func( double *x)      for (j=1;j<=nlstate+ndeath;j++){
 {        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   int i, ii, j, k, mi, d, kk;      }
   double l, ll[NLSTATEMAX], cov[NCOVMAX];  
   double **out;     cov[1]=1.;
   double sw; /* Sum of weights */   
   double lli; /* Individual log likelihood */   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
   int s1, s2;    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
   double bbh, survp;      newm=savm;
   long ipmx;      /* Covariates have to be included here again */
   /*extern weight */       cov[2]=agefin;
   /* We are differentiating ll according to initial status */   
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/        for (k=1; k<=cptcovn;k++) {
   /*for(i=1;i<imx;i++)           cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
     printf(" %d\n",s[4][i]);          /*      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]]);*/
   */        }
   cov[1]=1.;        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         for (k=1; k<=cptcovprod;k++)
   for(k=1; k<=nlstate; k++) ll[k]=0.;          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
   
   if(mle==1){        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];        /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
       for(mi=1; mi<= wav[i]-1; mi++){      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
         for (ii=1;ii<=nlstate+ndeath;ii++)  
           for (j=1;j<=nlstate+ndeath;j++){      savm=oldm;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);      oldm=newm;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);      maxmax=0.;
           }      for(j=1;j<=nlstate;j++){
         for(d=0; d<dh[mi][i]; d++){        min=1.;
           newm=savm;        max=0.;
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        for(i=1; i<=nlstate; i++) {
           for (kk=1; kk<=cptcovage;kk++) {          sumnew=0;
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
           }          prlim[i][j]= newm[i][j]/(1-sumnew);
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          max=FMAX(max,prlim[i][j]);
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          min=FMIN(min,prlim[i][j]);
           savm=oldm;        }
           oldm=newm;        maxmin=max-min;
         } /* end mult */        maxmax=FMAX(maxmax,maxmin);
             }
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */      if(maxmax < ftolpl){
         /* But now since version 0.9 we anticipate for bias and large stepm.        return prlim;
          * 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     }
          * 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  /*************** transition probabilities ***************/
          * 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  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
          * -stepm/2 to stepm/2 .  {
          * For stepm=1 the results are the same as for previous versions of Imach.    double s1, s2;
          * For stepm > 1 the results are less biased than in previous versions.     /*double t34;*/
          */    int i,j,j1, nc, ii, jj;
         s1=s[mw[mi][i]][i];  
         s2=s[mw[mi+1][i]][i];      for(i=1; i<= nlstate; i++){
         bbh=(double)bh[mi][i]/(double)stepm;         for(j=1; j<i;j++){
         /* bias is positive if real duration          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
          * is higher than the multiple of stepm and negative otherwise.            /*s2 += param[i][j][nc]*cov[nc];*/
          */            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
         if( s2 > nlstate){           }
           /* i.e. if s2 is a death state and if the date of death is known then the contribution          ps[i][j]=s2;
              to the likelihood is the probability to die between last step unit time and current   /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
              step unit time, which is also the differences between probability to die before dh         }
              and probability to die before dh-stepm .         for(j=i+1; j<=nlstate+ndeath;j++){
              In version up to 0.92 likelihood was computed          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
         as if date of death was unknown. Death was treated as any other            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
         health state: the date of the interview describes the actual state  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
         and not the date of a change in health state. The former idea was          }
         to consider that at each interview the state was recorded          ps[i][j]=s2;
         (healthy, disable or death) and IMaCh was corrected; but when we        }
         introduced the exact date of death then we should have modified      }
         the contribution of an exact death to the likelihood. This new      /*ps[3][2]=1;*/
         contribution is smaller and very dependent of the step unit     
         stepm. It is no more the probability to die between last interview      for(i=1; i<= nlstate; i++){
         and month of death but the probability to survive from last        s1=0;
         interview up to one month before death multiplied by the        for(j=1; j<i; j++)
         probability to die within a month. Thanks to Chris          s1+=exp(ps[i][j]);
         Jackson for correcting this bug.  Former versions increased        for(j=i+1; j<=nlstate+ndeath; j++)
         mortality artificially. The bad side is that we add another loop          s1+=exp(ps[i][j]);
         which slows down the processing. The difference can be up to 10%        ps[i][i]=1./(s1+1.);
         lower mortality.        for(j=1; j<i; j++)
           */          ps[i][j]= exp(ps[i][j])*ps[i][i];
           lli=log(out[s1][s2] - savm[s1][s2]);        for(j=i+1; j<=nlstate+ndeath; j++)
         }else{          ps[i][j]= exp(ps[i][j])*ps[i][i];
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
           /*  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 */      } /* end i */
         }      
         /*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==2){  /*        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
         s1=s[mw[mi][i]][i];       a pointer to pointers identical to out */
         s2=s[mw[mi+1][i]][i];    long i, j, k;
         bbh=(double)bh[mi][i]/(double)stepm;     for(i=nrl; i<= nrh; 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 */      for(k=ncolol; k<=ncoloh; k++)
         ipmx +=1;        for(j=ncl,out[i][k]=0.; j<=nch; j++)
         sw += weight[i];          out[i][k] +=in[i][j]*b[j][k];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;  
       } /* end of wave */    return out;
     } /* end of individual */  }
   }  else if(mle==3){  /* exponential 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];  /************* Higher Matrix Product ***************/
       for(mi=1; mi<= wav[i]-1; mi++){  
         for (ii=1;ii<=nlstate+ndeath;ii++)  double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
           for (j=1;j<=nlstate+ndeath;j++){  {
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    /* Computes the transition matrix starting at age 'age' over
             savm[ii][j]=(ii==j ? 1.0 : 0.0);       'nhstepm*hstepm*stepm' months (i.e. until
           }       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
         for(d=0; d<dh[mi][i]; d++){       nhstepm*hstepm matrices.
           newm=savm;       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;       (typically every 2 years instead of every month which is too big
           for (kk=1; kk<=cptcovage;kk++) {       for the memory).
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];       Model is determined by parameters x and covariates have to be
           }       included manually here.
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,  
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));       */
           savm=oldm;  
           oldm=newm;    int i, j, d, h, k;
         } /* end mult */    double **out, cov[NCOVMAX];
           double **newm;
         s1=s[mw[mi][i]][i];  
         s2=s[mw[mi+1][i]][i];    /* Hstepm could be zero and should return the unit matrix */
         bbh=(double)bh[mi][i]/(double)stepm;     for (i=1;i<=nlstate+ndeath;i++)
         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 */      for (j=1;j<=nlstate+ndeath;j++){
         ipmx +=1;        oldm[i][j]=(i==j ? 1.0 : 0.0);
         sw += weight[i];        po[i][j][0]=(i==j ? 1.0 : 0.0);
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;      }
       } /* end of wave */    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
     } /* end of individual */    for(h=1; h <=nhstepm; h++){
   }else if (mle==4){  /* ml=4 no inter-extrapolation */      for(d=1; d <=hstepm; d++){
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){        newm=savm;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];        /* Covariates have to be included here again */
       for(mi=1; mi<= wav[i]-1; mi++){        cov[1]=1.;
         for (ii=1;ii<=nlstate+ndeath;ii++)        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
           for (j=1;j<=nlstate+ndeath;j++){        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);        for (k=1; k<=cptcovage;k++)
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           }        for (k=1; k<=cptcovprod;k++)
         for(d=0; d<dh[mi][i]; d++){          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
           newm=savm;  
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;  
           for (kk=1; kk<=cptcovage;kk++) {        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
           }        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                              pmij(pmmij,cov,ncovmodel,x,nlstate));
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,        savm=oldm;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));        oldm=newm;
           savm=oldm;      }
           oldm=newm;      for(i=1; i<=nlstate+ndeath; i++)
         } /* end mult */        for(j=1;j<=nlstate+ndeath;j++) {
                 po[i][j][h]=newm[i][j];
         s1=s[mw[mi][i]][i];          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
         s2=s[mw[mi+1][i]][i];           */
         if( s2 > nlstate){         }
           lli=log(out[s1][s2] - savm[s1][s2]);    } /* end h */
         }else{    return po;
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */  }
         }  
         ipmx +=1;  
         sw += weight[i];  /*************** log-likelihood *************/
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;  double func( double *x)
 /*      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]); */  {
       } /* end of wave */    int i, ii, j, k, mi, d, kk;
     } /* end of individual */    double l, ll[NLSTATEMAX], cov[NCOVMAX];
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */    double **out;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){    double sw; /* Sum of weights */
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];    double lli; /* Individual log likelihood */
       for(mi=1; mi<= wav[i]-1; mi++){    int s1, s2;
         for (ii=1;ii<=nlstate+ndeath;ii++)    double bbh, survp;
           for (j=1;j<=nlstate+ndeath;j++){    long ipmx;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    /*extern weight */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    /* We are differentiating ll according to initial status */
           }    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
         for(d=0; d<dh[mi][i]; d++){    /*for(i=1;i<imx;i++)
           newm=savm;      printf(" %d\n",s[4][i]);
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    */
           for (kk=1; kk<=cptcovage;kk++) {    cov[1]=1.;
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];  
           }    for(k=1; k<=nlstate; k++) ll[k]=0.;
           
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    if(mle==1){
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
           savm=oldm;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           oldm=newm;        for(mi=1; mi<= wav[i]-1; mi++){
         } /* end mult */          for (ii=1;ii<=nlstate+ndeath;ii++)
                   for (j=1;j<=nlstate+ndeath;j++){
         s1=s[mw[mi][i]][i];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         s2=s[mw[mi+1][i]][i];              savm[ii][j]=(ii==j ? 1.0 : 0.0);
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */            }
         ipmx +=1;          for(d=0; d<dh[mi][i]; d++){
         sw += weight[i];            newm=savm;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         /*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 (kk=1; kk<=cptcovage;kk++) {
       } /* end of wave */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     } /* end of individual */            }
   } /* End of if */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */            savm=oldm;
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */            oldm=newm;
   return -l;          } /* end mult */
 }       
           /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 /*************** log-likelihood *************/          /* But now since version 0.9 we anticipate for bias at large stepm.
 double funcone( double *x)           * 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
   /* Same as likeli but slower because of a lot of printf and if */           * the nearest (and in case of equal distance, to the lowest) interval but now
   int i, ii, j, k, mi, d, kk;           * we keep into memory the bias bh[mi][i] and also the previous matrix product
   double l, ll[NLSTATEMAX], cov[NCOVMAX];           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
   double **out;           * probability in order to take into account the bias as a fraction of the way
   double lli; /* Individual log likelihood */           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
   double llt;           * -stepm/2 to stepm/2 .
   int s1, s2;           * For stepm=1 the results are the same as for previous versions of Imach.
   double bbh, survp;           * For stepm > 1 the results are less biased than in previous versions.
   /*extern weight */           */
   /* We are differentiating ll according to initial status */          s1=s[mw[mi][i]][i];
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/          s2=s[mw[mi+1][i]][i];
   /*for(i=1;i<imx;i++)           bbh=(double)bh[mi][i]/(double)stepm;
     printf(" %d\n",s[4][i]);          /* bias bh is positive if real duration
   */           * is higher than the multiple of stepm and negative otherwise.
   cov[1]=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]));*/
   for(k=1; k<=nlstate; k++) ll[k]=0.;          if( s2 > nlstate){
             /* i.e. if s2 is a death state and if the date of death is known
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){               then the contribution to the likelihood is the probability to
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];               die between last step unit time and current  step unit time,
     for(mi=1; mi<= wav[i]-1; mi++){               which is also equal to probability to die before dh
       for (ii=1;ii<=nlstate+ndeath;ii++)               minus probability to die before dh-stepm .
         for (j=1;j<=nlstate+ndeath;j++){               In version up to 0.92 likelihood was computed
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);          as if date of death was unknown. Death was treated as any other
           savm[ii][j]=(ii==j ? 1.0 : 0.0);          health state: the date of the interview describes the actual state
         }          and not the date of a change in health state. The former idea was
       for(d=0; d<dh[mi][i]; d++){          to consider that at each interview the state was recorded
         newm=savm;          (healthy, disable or death) and IMaCh was corrected; but when we
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          introduced the exact date of death then we should have modified
         for (kk=1; kk<=cptcovage;kk++) {          the contribution of an exact death to the likelihood. This new
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          contribution is smaller and very dependent of the step unit
         }          stepm. It is no more the probability to die between last interview
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          and month of death but the probability to survive from last
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          interview up to one month before death multiplied by the
         savm=oldm;          probability to die within a month. Thanks to Chris
         oldm=newm;          Jackson for correcting this bug.  Former versions increased
       } /* end mult */          mortality artificially. The bad side is that we add another loop
                 which slows down the processing. The difference can be up to 10%
       s1=s[mw[mi][i]][i];          lower mortality.
       s2=s[mw[mi+1][i]][i];            */
       bbh=(double)bh[mi][i]/(double)stepm;             lli=log(out[s1][s2] - savm[s1][s2]);
       /* bias is positive if real duration  
        * is higher than the multiple of stepm and negative otherwise.  
        */          } else if  (s2==-2) {
       if( s2 > nlstate && (mle <5) ){  /* Jackson */            for (j=1,survp=0. ; j<=nlstate; j++)
         lli=log(out[s1][s2] - savm[s1][s2]);              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
       } else if (mle==1){            /*survp += out[s1][j]; */
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */            lli= log(survp);
       } else if(mle==2){          }
         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 */          else if  (s2==-4) {
         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 */            for (j=3,survp=0. ; j<=nlstate; j++)  
       } else if (mle==4){  /* mle=4 no inter-extrapolation */              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         lli=log(out[s1][s2]); /* Original formula */            lli= log(survp);
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */          }
         lli=log(out[s1][s2]); /* Original formula */  
       } /* End of if */          else if  (s2==-5) {
       ipmx +=1;            for (j=1,survp=0. ; j<=2; j++)  
       sw += weight[i];              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            lli= log(survp);
 /*       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]); */          }
       if(globpr){         
         fprintf(ficresilk,"%9d %6d %1d %1d %1d %1d %3d %10.6f %6.4f\          else{
  %10.6f %10.6f %10.6f ", \            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[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 */
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);          }
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
           llt +=ll[k]*gipmx/gsw;          /*if(lli ==000.0)*/
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);          /*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;
         fprintf(ficresilk," %10.6f\n", -llt);          sw += weight[i];
       }          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     } /* end of wave */        } /* end of wave */
   } /* end of individual */      } /* end of individual */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];    }  else if(mle==2){
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   if(globpr==0){ /* First time we count the contributions and weights */        for(mi=1; mi<= wav[i]-1; mi++){
     gipmx=ipmx;          for (ii=1;ii<=nlstate+ndeath;ii++)
     gsw=sw;            for (j=1;j<=nlstate+ndeath;j++){
   }              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   return -l;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
 }            }
           for(d=0; d<=dh[mi][i]; d++){
             newm=savm;
 /*************** function likelione ***********/            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))            for (kk=1; kk<=cptcovage;kk++) {
 {              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   /* This routine should help understanding what is done with             }
      the selection of individuals/waves and            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
      to check the exact contribution to the likelihood.                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
      Plotting could be done.            savm=oldm;
    */            oldm=newm;
   int k;          } /* end mult */
        
   if(*globpri !=0){ /* Just counts and sums, no printings */          s1=s[mw[mi][i]][i];
     strcpy(fileresilk,"ilk");           s2=s[mw[mi+1][i]][i];
     strcat(fileresilk,fileres);          bbh=(double)bh[mi][i]/(double)stepm;
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {          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("Problem with resultfile: %s\n", fileresilk);          ipmx +=1;
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);          sw += weight[i];
     }          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     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");        } /* end of wave */
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");      } /* end of individual */
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */    }  else if(mle==3){  /* exponential inter-extrapolation */
     for(k=1; k<=nlstate; k++)       for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");        for(mi=1; mi<= wav[i]-1; mi++){
   }          for (ii=1;ii<=nlstate+ndeath;ii++)
             for (j=1;j<=nlstate+ndeath;j++){
   *fretone=(*funcone)(p);              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   if(*globpri !=0){              savm[ii][j]=(ii==j ? 1.0 : 0.0);
     fclose(ficresilk);            }
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));          for(d=0; d<dh[mi][i]; d++){
     fflush(fichtm);             newm=savm;
   }             cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   return;            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,
 /*********** Maximum Likelihood Estimation ***************/                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
             savm=oldm;
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))            oldm=newm;
 {          } /* end mult */
   int i,j, iter;       
   double **xi;          s1=s[mw[mi][i]][i];
   double fret;          s2=s[mw[mi+1][i]][i];
   double fretone; /* Only one call to likelihood */          bbh=(double)bh[mi][i]/(double)stepm;
   char filerespow[FILENAMELENGTH];          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 */
   xi=matrix(1,npar,1,npar);          ipmx +=1;
   for (i=1;i<=npar;i++)          sw += weight[i];
     for (j=1;j<=npar;j++)          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       xi[i][j]=(i==j ? 1.0 : 0.0);        } /* end of wave */
   printf("Powell\n");  fprintf(ficlog,"Powell\n");      } /* end of individual */
   strcpy(filerespow,"pow");     }else if (mle==4){  /* ml=4 no inter-extrapolation */
   strcat(filerespow,fileres);      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   if((ficrespow=fopen(filerespow,"w"))==NULL) {        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
     printf("Problem with resultfile: %s\n", filerespow);        for(mi=1; mi<= wav[i]-1; mi++){
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);          for (ii=1;ii<=nlstate+ndeath;ii++)
   }            for (j=1;j<=nlstate+ndeath;j++){
   fprintf(ficrespow,"# Powell\n# iter -2*LL");              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   for (i=1;i<=nlstate;i++)              savm[ii][j]=(ii==j ? 1.0 : 0.0);
     for(j=1;j<=nlstate+ndeath;j++)            }
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);          for(d=0; d<dh[mi][i]; d++){
   fprintf(ficrespow,"\n");            newm=savm;
             cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   powell(p,xi,npar,ftol,&iter,&fret,func);            for (kk=1; kk<=cptcovage;kk++) {
               cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   fclose(ficrespow);            }
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));         
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
             savm=oldm;
 }            oldm=newm;
           } /* end mult */
 /**** Computes Hessian and covariance matrix ***/       
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))          s1=s[mw[mi][i]][i];
 {          s2=s[mw[mi+1][i]][i];
   double  **a,**y,*x,pd;          if( s2 > nlstate){
   double **hess;            lli=log(out[s1][s2] - savm[s1][s2]);
   int i, j,jk;          }else{
   int *indx;            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
           }
   double hessii(double p[], double delta, int theta, double delti[]);          ipmx +=1;
   double hessij(double p[], double delti[], int i, int j);          sw += weight[i];
   void lubksb(double **a, int npar, int *indx, double b[]) ;          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   void ludcmp(double **a, int npar, int *indx, double *d) ;  /*      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]); */
         } /* end of wave */
   hess=matrix(1,npar,1,npar);      } /* end of individual */
     }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
   printf("\nCalculation of the hessian matrix. Wait...\n");      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   for (i=1;i<=npar;i++){        for(mi=1; mi<= wav[i]-1; mi++){
     printf("%d",i);fflush(stdout);          for (ii=1;ii<=nlstate+ndeath;ii++)
     fprintf(ficlog,"%d",i);fflush(ficlog);            for (j=1;j<=nlstate+ndeath;j++){
     hess[i][i]=hessii(p,ftolhess,i,delti);              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     /*printf(" %f ",p[i]);*/              savm[ii][j]=(ii==j ? 1.0 : 0.0);
     /*printf(" %lf ",hess[i][i]);*/            }
   }          for(d=0; d<dh[mi][i]; d++){
               newm=savm;
   for (i=1;i<=npar;i++) {            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
     for (j=1;j<=npar;j++)  {            for (kk=1; kk<=cptcovage;kk++) {
       if (j>i) {               cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         printf(".%d%d",i,j);fflush(stdout);            }
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);         
         hess[i][j]=hessij(p,delti,i,j);            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         hess[j][i]=hess[i][j];                             1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         /*printf(" %lf ",hess[i][j]);*/            savm=oldm;
       }            oldm=newm;
     }          } /* end mult */
   }       
   printf("\n");          s1=s[mw[mi][i]][i];
   fprintf(ficlog,"\n");          s2=s[mw[mi+1][i]][i];
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");          ipmx +=1;
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");          sw += weight[i];
             ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   a=matrix(1,npar,1,npar);          /*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]);*/
   y=matrix(1,npar,1,npar);        } /* end of wave */
   x=vector(1,npar);      } /* end of individual */
   indx=ivector(1,npar);    } /* End of if */
   for (i=1;i<=npar;i++)    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   ludcmp(a,npar,indx,&pd);    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
     return -l;
   for (j=1;j<=npar;j++) {  }
     for (i=1;i<=npar;i++) x[i]=0;  
     x[j]=1;  /*************** log-likelihood *************/
     lubksb(a,npar,indx,x);  double funcone( double *x)
     for (i=1;i<=npar;i++){   {
       matcov[i][j]=x[i];    /* Same as likeli but slower because of a lot of printf and if */
     }    int i, ii, j, k, mi, d, kk;
   }    double l, ll[NLSTATEMAX], cov[NCOVMAX];
     double **out;
   printf("\n#Hessian matrix#\n");    double lli; /* Individual log likelihood */
   fprintf(ficlog,"\n#Hessian matrix#\n");    double llt;
   for (i=1;i<=npar;i++) {     int s1, s2;
     for (j=1;j<=npar;j++) {     double bbh, survp;
       printf("%.3e ",hess[i][j]);    /*extern weight */
       fprintf(ficlog,"%.3e ",hess[i][j]);    /* We are differentiating ll according to initial status */
     }    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     printf("\n");    /*for(i=1;i<imx;i++)
     fprintf(ficlog,"\n");      printf(" %d\n",s[4][i]);
   }    */
     cov[1]=1.;
   /* Recompute Inverse */  
   for (i=1;i<=npar;i++)    for(k=1; k<=nlstate; k++) ll[k]=0.;
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];  
   ludcmp(a,npar,indx,&pd);    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   /*  printf("\n#Hessian matrix recomputed#\n");      for(mi=1; mi<= wav[i]-1; mi++){
         for (ii=1;ii<=nlstate+ndeath;ii++)
   for (j=1;j<=npar;j++) {          for (j=1;j<=nlstate+ndeath;j++){
     for (i=1;i<=npar;i++) x[i]=0;            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     x[j]=1;            savm[ii][j]=(ii==j ? 1.0 : 0.0);
     lubksb(a,npar,indx,x);          }
     for (i=1;i<=npar;i++){         for(d=0; d<dh[mi][i]; d++){
       y[i][j]=x[i];          newm=savm;
       printf("%.3e ",y[i][j]);          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       fprintf(ficlog,"%.3e ",y[i][j]);          for (kk=1; kk<=cptcovage;kk++) {
     }            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     printf("\n");          }
     fprintf(ficlog,"\n");          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   }                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   */          savm=oldm;
           oldm=newm;
   free_matrix(a,1,npar,1,npar);        } /* end mult */
   free_matrix(y,1,npar,1,npar);       
   free_vector(x,1,npar);        s1=s[mw[mi][i]][i];
   free_ivector(indx,1,npar);        s2=s[mw[mi+1][i]][i];
   free_matrix(hess,1,npar,1,npar);        bbh=(double)bh[mi][i]/(double)stepm;
         /* bias is positive if real duration
          * is higher than the multiple of stepm and negative otherwise.
 }         */
         if( s2 > nlstate && (mle <5) ){  /* Jackson */
 /*************** hessian matrix ****************/          lli=log(out[s1][s2] - savm[s1][s2]);
 double hessii( double x[], double delta, int theta, double delti[])        } else if  (s2==-2) {
 {          for (j=1,survp=0. ; j<=nlstate; j++)
   int i;            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
   int l=1, lmax=20;          lli= log(survp);
   double k1,k2;        }else if (mle==1){
   double p2[NPARMAX+1];          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
   double res;        } else if(mle==2){
   double delt, delts, nkhi=10.,nkhif=1., khi=1.e-4;          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 */
   double fx;        } else if(mle==3){  /* exponential inter-extrapolation */
   int k=0,kmax=10;          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 */
   double l1;        } else if (mle==4){  /* mle=4 no inter-extrapolation */
           lli=log(out[s1][s2]); /* Original formula */
   fx=func(x);        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
   for (i=1;i<=npar;i++) p2[i]=x[i];          lli=log(out[s1][s2]); /* Original formula */
   for(l=0 ; l <=lmax; l++){        } /* End of if */
     l1=pow(10,l);        ipmx +=1;
     delts=delt;        sw += weight[i];
     for(k=1 ; k <kmax; k=k+1){        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       delt = delta*(l1*k);  /*       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]); */
       p2[theta]=x[theta] +delt;        if(globpr){
       k1=func(p2)-fx;          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
       p2[theta]=x[theta]-delt;   %11.6f %11.6f %11.6f ", \
       k2=func(p2)-fx;                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
       /*res= (k1-2.0*fx+k2)/delt/delt; */                  2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   llt +=ll[k]*gipmx/gsw;
 #ifdef DEBUG            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
       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(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);          fprintf(ficresilk," %10.6f\n", -llt);
 #endif        }
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */      } /* end of wave */
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){    } /* end of individual */
         k=kmax;    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
       }    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
         k=kmax; l=lmax*10.;    if(globpr==0){ /* First time we count the contributions and weights */
       }      gipmx=ipmx;
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){       gsw=sw;
         delts=delt;    }
       }    return -l;
     }  }
   }  
   delti[theta]=delts;  
   return res;   /*************** function likelione ***********/
     void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 }  {
     /* This routine should help understanding what is done with
 double hessij( double x[], double delti[], int thetai,int thetaj)       the selection of individuals/waves and
 {       to check the exact contribution to the likelihood.
   int i;       Plotting could be done.
   int l=1, l1, lmax=20;     */
   double k1,k2,k3,k4,res,fx;    int k;
   double p2[NPARMAX+1];  
   int k;    if(*globpri !=0){ /* Just counts and sums, no printings */
       strcpy(fileresilk,"ilk");
   fx=func(x);      strcat(fileresilk,fileres);
   for (k=1; k<=2; k++) {      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
     for (i=1;i<=npar;i++) p2[i]=x[i];        printf("Problem with resultfile: %s\n", fileresilk);
     p2[thetai]=x[thetai]+delti[thetai]/k;        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;      }
     k1=func(p2)-fx;      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 ");
     p2[thetai]=x[thetai]+delti[thetai]/k;      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;      for(k=1; k<=nlstate; k++)
     k2=func(p2)-fx;        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
         fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
     p2[thetai]=x[thetai]-delti[thetai]/k;    }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;  
     k3=func(p2)-fx;    *fretone=(*funcone)(p);
       if(*globpri !=0){
     p2[thetai]=x[thetai]-delti[thetai]/k;      fclose(ficresilk);
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
     k4=func(p2)-fx;      fflush(fichtm);
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */    }
 #ifdef DEBUG    return;
     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);  }
     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);  
 #endif  
   }  /*********** Maximum Likelihood Estimation ***************/
   return res;  
 }  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   {
 /************** Inverse of matrix **************/    int i,j, iter;
 void ludcmp(double **a, int n, int *indx, double *d)     double **xi;
 {     double fret;
   int i,imax,j,k;     double fretone; /* Only one call to likelihood */
   double big,dum,sum,temp;     /*  char filerespow[FILENAMELENGTH];*/
   double *vv;     xi=matrix(1,npar,1,npar);
      for (i=1;i<=npar;i++)
   vv=vector(1,n);       for (j=1;j<=npar;j++)
   *d=1.0;         xi[i][j]=(i==j ? 1.0 : 0.0);
   for (i=1;i<=n;i++) {     printf("Powell\n");  fprintf(ficlog,"Powell\n");
     big=0.0;     strcpy(filerespow,"pow");
     for (j=1;j<=n;j++)     strcat(filerespow,fileres);
       if ((temp=fabs(a[i][j])) > big) big=temp;     if((ficrespow=fopen(filerespow,"w"))==NULL) {
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");       printf("Problem with resultfile: %s\n", filerespow);
     vv[i]=1.0/big;       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
   }     }
   for (j=1;j<=n;j++) {     fprintf(ficrespow,"# Powell\n# iter -2*LL");
     for (i=1;i<j;i++) {     for (i=1;i<=nlstate;i++)
       sum=a[i][j];       for(j=1;j<=nlstate+ndeath;j++)
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
       a[i][j]=sum;     fprintf(ficrespow,"\n");
     }   
     big=0.0;     powell(p,xi,npar,ftol,&iter,&fret,func);
     for (i=j;i<=n;i++) {   
       sum=a[i][j];     free_matrix(xi,1,npar,1,npar);
       for (k=1;k<j;k++)     fclose(ficrespow);
         sum -= a[i][k]*a[k][j];     printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
       a[i][j]=sum;     fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
       if ( (dum=vv[i]*fabs(sum)) >= big) {     fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
         big=dum;   
         imax=i;   }
       }   
     }   /**** Computes Hessian and covariance matrix ***/
     if (j != imax) {   void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
       for (k=1;k<=n;k++) {   {
         dum=a[imax][k];     double  **a,**y,*x,pd;
         a[imax][k]=a[j][k];     double **hess;
         a[j][k]=dum;     int i, j,jk;
       }     int *indx;
       *d = -(*d);   
       vv[imax]=vv[j];     double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
     }     double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
     indx[j]=imax;     void lubksb(double **a, int npar, int *indx, double b[]) ;
     if (a[j][j] == 0.0) a[j][j]=TINY;     void ludcmp(double **a, int npar, int *indx, double *d) ;
     if (j != n) {     double gompertz(double p[]);
       dum=1.0/(a[j][j]);     hess=matrix(1,npar,1,npar);
       for (i=j+1;i<=n;i++) a[i][j] *= dum;   
     }     printf("\nCalculation of the hessian matrix. Wait...\n");
   }     fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
   free_vector(vv,1,n);  /* Doesn't work */    for (i=1;i<=npar;i++){
 ;      printf("%d",i);fflush(stdout);
 }       fprintf(ficlog,"%d",i);fflush(ficlog);
      
 void lubksb(double **a, int n, int *indx, double b[])        hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 {      
   int i,ii=0,ip,j;       /*  printf(" %f ",p[i]);
   double sum;           printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
      }
   for (i=1;i<=n;i++) {    
     ip=indx[i];     for (i=1;i<=npar;i++) {
     sum=b[ip];       for (j=1;j<=npar;j++)  {
     b[ip]=b[i];         if (j>i) {
     if (ii)           printf(".%d%d",i,j);fflush(stdout);
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];           fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
     else if (sum) ii=i;           hess[i][j]=hessij(p,delti,i,j,func,npar);
     b[i]=sum;          
   }           hess[j][i]=hess[i][j];    
   for (i=n;i>=1;i--) {           /*printf(" %lf ",hess[i][j]);*/
     sum=b[i];         }
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];       }
     b[i]=sum/a[i][i];     }
   }     printf("\n");
 }     fprintf(ficlog,"\n");
   
 /************ Frequencies ********************/    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 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)    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 {  /* Some frequencies */   
       a=matrix(1,npar,1,npar);
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;    y=matrix(1,npar,1,npar);
   int first;    x=vector(1,npar);
   double ***freq; /* Frequencies */    indx=ivector(1,npar);
   double *pp, **prop;    for (i=1;i<=npar;i++)
   double pos,posprop, k2, dateintsum=0,k2cpt=0;      for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
   FILE *ficresp;    ludcmp(a,npar,indx,&pd);
   char fileresp[FILENAMELENGTH];  
       for (j=1;j<=npar;j++) {
   pp=vector(1,nlstate);      for (i=1;i<=npar;i++) x[i]=0;
   prop=matrix(1,nlstate,iagemin,iagemax+3);      x[j]=1;
   strcpy(fileresp,"p");      lubksb(a,npar,indx,x);
   strcat(fileresp,fileres);      for (i=1;i<=npar;i++){
   if((ficresp=fopen(fileresp,"w"))==NULL) {        matcov[i][j]=x[i];
     printf("Problem with prevalence resultfile: %s\n", fileresp);      }
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);    }
     exit(0);  
   }    printf("\n#Hessian matrix#\n");
   freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);    fprintf(ficlog,"\n#Hessian matrix#\n");
   j1=0;    for (i=1;i<=npar;i++) {
         for (j=1;j<=npar;j++) {
   j=cptcoveff;        printf("%.3e ",hess[i][j]);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}        fprintf(ficlog,"%.3e ",hess[i][j]);
       }
   first=1;      printf("\n");
       fprintf(ficlog,"\n");
   for(k1=1; k1<=j;k1++){    }
     for(i1=1; i1<=ncodemax[k1];i1++){  
       j1++;    /* Recompute Inverse */
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    for (i=1;i<=npar;i++)
         scanf("%d", i);*/      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
       for (i=-1; i<=nlstate+ndeath; i++)      ludcmp(a,npar,indx,&pd);
         for (jk=-1; jk<=nlstate+ndeath; jk++)    
           for(m=iagemin; m <= iagemax+3; m++)    /*  printf("\n#Hessian matrix recomputed#\n");
             freq[i][jk][m]=0;  
     for (j=1;j<=npar;j++) {
     for (i=1; i<=nlstate; i++)        for (i=1;i<=npar;i++) x[i]=0;
       for(m=iagemin; m <= iagemax+3; m++)      x[j]=1;
         prop[i][m]=0;      lubksb(a,npar,indx,x);
             for (i=1;i<=npar;i++){
       dateintsum=0;        y[i][j]=x[i];
       k2cpt=0;        printf("%.3e ",y[i][j]);
       for (i=1; i<=imx; i++) {        fprintf(ficlog,"%.3e ",y[i][j]);
         bool=1;      }
         if  (cptcovn>0) {      printf("\n");
           for (z1=1; z1<=cptcoveff; z1++)       fprintf(ficlog,"\n");
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     }
               bool=0;    */
         }  
         if (bool==1){    free_matrix(a,1,npar,1,npar);
           for(m=firstpass; m<=lastpass; m++){    free_matrix(y,1,npar,1,npar);
             k2=anint[m][i]+(mint[m][i]/12.);    free_vector(x,1,npar);
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/    free_ivector(indx,1,npar);
               if(agev[m][i]==0) agev[m][i]=iagemax+1;    free_matrix(hess,1,npar,1,npar);
               if(agev[m][i]==1) agev[m][i]=iagemax+2;  
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];  
               if (m<lastpass) {  }
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];  
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];  /*************** hessian matrix ****************/
               }  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                 {
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {    int i;
                 dateintsum=dateintsum+k2;    int l=1, lmax=20;
                 k2cpt++;    double k1,k2;
               }    double p2[NPARMAX+1];
               /*}*/    double res;
           }    double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
         }    double fx;
       }    int k=0,kmax=10;
            double l1;
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/  
     fx=func(x);
       if  (cptcovn>0) {    for (i=1;i<=npar;i++) p2[i]=x[i];
         fprintf(ficresp, "\n#********** Variable ");     for(l=0 ; l <=lmax; l++){
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      l1=pow(10,l);
         fprintf(ficresp, "**********\n#");      delts=delt;
       }      for(k=1 ; k <kmax; k=k+1){
       for(i=1; i<=nlstate;i++)         delt = delta*(l1*k);
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);        p2[theta]=x[theta] +delt;
       fprintf(ficresp, "\n");        k1=func(p2)-fx;
               p2[theta]=x[theta]-delt;
       for(i=iagemin; i <= iagemax+3; i++){        k2=func(p2)-fx;
         if(i==iagemax+3){        /*res= (k1-2.0*fx+k2)/delt/delt; */
           fprintf(ficlog,"Total");        res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
         }else{       
           if(first==1){  #ifdef DEBUG
             first=0;        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);
             printf("See log file for details...\n");        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
           fprintf(ficlog,"Age %d", i);        /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
         }        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
         for(jk=1; jk <=nlstate ; jk++){          k=kmax;
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)        }
             pp[jk] += freq[jk][m][i];         else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
         }          k=kmax; l=lmax*10.;
         for(jk=1; jk <=nlstate ; jk++){        }
           for(m=-1, pos=0; m <=0 ; m++)        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
             pos += freq[jk][m][i];          delts=delt;
           if(pp[jk]>=1.e-10){        }
             if(first==1){      }
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);    }
             }    delti[theta]=delts;
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);    return res;
           }else{   
             if(first==1)  }
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);  
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);  double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
           }  {
         }    int i;
     int l=1, l1, lmax=20;
         for(jk=1; jk <=nlstate ; jk++){    double k1,k2,k3,k4,res,fx;
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)    double p2[NPARMAX+1];
             pp[jk] += freq[jk][m][i];    int k;
         }         
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){    fx=func(x);
           pos += pp[jk];    for (k=1; k<=2; k++) {
           posprop += prop[jk][i];      for (i=1;i<=npar;i++) p2[i]=x[i];
         }      p2[thetai]=x[thetai]+delti[thetai]/k;
         for(jk=1; jk <=nlstate ; jk++){      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
           if(pos>=1.e-5){      k1=func(p2)-fx;
             if(first==1)   
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);      p2[thetai]=x[thetai]+delti[thetai]/k;
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
           }else{      k2=func(p2)-fx;
             if(first==1)   
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);      p2[thetai]=x[thetai]-delti[thetai]/k;
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
           }      k3=func(p2)-fx;
           if( i <= iagemax){   
             if(pos>=1.e-5){      p2[thetai]=x[thetai]-delti[thetai]/k;
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
               /*probs[i][jk][j1]= pp[jk]/pos;*/      k4=func(p2)-fx;
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/      res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
             }  #ifdef DEBUG
             else      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);
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);      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);
           }  #endif
         }    }
             return res;
         for(jk=-1; jk <=nlstate+ndeath; jk++)  }
           for(m=-1; m <=nlstate+ndeath; m++)  
             if(freq[jk][m][i] !=0 ) {  /************** Inverse of matrix **************/
             if(first==1)  void ludcmp(double **a, int n, int *indx, double *d)
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);  {
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);    int i,imax,j,k;
             }    double big,dum,sum,temp;
         if(i <= iagemax)    double *vv;
           fprintf(ficresp,"\n");   
         if(first==1)    vv=vector(1,n);
           printf("Others in log...\n");    *d=1.0;
         fprintf(ficlog,"\n");    for (i=1;i<=n;i++) {
       }      big=0.0;
     }      for (j=1;j<=n;j++)
   }        if ((temp=fabs(a[i][j])) > big) big=temp;
   dateintmean=dateintsum/k2cpt;       if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
        vv[i]=1.0/big;
   fclose(ficresp);    }
   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);    for (j=1;j<=n;j++) {
   free_vector(pp,1,nlstate);      for (i=1;i<j;i++) {
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);        sum=a[i][j];
   /* End of Freq */        for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
 }        a[i][j]=sum;
       }
 /************ Prevalence ********************/      big=0.0;
 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)      for (i=j;i<=n;i++) {
 {          sum=a[i][j];
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people        for (k=1;k<j;k++)
      in each health status at the date of interview (if between dateprev1 and dateprev2).          sum -= a[i][k]*a[k][j];
      We still use firstpass and lastpass as another selection.        a[i][j]=sum;
   */        if ( (dum=vv[i]*fabs(sum)) >= big) {
            big=dum;
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;          imax=i;
   double ***freq; /* Frequencies */        }
   double *pp, **prop;      }
   double pos,posprop;       if (j != imax) {
   double  y2; /* in fractional years */        for (k=1;k<=n;k++) {
   int iagemin, iagemax;          dum=a[imax][k];
           a[imax][k]=a[j][k];
   iagemin= (int) agemin;          a[j][k]=dum;
   iagemax= (int) agemax;        }
   /*pp=vector(1,nlstate);*/        *d = -(*d);
   prop=matrix(1,nlstate,iagemin,iagemax+3);         vv[imax]=vv[j];
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/      }
   j1=0;      indx[j]=imax;
         if (a[j][j] == 0.0) a[j][j]=TINY;
   j=cptcoveff;      if (j != n) {
   if (cptcovn<1) {j=1;ncodemax[1]=1;}        dum=1.0/(a[j][j]);
           for (i=j+1;i<=n;i++) a[i][j] *= dum;
   for(k1=1; k1<=j;k1++){      }
     for(i1=1; i1<=ncodemax[k1];i1++){    }
       j1++;    free_vector(vv,1,n);  /* Doesn't work */
         ;
       for (i=1; i<=nlstate; i++)    }
         for(m=iagemin; m <= iagemax+3; m++)  
           prop[i][m]=0.0;  void lubksb(double **a, int n, int *indx, double b[])
        {
       for (i=1; i<=imx; i++) { /* Each individual */    int i,ii=0,ip,j;
         bool=1;    double sum;
         if  (cptcovn>0) {   
           for (z1=1; z1<=cptcoveff; z1++)     for (i=1;i<=n;i++) {
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])       ip=indx[i];
               bool=0;      sum=b[ip];
         }       b[ip]=b[i];
         if (bool==1) {       if (ii)
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */      else if (sum) ii=i;
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */      b[i]=sum;
               if(agev[m][i]==0) agev[m][i]=iagemax+1;    }
               if(agev[m][i]==1) agev[m][i]=iagemax+2;    for (i=n;i>=1;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);       sum=b[i];
               if (s[m][i]>0 && s[m][i]<=nlstate) {       for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
                 /*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]]);*/      b[i]=sum/a[i][i];
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];    }
                 prop[s[m][i]][iagemax+3] += weight[i];   }
               }   
             }  void pstamp(FILE *fichier)
           } /* end selection of waves */  {
         }    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
       }  }
       for(i=iagemin; i <= iagemax+3; i++){    
           /************ Frequencies ********************/
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {   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[])
           posprop += prop[jk][i];   {  /* Some frequencies */
         }    
     int i, m, jk, k1,i1, j1, bool, z1,z2,j;
         for(jk=1; jk <=nlstate ; jk++){         int first;
           if( i <=  iagemax){     double ***freq; /* Frequencies */
             if(posprop>=1.e-5){     double *pp, **prop;
               probs[i][jk][j1]= prop[jk][i]/posprop;    double pos,posprop, k2, dateintsum=0,k2cpt=0;
             }     char fileresp[FILENAMELENGTH];
           }    
         }/* end jk */     pp=vector(1,nlstate);
       }/* end i */     prop=matrix(1,nlstate,iagemin,iagemax+3);
     } /* end i1 */    strcpy(fileresp,"p");
   } /* end k1 */    strcat(fileresp,fileres);
       if((ficresp=fopen(fileresp,"w"))==NULL) {
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/      printf("Problem with prevalence resultfile: %s\n", fileresp);
   /*free_vector(pp,1,nlstate);*/      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);      exit(0);
 }  /* End of prevalence */    }
     freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 /************* Waves Concatenation ***************/    j1=0;
    
 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)    j=cptcoveff;
 {    if (cptcovn<1) {j=1;ncodemax[1]=1;}
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.  
      Death is a valid wave (if date is known).    first=1;
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i  
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]    for(k1=1; k1<=j;k1++){
      and mw[mi+1][i]. dh depends on stepm.      for(i1=1; i1<=ncodemax[k1];i1++){
      */        j1++;
         /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
   int i, mi, m;          scanf("%d", i);*/
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;        for (i=-5; i<=nlstate+ndeath; i++)  
      double sum=0., jmean=0.;*/          for (jk=-5; jk<=nlstate+ndeath; jk++)  
   int first;            for(m=iagemin; m <= iagemax+3; m++)
   int j, k=0,jk, ju, jl;              freq[i][jk][m]=0;
   double sum=0.;  
   first=0;      for (i=1; i<=nlstate; i++)  
   jmin=1e+5;        for(m=iagemin; m <= iagemax+3; m++)
   jmax=-1;          prop[i][m]=0;
   jmean=0.;       
   for(i=1; i<=imx; i++){        dateintsum=0;
     mi=0;        k2cpt=0;
     m=firstpass;        for (i=1; i<=imx; i++) {
     while(s[m][i] <= nlstate){          bool=1;
       if(s[m][i]>=1)          if  (cptcovn>0) {
         mw[++mi][i]=m;            for (z1=1; z1<=cptcoveff; z1++)
       if(m >=lastpass)              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
         break;                bool=0;
       else          }
         m++;          if (bool==1){
     }/* end while */            for(m=firstpass; m<=lastpass; m++){
     if (s[m][i] > nlstate){              k2=anint[m][i]+(mint[m][i]/12.);
       mi++;     /* Death is another wave */              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
       /* if(mi==0)  never been interviewed correctly before death */                if(agev[m][i]==0) agev[m][i]=iagemax+1;
          /* Only death is a correct wave */                if(agev[m][i]==1) agev[m][i]=iagemax+2;
       mw[mi][i]=m;                if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
     }                if (m<lastpass) {
                   freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
     wav[i]=mi;                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
     if(mi==0){                }
       nbwarn++;               
       if(first==0){                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
         printf("Warning! None valid information for:%ld line=%d (skipped) and may be others, see log file\n",num[i],i);                  dateintsum=dateintsum+k2;
         first=1;                  k2cpt++;
       }                }
       if(first==1){                /*}*/
         fprintf(ficlog,"Warning! None valid information for:%ld line=%d (skipped)\n",num[i],i);            }
       }          }
     } /* end mi==0 */        }
   } /* End individuals */         
         /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
   for(i=1; i<=imx; i++){        pstamp(ficresp);
     for(mi=1; mi<wav[i];mi++){        if  (cptcovn>0) {
       if (stepm <=0)          fprintf(ficresp, "\n#********** Variable ");
         dh[mi][i]=1;          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
       else{          fprintf(ficresp, "**********\n#");
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */        }
           if (agedc[i] < 2*AGESUP) {        for(i=1; i<=nlstate;i++)
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);           fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
             if(j==0) j=1;  /* Survives at least one month after exam */        fprintf(ficresp, "\n");
             else if(j<0){       
               nberr++;        for(i=iagemin; i <= iagemax+3; i++){
               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(i==iagemax+3){
               j=1; /* Temporary Dangerous patch */            fprintf(ficlog,"Total");
               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);          }else{
               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]);            if(first==1){
               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);              first=0;
             }              printf("See log file for details...\n");
             k=k+1;            }
             if (j >= jmax) jmax=j;            fprintf(ficlog,"Age %d", i);
             if (j <= jmin) jmin=j;          }
             sum=sum+j;          for(jk=1; jk <=nlstate ; jk++){
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/              pp[jk] += freq[jk][m][i];
           }          }
         }          for(jk=1; jk <=nlstate ; jk++){
         else{            for(m=-1, pos=0; m <=0 ; m++)
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));              pos += freq[jk][m][i];
           /*      printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/            if(pp[jk]>=1.e-10){
           k=k+1;              if(first==1){
           if (j >= jmax) jmax=j;              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
           else if (j <= jmin)jmin=j;              }
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
           /*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]);*/            }else{
           if(j<0){              if(first==1)
             nberr++;                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             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]);              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             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]);            }
           }          }
           sum=sum+j;  
         }          for(jk=1; jk <=nlstate ; jk++){
         jk= j/stepm;            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
         jl= j -jk*stepm;              pp[jk] += freq[jk][m][i];
         ju= j -(jk+1)*stepm;          }      
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
           if(jl==0){            pos += pp[jk];
             dh[mi][i]=jk;            posprop += prop[jk][i];
             bh[mi][i]=0;          }
           }else{ /* We want a negative bias in order to only have interpolation ie          for(jk=1; jk <=nlstate ; jk++){
                   * at the price of an extra matrix product in likelihood */            if(pos>=1.e-5){
             dh[mi][i]=jk+1;              if(first==1)
             bh[mi][i]=ju;                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
           }              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
         }else{            }else{
           if(jl <= -ju){              if(first==1)
             dh[mi][i]=jk;                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
             bh[mi][i]=jl;       /* bias is positive if real duration              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                                  * is higher than the multiple of stepm and negative otherwise.            }
                                  */            if( i <= iagemax){
           }              if(pos>=1.e-5){
           else{                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
             dh[mi][i]=jk+1;                /*probs[i][jk][j1]= pp[jk]/pos;*/
             bh[mi][i]=ju;                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
           }              }
           if(dh[mi][i]==0){              else
             dh[mi][i]=1; /* At least one step */                fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
             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);*/          }
           }         
         } /* end if mle */          for(jk=-1; jk <=nlstate+ndeath; jk++)
       }            for(m=-1; m <=nlstate+ndeath; m++)
     } /* end wave */              if(freq[jk][m][i] !=0 ) {
   }              if(first==1)
   jmean=sum/k;                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
   fprintf(ficlog,"Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);              }
  }          if(i <= iagemax)
             fprintf(ficresp,"\n");
 /*********** Tricode ****************************/          if(first==1)
 void tricode(int *Tvar, int **nbcode, int imx)            printf("Others in log...\n");
 {          fprintf(ficlog,"\n");
           }
   int Ndum[20],ij=1, k, j, i, maxncov=19;      }
   int cptcode=0;    }
   cptcoveff=0;     dateintmean=dateintsum/k2cpt;
     
   for (k=0; k<maxncov; k++) Ndum[k]=0;    fclose(ficresp);
   for (k=1; k<=7; k++) ncodemax[k]=0;    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
     free_vector(pp,1,nlstate);
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum     /* End of Freq */
                                modality*/   }
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/  
       Ndum[ij]++; /*store the modality */  /************ Prevalence ********************/
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/  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)
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable   {  
                                        Tvar[j]. If V=sex and male is 0 and     /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                                        female is 1, then  cptcode=1.*/       in each health status at the date of interview (if between dateprev1 and dateprev2).
     }       We still use firstpass and lastpass as another selection.
     */
     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 */    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
     }    double ***freq; /* Frequencies */
     double *pp, **prop;
     ij=1;     double pos,posprop;
     for (i=1; i<=ncodemax[j]; i++) {    double  y2; /* in fractional years */
       for (k=0; k<= maxncov; k++) {    int iagemin, iagemax;
         if (Ndum[k] != 0) {  
           nbcode[Tvar[j]][ij]=k;     iagemin= (int) agemin;
           /* 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; */    iagemax= (int) agemax;
               /*pp=vector(1,nlstate);*/
           ij++;    prop=matrix(1,nlstate,iagemin,iagemax+3);
         }    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
         if (ij > ncodemax[j]) break;     j1=0;
       }     
     }     j=cptcoveff;
   }      if (cptcovn<1) {j=1;ncodemax[1]=1;}
    
  for (k=0; k< maxncov; k++) Ndum[k]=0;    for(k1=1; k1<=j;k1++){
       for(i1=1; i1<=ncodemax[k1];i1++){
  for (i=1; i<=ncovmodel-2; i++) {         j1++;
    /* Listing of all covariables in staement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/       
    ij=Tvar[i];        for (i=1; i<=nlstate; i++)  
    Ndum[ij]++;          for(m=iagemin; m <= iagemax+3; m++)
  }            prop[i][m]=0.0;
        
  ij=1;        for (i=1; i<=imx; i++) { /* Each individual */
  for (i=1; i<= maxncov; i++) {          bool=1;
    if((Ndum[i]!=0) && (i<=ncovcol)){          if  (cptcovn>0) {
      Tvaraff[ij]=i; /*For printing */            for (z1=1; z1<=cptcoveff; z1++)
      ij++;              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
    }                bool=0;
  }          }
            if (bool==1) {
  cptcoveff=ij-1; /*Number of simple covariates*/            for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 }              y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
               if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 /*********** Health Expectancies ****************/                if(agev[m][i]==0) agev[m][i]=iagemax+1;
                 if(agev[m][i]==1) agev[m][i]=iagemax+2;
 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((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);
                 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]]);*/
   /* Health expectancies */                  prop[s[m][i]][(int)agev[m][i]] += weight[i];
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;                  prop[s[m][i]][iagemax+3] += weight[i];
   double age, agelim, hf;                }
   double ***p3mat,***varhe;              }
   double **dnewm,**doldm;            } /* end selection of waves */
   double *xp;          }
   double **gp, **gm;        }
   double ***gradg, ***trgradg;        for(i=iagemin; i <= iagemax+3; i++){  
   int theta;         
           for(jk=1,posprop=0; jk <=nlstate ; jk++) {
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);            posprop += prop[jk][i];
   xp=vector(1,npar);          }
   dnewm=matrix(1,nlstate*nlstate,1,npar);  
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);          for(jk=1; jk <=nlstate ; jk++){    
               if( i <=  iagemax){
   fprintf(ficreseij,"# Health expectancies\n");              if(posprop>=1.e-5){
   fprintf(ficreseij,"# Age");                probs[i][jk][j1]= prop[jk][i]/posprop;
   for(i=1; i<=nlstate;i++)              }
     for(j=1; j<=nlstate;j++)            }
       fprintf(ficreseij," %1d-%1d (SE)",i,j);          }/* end jk */
   fprintf(ficreseij,"\n");        }/* end i */
       } /* end i1 */
   if(estepm < stepm){    } /* end k1 */
     printf ("Problem %d lower than %d\n",estepm, stepm);   
   }    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
   else  hstepm=estepm;       /*free_vector(pp,1,nlstate);*/
   /* We compute the life expectancy from trapezoids spaced every estepm months    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
    * This is mainly to measure the difference between two models: for example  }  /* End of prevalence */
    * 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   /************* Waves Concatenation ***************/
    * progression in between and thus overestimating or underestimating according  
    * to the curvature of the survival function. If, for the same date, we   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)
    * 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     /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
    * hypothesis. A more precise result, taking into account a more precise       Death is a valid wave (if date is known).
    * curvature will be obtained if estepm is as small as stepm. */       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
        dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
   /* For example we decided to compute the life expectancy with the smallest unit */       and mw[mi+1][i]. dh depends on stepm.
   /* 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   
      nstepm is the number of stepm from age to agelin.     int i, mi, m;
      Look at hpijx to understand the reason of that which relies in memory size    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
      and note for a fixed period like estepm months */       double sum=0., jmean=0.;*/
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    int first;
      survival function given by stepm (the optimization length). Unfortunately it    int j, k=0,jk, ju, jl;
      means that if the survival funtion is printed only each two years of age and if    double sum=0.;
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     first=0;
      results. So we changed our mind and took the option of the best precision.    jmin=1e+5;
   */    jmax=-1;
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     jmean=0.;
     for(i=1; i<=imx; i++){
   agelim=AGESUP;      mi=0;
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */      m=firstpass;
     /* nhstepm age range expressed in number of stepm */      while(s[m][i] <= nlstate){
     nstepm=(int) rint((agelim-age)*YEARM/stepm);         if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
     /* Typically if 20 years nstepm = 20*12/6=40 stepm */           mw[++mi][i]=m;
     /* if (stepm >= YEARM) hstepm=1;*/        if(m >=lastpass)
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */          break;
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        else
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);          m++;
     gp=matrix(0,nhstepm,1,nlstate*nlstate);      }/* end while */
     gm=matrix(0,nhstepm,1,nlstate*nlstate);      if (s[m][i] > nlstate){
         mi++;     /* Death is another wave */
     /* Computed by stepm unit matrices, product of hstepm matrices, stored        /* if(mi==0)  never been interviewed correctly before death */
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */           /* Only death is a correct wave */
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);          mw[mi][i]=m;
        }
   
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */      wav[i]=mi;
       if(mi==0){
     /* Computing  Variances of health expectancies */        nbwarn++;
         if(first==0){
      for(theta=1; theta <=npar; theta++){          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
       for(i=1; i<=npar; i++){           first=1;
         xp[i] = x[i] + (i==theta ?delti[theta]:0);        }
       }        if(first==1){
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);            fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
           }
       cptj=0;      } /* end mi==0 */
       for(j=1; j<= nlstate; j++){    } /* End individuals */
         for(i=1; i<=nlstate; i++){  
           cptj=cptj+1;    for(i=1; i<=imx; i++){
           for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){      for(mi=1; mi<wav[i];mi++){
             gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;        if (stepm <=0)
           }          dh[mi][i]=1;
         }        else{
       }          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                  if (agedc[i] < 2*AGESUP) {
                    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
       for(i=1; i<=npar; i++)               if(j==0) j=1;  /* Survives at least one month after exam */
         xp[i] = x[i] - (i==theta ?delti[theta]:0);              else if(j<0){
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);                  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]);
       cptj=0;                j=1; /* Temporary Dangerous patch */
       for(j=1; j<= nlstate; j++){                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);
         for(i=1;i<=nlstate;i++){                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]);
           cptj=cptj+1;                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(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){              }
               k=k+1;
             gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;              if (j >= jmax){
           }                jmax=j;
         }                ijmax=i;
       }              }
       for(j=1; j<= nlstate*nlstate; j++)              if (j <= jmin){
         for(h=0; h<=nhstepm-1; h++){                jmin=j;
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];                ijmin=i;
         }              }
      }               sum=sum+j;
                  /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 /* End theta */              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
             }
      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);          }
           else{
      for(h=0; h<=nhstepm-1; h++)            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
       for(j=1; j<=nlstate*nlstate;j++)  /*        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]); */
         for(theta=1; theta <=npar; theta++)  
           trgradg[h][j][theta]=gradg[h][theta][j];            k=k+1;
                  if (j >= jmax) {
               jmax=j;
      for(i=1;i<=nlstate*nlstate;i++)              ijmax=i;
       for(j=1;j<=nlstate*nlstate;j++)            }
         varhe[i][j][(int)age] =0.;            else if (j <= jmin){
               jmin=j;
      printf("%d|",(int)age);fflush(stdout);              ijmin=i;
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);            }
      for(h=0;h<=nhstepm-1;h++){            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
       for(k=0;k<=nhstepm-1;k++){            /*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]);*/
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);            if(j<0){
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);              nberr++;
         for(i=1;i<=nlstate*nlstate;i++)              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(j=1;j<=nlstate*nlstate;j++)              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]);
             varhe[i][j][(int)age] += doldm[i][j]*hf*hf;            }
       }            sum=sum+j;
     }          }
     /* Computing expectancies */          jk= j/stepm;
     for(i=1; i<=nlstate;i++)          jl= j -jk*stepm;
       for(j=1; j<=nlstate;j++)          ju= j -(jk+1)*stepm;
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;            if(jl==0){
                         dh[mi][i]=jk;
 /* 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]);*/              bh[mi][i]=0;
             }else{ /* We want a negative bias in order to only have interpolation ie
         }                    * at the price of an extra matrix product in likelihood */
               dh[mi][i]=jk+1;
     fprintf(ficreseij,"%3.0f",age );              bh[mi][i]=ju;
     cptj=0;            }
     for(i=1; i<=nlstate;i++)          }else{
       for(j=1; j<=nlstate;j++){            if(jl <= -ju){
         cptj++;              dh[mi][i]=jk;
         fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );              bh[mi][i]=jl;       /* bias is positive if real duration
       }                                   * is higher than the multiple of stepm and negative otherwise.
     fprintf(ficreseij,"\n");                                   */
                }
     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);            else{
     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);              dh[mi][i]=jk+1;
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);              bh[mi][i]=ju;
     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);            }
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            if(dh[mi][i]==0){
   }              dh[mi][i]=1; /* At least one step */
   printf("\n");              bh[mi][i]=ju; /* At least one step */
   fprintf(ficlog,"\n");              /*  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);*/
             }
   free_vector(xp,1,npar);          } /* end if mle */
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);        }
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);      } /* end wave */
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);    }
 }    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);
 /************ Variance ******************/    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);
 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)   }
 {  
   /* Variance of health expectancies */  /*********** Tricode ****************************/
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/  void tricode(int *Tvar, int **nbcode, int imx)
   /* double **newm;*/  {
   double **dnewm,**doldm;   
   double **dnewmp,**doldmp;    int Ndum[20],ij=1, k, j, i, maxncov=19;
   int i, j, nhstepm, hstepm, h, nstepm ;    int cptcode=0;
   int k, cptcode;    cptcoveff=0;
   double *xp;   
   double **gp, **gm;  /* for var eij */    for (k=0; k<maxncov; k++) Ndum[k]=0;
   double ***gradg, ***trgradg; /*for var eij */    for (k=1; k<=7; k++) ncodemax[k]=0;
   double **gradgp, **trgradgp; /* for var p point j */  
   double *gpp, *gmp; /* for var p point j */    for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */      for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
   double ***p3mat;                                 modality*/
   double age,agelim, hf;        ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
   double ***mobaverage;        Ndum[ij]++; /*store the modality */
   int theta;        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
   char digit[4];        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
   char digitp[25];                                         Tvar[j]. If V=sex and male is 0 and
                                          female is 1, then  cptcode=1.*/
   char fileresprobmorprev[FILENAMELENGTH];      }
   
   if(popbased==1){      for (i=0; i<=cptcode; i++) {
     if(mobilav!=0)        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 */
       strcpy(digitp,"-populbased-mobilav-");      }
     else strcpy(digitp,"-populbased-nomobil-");  
   }      ij=1;
   else       for (i=1; i<=ncodemax[j]; i++) {
     strcpy(digitp,"-stablbased-");        for (k=0; k<= maxncov; k++) {
           if (Ndum[k] != 0) {
   if (mobilav!=0) {            nbcode[Tvar[j]][ij]=k;
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            /* 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; */
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){           
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);            ij++;
       printf(" Error in movingaverage mobilav=%d\n",mobilav);          }
     }          if (ij > ncodemax[j]) break;
   }        }  
       }
   strcpy(fileresprobmorprev,"prmorprev");     }  
   sprintf(digit,"%-d",ij);  
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/   for (k=0; k< maxncov; k++) Ndum[k]=0;
   strcat(fileresprobmorprev,digit); /* Tvar to be done */  
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */   for (i=1; i<=ncovmodel-2; i++) {
   strcat(fileresprobmorprev,fileres);     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {     ij=Tvar[i];
     printf("Problem with resultfile: %s\n", fileresprobmorprev);     Ndum[ij]++;
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);   }
   }  
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);   ij=1;
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);   for (i=1; i<= maxncov; i++) {
   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);     if((Ndum[i]!=0) && (i<=ncovcol)){
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);       Tvaraff[ij]=i; /*For printing */
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){       ij++;
     fprintf(ficresprobmorprev," p.%-d SE",j);     }
     for(i=1; i<=nlstate;i++)   }
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);   
   }     cptcoveff=ij-1; /*Number of simple covariates*/
   fprintf(ficresprobmorprev,"\n");  }
   fprintf(ficgp,"\n# Routine varevsij");  
   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");  /*********** Health Expectancies ****************/
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);  
 /*   } */  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[] )
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);  
   {
   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");    /* Health expectancies, no variances */
   fprintf(ficresvij,"# Age");    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
   for(i=1; i<=nlstate;i++)    double age, agelim, hf;
     for(j=1; j<=nlstate;j++)    double ***p3mat;
       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);    double eip;
   fprintf(ficresvij,"\n");  
     pstamp(ficreseij);
   xp=vector(1,npar);    fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
   dnewm=matrix(1,nlstate,1,npar);    fprintf(ficreseij,"# Age");
   doldm=matrix(1,nlstate,1,nlstate);    for(i=1; i<=nlstate;i++){
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);      for(j=1; j<=nlstate;j++){
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);        fprintf(ficreseij," e%1d%1d ",i,j);
       }
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);      fprintf(ficreseij," e%1d. ",i);
   gpp=vector(nlstate+1,nlstate+ndeath);    }
   gmp=vector(nlstate+1,nlstate+ndeath);    fprintf(ficreseij,"\n");
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/  
      
   if(estepm < stepm){    if(estepm < stepm){
     printf ("Problem %d lower than %d\n",estepm, stepm);      printf ("Problem %d lower than %d\n",estepm, stepm);
   }    }
   else  hstepm=estepm;       else  hstepm=estepm;  
   /* For example we decided to compute the life expectancy with the smallest unit */    /* We compute the life expectancy from trapezoids spaced every estepm months
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.      * This is mainly to measure the difference between two models: for example
      nhstepm is the number of hstepm from age to agelim      * if stepm=24 months pijx are given only every 2 years and by summing them
      nstepm is the number of stepm from age to agelin.      * we are calculating an estimate of the Life Expectancy assuming a linear
      Look at hpijx to understand the reason of that which relies in memory size     * progression in between and thus overestimating or underestimating according
      and note for a fixed period like k years */     * to the curvature of the survival function. If, for the same date, we
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the     * estimate the model with stepm=1 month, we can keep estepm to 24 months
      survival function given by stepm (the optimization length). Unfortunately it     * to compare the new estimate of Life expectancy with the same linear
      means that if the survival funtion is printed every two years of age and if     * hypothesis. A more precise result, taking into account a more precise
      you sum them up and add 1 year (area under the trapezoids) you won't get the same      * curvature will be obtained if estepm is as small as stepm. */
      results. So we changed our mind and took the option of the best precision.  
   */    /* For example we decided to compute the life expectancy with the smallest unit */
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   agelim = AGESUP;       nhstepm is the number of hstepm from age to agelim
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */       nstepm is the number of stepm from age to agelin.
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */        Look at hpijx to understand the reason of that which relies in memory size
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */       and note for a fixed period like estepm months */
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);       survival function given by stepm (the optimization length). Unfortunately it
     gp=matrix(0,nhstepm,1,nlstate);       means that if the survival funtion is printed only each two years of age and if
     gm=matrix(0,nhstepm,1,nlstate);       you sum them up and add 1 year (area under the trapezoids) you won't get the same
        results. So we changed our mind and took the option of the best precision.
     */
     for(theta=1; theta <=npar; theta++){    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/  
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    agelim=AGESUP;
       }    /* If stepm=6 months */
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        /* Computed by stepm unit matrices, product of hstepm matrices, stored
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
      
       if (popbased==1) {  /* nhstepm age range expressed in number of stepm */
         if(mobilav ==0){    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
           for(i=1; i<=nlstate;i++)    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
             prlim[i][i]=probs[(int)age][i][ij];    /* if (stepm >= YEARM) hstepm=1;*/
         }else{ /* mobilav */     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
           for(i=1; i<=nlstate;i++)    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             prlim[i][i]=mobaverage[(int)age][i][ij];  
         }    for (age=bage; age<=fage; age ++){
       }  
     
       for(j=1; j<= nlstate; j++){      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
         for(h=0; h<=nhstepm; h++){     
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];     
         }      printf("%d|",(int)age);fflush(stdout);
       }      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
       /* This for computing probability of death (h=1 means     
          computed over hstepm matrices product = hstepm*stepm months)   
          as a weighted average of prlim.      /* Computing expectancies */
       */      for(i=1; i<=nlstate;i++)
       for(j=nlstate+1;j<=nlstate+ndeath;j++){        for(j=1; j<=nlstate;j++)
         for(i=1,gpp[j]=0.; i<= nlstate; i++)          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
           gpp[j] += prlim[i][i]*p3mat[i][j][1];            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
       }               
       /* end probability of death */            /*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(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);        fprintf(ficreseij,"%3.0f",age );
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      for(i=1; i<=nlstate;i++){
          eip=0;
       if (popbased==1) {        for(j=1; j<=nlstate;j++){
         if(mobilav ==0){          eip +=eij[i][j][(int)age];
           for(i=1; i<=nlstate;i++)          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
             prlim[i][i]=probs[(int)age][i][ij];        }
         }else{ /* mobilav */         fprintf(ficreseij,"%9.4f", eip );
           for(i=1; i<=nlstate;i++)      }
             prlim[i][i]=mobaverage[(int)age][i][ij];      fprintf(ficreseij,"\n");
         }     
       }    }
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       for(j=1; j<= nlstate; j++){    printf("\n");
         for(h=0; h<=nhstepm; h++){    fprintf(ficlog,"\n");
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)   
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];  }
         }  
       }  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[] )
       /* This for computing probability of death (h=1 means  
          computed over hstepm matrices product = hstepm*stepm months)   {
          as a weighted average of prlim.    /* Covariances of health expectancies eij and of total life expectancies according
       */     to initial status i, ei. .
       for(j=nlstate+1;j<=nlstate+ndeath;j++){    */
         for(i=1,gmp[j]=0.; i<= nlstate; i++)    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
          gmp[j] += prlim[i][i]*p3mat[i][j][1];    double age, agelim, hf;
       }        double ***p3matp, ***p3matm, ***varhe;
       /* end probability of death */    double **dnewm,**doldm;
     double *xp, *xm;
       for(j=1; j<= nlstate; j++) /* vareij */    double **gp, **gm;
         for(h=0; h<=nhstepm; h++){    double ***gradg, ***trgradg;
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];    int theta;
         }  
     double eip, vip;
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */  
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
       }    xp=vector(1,npar);
     xm=vector(1,npar);
     } /* End theta */    dnewm=matrix(1,nlstate*nlstate,1,npar);
     doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */   
     pstamp(ficresstdeij);
     for(h=0; h<=nhstepm; h++) /* veij */    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
       for(j=1; j<=nlstate;j++)    fprintf(ficresstdeij,"# Age");
         for(theta=1; theta <=npar; theta++)    for(i=1; i<=nlstate;i++){
           trgradg[h][j][theta]=gradg[h][theta][j];      for(j=1; j<=nlstate;j++)
         fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */      fprintf(ficresstdeij," e%1d. ",i);
       for(theta=1; theta <=npar; theta++)    }
         trgradgp[j][theta]=gradgp[theta][j];    fprintf(ficresstdeij,"\n");
     
     pstamp(ficrescveij);
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
     for(i=1;i<=nlstate;i++)    fprintf(ficrescveij,"# Age");
       for(j=1;j<=nlstate;j++)    for(i=1; i<=nlstate;i++)
         vareij[i][j][(int)age] =0.;      for(j=1; j<=nlstate;j++){
         cptj= (j-1)*nlstate+i;
     for(h=0;h<=nhstepm;h++){        for(i2=1; i2<=nlstate;i2++)
       for(k=0;k<=nhstepm;k++){          for(j2=1; j2<=nlstate;j2++){
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);            cptj2= (j2-1)*nlstate+i2;
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);            if(cptj2 <= cptj)
         for(i=1;i<=nlstate;i++)              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
           for(j=1;j<=nlstate;j++)          }
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;      }
       }    fprintf(ficrescveij,"\n");
     }   
       if(estepm < stepm){
     /* pptj */      printf ("Problem %d lower than %d\n",estepm, stepm);
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);    }
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);    else  hstepm=estepm;  
     for(j=nlstate+1;j<=nlstate+ndeath;j++)    /* We compute the life expectancy from trapezoids spaced every estepm months
       for(i=nlstate+1;i<=nlstate+ndeath;i++)     * This is mainly to measure the difference between two models: for example
         varppt[j][i]=doldmp[j][i];     * if stepm=24 months pijx are given only every 2 years and by summing them
     /* end ppptj */     * we are calculating an estimate of the Life Expectancy assuming a linear
     /*  x centered again */     * progression in between and thus overestimating or underestimating according
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);       * to the curvature of the survival function. If, for the same date, we
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);     * 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
     if (popbased==1) {     * hypothesis. A more precise result, taking into account a more precise
       if(mobilav ==0){     * curvature will be obtained if estepm is as small as stepm. */
         for(i=1; i<=nlstate;i++)  
           prlim[i][i]=probs[(int)age][i][ij];    /* For example we decided to compute the life expectancy with the smallest unit */
       }else{ /* mobilav */     /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
         for(i=1; i<=nlstate;i++)       nhstepm is the number of hstepm from age to agelim
           prlim[i][i]=mobaverage[(int)age][i][ij];       nstepm is the number of stepm from age to agelin.
       }       Look at hpijx to understand the reason of that which relies in memory size
     }       and note for a fixed period like estepm months */
                  /* We decided (b) to get a life expectancy respecting the most precise curvature of the
     /* This for computing probability of death (h=1 means       survival function given by stepm (the optimization length). Unfortunately it
        computed over hstepm (estepm) matrices product = hstepm*stepm months)        means that if the survival funtion is printed only each two years of age and if
        as a weighted average of prlim.       you sum them up and add 1 year (area under the trapezoids) you won't get the same
     */       results. So we changed our mind and took the option of the best precision.
     for(j=nlstate+1;j<=nlstate+ndeath;j++){    */
       for(i=1,gmp[j]=0.;i<= nlstate; i++)     hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
         gmp[j] += prlim[i][i]*p3mat[i][j][1];   
     }        /* If stepm=6 months */
     /* end probability of death */    /* nhstepm age range expressed in number of stepm */
     agelim=AGESUP;
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));    /* if (stepm >= YEARM) hstepm=1;*/
       for(i=1; i<=nlstate;i++){    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);   
       }    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     }     p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     fprintf(ficresprobmorprev,"\n");    gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
     trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
     fprintf(ficresvij,"%.0f ",age );    gp=matrix(0,nhstepm,1,nlstate*nlstate);
     for(i=1; i<=nlstate;i++)    gm=matrix(0,nhstepm,1,nlstate*nlstate);
       for(j=1; j<=nlstate;j++){  
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);    for (age=bage; age<=fage; age ++){
       }  
     fprintf(ficresvij,"\n");      /* Computed by stepm unit matrices, product of hstepm matrices, stored
     free_matrix(gp,0,nhstepm,1,nlstate);         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
     free_matrix(gm,0,nhstepm,1,nlstate);   
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);  
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      /* Computing  Variances of health expectancies */
   } /* End age */      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
   free_vector(gpp,nlstate+1,nlstate+ndeath);         decrease memory allocation */
   free_vector(gmp,nlstate+1,nlstate+ndeath);      for(theta=1; theta <=npar; theta++){
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);        for(i=1; i<=npar; i++){
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/          xp[i] = x[i] + (i==theta ?delti[theta]:0);
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");          xm[i] = x[i] - (i==theta ?delti[theta]:0);
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */        }
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */   
 /*   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; j++){
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));          for(i=1; i<=nlstate; i++){
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));            for(h=0; h<=nhstepm-1; h++){
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));              gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));              gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
   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);            }
   /*  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(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);        for(ij=1; ij<= nlstate*nlstate; ij++)
           for(h=0; h<=nhstepm-1; h++){
   free_vector(xp,1,npar);            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
   free_matrix(doldm,1,nlstate,1,nlstate);          }
   free_matrix(dnewm,1,nlstate,1,npar);      }/* End theta */
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);     
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);     
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);      for(h=0; h<=nhstepm-1; h++)
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        for(j=1; j<=nlstate*nlstate;j++)
   fclose(ficresprobmorprev);          for(theta=1; theta <=npar; theta++)
   fflush(ficgp);            trgradg[h][j][theta]=gradg[h][theta][j];
   fflush(fichtm);      
 }  /* end varevsij */  
        for(ij=1;ij<=nlstate*nlstate;ij++)
 /************ Variance of prevlim ******************/        for(ji=1;ji<=nlstate*nlstate;ji++)
 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)          varhe[ij][ji][(int)age] =0.;
 {  
   /* Variance of prevalence limit */       printf("%d|",(int)age);fflush(stdout);
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
   double **newm;       for(h=0;h<=nhstepm-1;h++){
   double **dnewm,**doldm;        for(k=0;k<=nhstepm-1;k++){
   int i, j, nhstepm, hstepm;          matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
   int k, cptcode;          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
   double *xp;          for(ij=1;ij<=nlstate*nlstate;ij++)
   double *gp, *gm;            for(ji=1;ji<=nlstate*nlstate;ji++)
   double **gradg, **trgradg;              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
   double age,agelim;        }
   int theta;      }
      
   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");      /* Computing expectancies */
   fprintf(ficresvpl,"# Age");      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
   for(i=1; i<=nlstate;i++)      for(i=1; i<=nlstate;i++)
       fprintf(ficresvpl," %1d-%1d",i,i);        for(j=1; j<=nlstate;j++)
   fprintf(ficresvpl,"\n");          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
             eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
   xp=vector(1,npar);           
   dnewm=matrix(1,nlstate,1,npar);            /* 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]);*/
   doldm=matrix(1,nlstate,1,nlstate);  
             }
   hstepm=1*YEARM; /* Every year of age */  
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */       fprintf(ficresstdeij,"%3.0f",age );
   agelim = AGESUP;      for(i=1; i<=nlstate;i++){
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */        eip=0.;
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */         vip=0.;
     if (stepm >= YEARM) hstepm=1;        for(j=1; j<=nlstate;j++){
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */          eip += eij[i][j][(int)age];
     gradg=matrix(1,npar,1,nlstate);          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
     gp=vector(1,nlstate);            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
     gm=vector(1,nlstate);          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
         }
     for(theta=1; theta <=npar; theta++){        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
       for(i=1; i<=npar; i++){ /* Computes gradient */      }
         xp[i] = x[i] + (i==theta ?delti[theta]:0);      fprintf(ficresstdeij,"\n");
       }  
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      fprintf(ficrescveij,"%3.0f",age );
       for(i=1;i<=nlstate;i++)      for(i=1; i<=nlstate;i++)
         gp[i] = prlim[i][i];        for(j=1; j<=nlstate;j++){
               cptj= (j-1)*nlstate+i;
       for(i=1; i<=npar; i++) /* Computes gradient */          for(i2=1; i2<=nlstate;i2++)
         xp[i] = x[i] - (i==theta ?delti[theta]:0);            for(j2=1; j2<=nlstate;j2++){
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);              cptj2= (j2-1)*nlstate+i2;
       for(i=1;i<=nlstate;i++)              if(cptj2 <= cptj)
         gm[i] = prlim[i][i];                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
             }
       for(i=1;i<=nlstate;i++)        }
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];      fprintf(ficrescveij,"\n");
     } /* End theta */     
     }
     trgradg =matrix(1,nlstate,1,npar);    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
     for(j=1; j<=nlstate;j++)    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
       for(theta=1; theta <=npar; theta++)    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
         trgradg[j][theta]=gradg[theta][j];    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     for(i=1;i<=nlstate;i++)    printf("\n");
       varpl[i][(int)age] =0.;    fprintf(ficlog,"\n");
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);  
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);    free_vector(xm,1,npar);
     for(i=1;i<=nlstate;i++)    free_vector(xp,1,npar);
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
     free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
     fprintf(ficresvpl,"%.0f ",age );    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
     for(i=1; i<=nlstate;i++)  }
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));  
     fprintf(ficresvpl,"\n");  /************ Variance ******************/
     free_vector(gp,1,nlstate);  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[])
     free_vector(gm,1,nlstate);  {
     free_matrix(gradg,1,npar,1,nlstate);    /* Variance of health expectancies */
     free_matrix(trgradg,1,nlstate,1,npar);    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
   } /* End age */    /* double **newm;*/
     double **dnewm,**doldm;
   free_vector(xp,1,npar);    double **dnewmp,**doldmp;
   free_matrix(doldm,1,nlstate,1,npar);    int i, j, nhstepm, hstepm, h, nstepm ;
   free_matrix(dnewm,1,nlstate,1,nlstate);    int k, cptcode;
     double *xp;
 }    double **gp, **gm;  /* for var eij */
     double ***gradg, ***trgradg; /*for var eij */
 /************ Variance of one-step probabilities  ******************/    double **gradgp, **trgradgp; /* for var p point j */
 void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax)    double *gpp, *gmp; /* for var p point j */
 {    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
   int i, j=0,  i1, k1, l1, t, tj;    double ***p3mat;
   int k2, l2, j1,  z1;    double age,agelim, hf;
   int k=0,l, cptcode;    double ***mobaverage;
   int first=1, first1;    int theta;
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;    char digit[4];
   double **dnewm,**doldm;    char digitp[25];
   double *xp;  
   double *gp, *gm;    char fileresprobmorprev[FILENAMELENGTH];
   double **gradg, **trgradg;  
   double **mu;    if(popbased==1){
   double age,agelim, cov[NCOVMAX];      if(mobilav!=0)
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */        strcpy(digitp,"-populbased-mobilav-");
   int theta;      else strcpy(digitp,"-populbased-nomobil-");
   char fileresprob[FILENAMELENGTH];    }
   char fileresprobcov[FILENAMELENGTH];    else
   char fileresprobcor[FILENAMELENGTH];      strcpy(digitp,"-stablbased-");
   
   double ***varpij;    if (mobilav!=0) {
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   strcpy(fileresprob,"prob");       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
   strcat(fileresprob,fileres);        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {        printf(" Error in movingaverage mobilav=%d\n",mobilav);
     printf("Problem with resultfile: %s\n", fileresprob);      }
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);    }
   }  
   strcpy(fileresprobcov,"probcov");     strcpy(fileresprobmorprev,"prmorprev");
   strcat(fileresprobcov,fileres);    sprintf(digit,"%-d",ij);
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
     printf("Problem with resultfile: %s\n", fileresprobcov);    strcat(fileresprobmorprev,digit); /* Tvar to be done */
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
   }    strcat(fileresprobmorprev,fileres);
   strcpy(fileresprobcor,"probcor");     if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
   strcat(fileresprobcor,fileres);      printf("Problem with resultfile: %s\n", fileresprobmorprev);
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
     printf("Problem with resultfile: %s\n", fileresprobcor);    }
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   }   
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    pstamp(ficresprobmorprev);
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    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,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);      fprintf(ficresprobmorprev," p.%-d SE",j);
         for(i=1; i<=nlstate;i++)
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
   fprintf(ficresprob,"# Age");    }  
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");    fprintf(ficresprobmorprev,"\n");
   fprintf(ficresprobcov,"# Age");    fprintf(ficgp,"\n# Routine varevsij");
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   fprintf(ficresprobcov,"# Age");    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);
   /*   } */
   for(i=1; i<=nlstate;i++)    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
     for(j=1; j<=(nlstate+ndeath);j++){    pstamp(ficresvij);
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
       fprintf(ficresprobcov," p%1d-%1d ",i,j);    if(popbased==1)
       fprintf(ficresprobcor," p%1d-%1d ",i,j);      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
     }      else
  /* fprintf(ficresprob,"\n");      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
   fprintf(ficresprobcov,"\n");    fprintf(ficresvij,"# Age");
   fprintf(ficresprobcor,"\n");    for(i=1; i<=nlstate;i++)
  */      for(j=1; j<=nlstate;j++)
  xp=vector(1,npar);        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    fprintf(ficresvij,"\n");
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));  
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);    xp=vector(1,npar);
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);    dnewm=matrix(1,nlstate,1,npar);
   first=1;    doldm=matrix(1,nlstate,1,nlstate);
   fprintf(ficgp,"\n# Routine varprob");    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   fprintf(fichtm,"\n");  
     gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);    gpp=vector(nlstate+1,nlstate+ndeath);
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\    gmp=vector(nlstate+1,nlstate+ndeath);
   file %s<br>\n",optionfilehtmcov);    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\   
 and drawn. It helps understanding how is the covariance between two incidences.\    if(estepm < stepm){
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");      printf ("Problem %d lower than %d\n",estepm, stepm);
   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. \    }
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \    else  hstepm=estepm;  
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \    /* For example we decided to compute the life expectancy with the smallest unit */
 standard deviations wide on each axis. <br>\    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\       nhstepm is the number of hstepm from age to agelim
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\       nstepm is the number of stepm from age to agelin.
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");       Look at hpijx to understand the reason of that which relies in memory size
        and note for a fixed period like k years */
   cov[1]=1;    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   tj=cptcoveff;       survival function given by stepm (the optimization length). Unfortunately it
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}       means that if the survival funtion is printed every two years of age and if
   j1=0;       you sum them up and add 1 year (area under the trapezoids) you won't get the same
   for(t=1; t<=tj;t++){       results. So we changed our mind and took the option of the best precision.
     for(i1=1; i1<=ncodemax[t];i1++){     */
       j1++;    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
       if  (cptcovn>0) {    agelim = AGESUP;
         fprintf(ficresprob, "\n#********** Variable ");     for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
         fprintf(ficresprob, "**********\n#\n");      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
         fprintf(ficresprobcov, "\n#********** Variable ");       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
         fprintf(ficresprobcov, "**********\n#\n");      gp=matrix(0,nhstepm,1,nlstate);
               gm=matrix(0,nhstepm,1,nlstate);
         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(theta=1; theta <=npar; theta++){
                 for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   xp[i] = x[i] + (i==theta ?delti[theta]:0);
         fprintf(fichtm, "\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]]);        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
         fprintf(fichtm, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
           
         fprintf(ficresprobcor, "\n#********** Variable ");            if (popbased==1) {
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          if(mobilav ==0){
         fprintf(ficresprobcor, "**********\n#");                for(i=1; i<=nlstate;i++)
       }              prlim[i][i]=probs[(int)age][i][ij];
                 }else{ /* mobilav */
       for (age=bage; age<=fage; age ++){             for(i=1; i<=nlstate;i++)
         cov[2]=age;              prlim[i][i]=mobaverage[(int)age][i][ij];
         for (k=1; k<=cptcovn;k++) {          }
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];        }
         }   
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];        for(j=1; j<= nlstate; j++){
         for (k=1; k<=cptcovprod;k++)          for(h=0; h<=nhstepm; h++){
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                       gp[h][j] += prlim[i][i]*p3mat[i][j][h];
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));          }
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);        }
         gp=vector(1,(nlstate)*(nlstate+ndeath));        /* This for computing probability of death (h=1 means
         gm=vector(1,(nlstate)*(nlstate+ndeath));           computed over hstepm matrices product = hstepm*stepm months)
                as a weighted average of prlim.
         for(theta=1; theta <=npar; theta++){        */
           for(i=1; i<=npar; i++)        for(j=nlstate+1;j<=nlstate+ndeath;j++){
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);          for(i=1,gpp[j]=0.; i<= nlstate; i++)
                       gpp[j] += prlim[i][i]*p3mat[i][j][1];
           pmij(pmmij,cov,ncovmodel,xp,nlstate);        }    
                   /* end probability of death */
           k=0;  
           for(i=1; i<= (nlstate); i++){        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
             for(j=1; j<=(nlstate+ndeath);j++){          xp[i] = x[i] - (i==theta ?delti[theta]:0);
               k=k+1;        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
               gp[k]=pmmij[i][j];        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
             }   
           }        if (popbased==1) {
                     if(mobilav ==0){
           for(i=1; i<=npar; i++)            for(i=1; i<=nlstate;i++)
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);              prlim[i][i]=probs[(int)age][i][ij];
               }else{ /* mobilav */
           pmij(pmmij,cov,ncovmodel,xp,nlstate);            for(i=1; i<=nlstate;i++)
           k=0;              prlim[i][i]=mobaverage[(int)age][i][ij];
           for(i=1; i<=(nlstate); i++){          }
             for(j=1; j<=(nlstate+ndeath);j++){        }
               k=k+1;  
               gm[k]=pmmij[i][j];        for(j=1; j<= nlstate; j++){
             }          for(h=0; h<=nhstepm; h++){
           }            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)           }
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];          }
         }        /* This for computing probability of death (h=1 means
            computed over hstepm matrices product = hstepm*stepm months)
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)           as a weighted average of prlim.
           for(theta=1; theta <=npar; theta++)        */
             trgradg[j][theta]=gradg[theta][j];        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   for(i=1,gmp[j]=0.; i<= nlstate; i++)
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);            gmp[j] += prlim[i][i]*p3mat[i][j][1];
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);        }    
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));        /* end probability of death */
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));  
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);        for(j=1; j<= nlstate; j++) /* vareij */
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);          for(h=0; h<=nhstepm; h++){
             gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
         pmij(pmmij,cov,ncovmodel,x,nlstate);          }
           
         k=0;        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
         for(i=1; i<=(nlstate); i++){          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
           for(j=1; j<=(nlstate+ndeath);j++){        }
             k=k+1;  
             mu[k][(int) age]=pmmij[i][j];      } /* End theta */
           }  
         }      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)  
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)      for(h=0; h<=nhstepm; h++) /* veij */
             varpij[i][j][(int)age] = doldm[i][j];        for(j=1; j<=nlstate;j++)
           for(theta=1; theta <=npar; theta++)
         /*printf("\n%d ",(int)age);            trgradg[h][j][theta]=gradg[h][theta][j];
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){  
           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));        for(theta=1; theta <=npar; theta++)
           }*/          trgradgp[j][theta]=gradgp[theta][j];
    
         fprintf(ficresprob,"\n%d ",(int)age);  
         fprintf(ficresprobcov,"\n%d ",(int)age);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
         fprintf(ficresprobcor,"\n%d ",(int)age);      for(i=1;i<=nlstate;i++)
         for(j=1;j<=nlstate;j++)
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)          vareij[i][j][(int)age] =0.;
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));  
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){      for(h=0;h<=nhstepm;h++){
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);        for(k=0;k<=nhstepm;k++){
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
         }          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
         i=0;          for(i=1;i<=nlstate;i++)
         for (k=1; k<=(nlstate);k++){            for(j=1;j<=nlstate;j++)
           for (l=1; l<=(nlstate+ndeath);l++){               vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
             i=i++;        }
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);      }
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);   
             for (j=1; j<=i;j++){      /* pptj */
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
             }      for(j=nlstate+1;j<=nlstate+ndeath;j++)
           }        for(i=nlstate+1;i<=nlstate+ndeath;i++)
         }/* end of loop for state */          varppt[j][i]=doldmp[j][i];
       } /* end of loop for age */      /* end ppptj */
       /*  x centered again */
       /* Confidence intervalle of pij  */      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
       /*      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
         fprintf(ficgp,"\nset noparametric;unset label");   
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");      if (popbased==1) {
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");        if(mobilav ==0){
         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);          for(i=1; i<=nlstate;i++)
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);            prlim[i][i]=probs[(int)age][i][ij];
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);        }else{ /* mobilav */
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);          for(i=1; i<=nlstate;i++)
       */            prlim[i][i]=mobaverage[(int)age][i][ij];
         }
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/      }
       first1=1;               
       for (k2=1; k2<=(nlstate);k2++){      /* This for computing probability of death (h=1 means
         for (l2=1; l2<=(nlstate+ndeath);l2++){          computed over hstepm (estepm) matrices product = hstepm*stepm months)
           if(l2==k2) continue;         as a weighted average of prlim.
           j=(k2-1)*(nlstate+ndeath)+l2;      */
           for (k1=1; k1<=(nlstate);k1++){      for(j=nlstate+1;j<=nlstate+ndeath;j++){
             for (l1=1; l1<=(nlstate+ndeath);l1++){         for(i=1,gmp[j]=0.;i<= nlstate; i++)
               if(l1==k1) continue;          gmp[j] += prlim[i][i]*p3mat[i][j][1];
               i=(k1-1)*(nlstate+ndeath)+l1;      }    
               if(i<=j) continue;      /* end probability of death */
               for (age=bage; age<=fage; age ++){   
                 if ((int)age %5==0){      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;        for(i=1; i<=nlstate;i++){
                   mu1=mu[i][(int) age]/stepm*YEARM ;          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   mu2=mu[j][(int) age]/stepm*YEARM;        }
                   c12=cv12/sqrt(v1*v2);      }
                   /* Computing eigen value of matrix of covariance */      fprintf(ficresprobmorprev,"\n");
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;      fprintf(ficresvij,"%.0f ",age );
                   /* Eigen vectors */      for(i=1; i<=nlstate;i++)
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));        for(j=1; j<=nlstate;j++){
                   /*v21=sqrt(1.-v11*v11); *//* error */          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   v21=(lc1-v1)/cv12*v11;        }
                   v12=-v21;      fprintf(ficresvij,"\n");
                   v22=v11;      free_matrix(gp,0,nhstepm,1,nlstate);
                   tnalp=v21/v11;      free_matrix(gm,0,nhstepm,1,nlstate);
                   if(first1==1){      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                     first1=0;      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                     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);      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   }    } /* End 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);    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   /*printf(fignu*/    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   if(first==1){    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
                     first=0;    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                     fprintf(ficgp,"\nset parametric;unset label");    fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                     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);  /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    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);
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);    /*  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(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);  */
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                     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",\  
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\    free_vector(xp,1,npar);
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    free_matrix(doldm,1,nlstate,1,nlstate);
                   }else{    free_matrix(dnewm,1,nlstate,1,npar);
                     first=0;    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                     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",\    fclose(ficresprobmorprev);
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\    fflush(ficgp);
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    fflush(fichtm);
                   }/* if first */  }  /* end varevsij */
                 } /* age mod 5 */  
               } /* end loop age */  /************ Variance of prevlim ******************/
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",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[])
               first=1;  {
             } /*l12 */    /* Variance of prevalence limit */
           } /* k12 */    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
         } /*l1 */    double **newm;
       }/* k1 */    double **dnewm,**doldm;
     } /* loop covariates */    int i, j, nhstepm, hstepm;
   }    int k, cptcode;
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);    double *xp;
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);    double *gp, *gm;
   free_vector(xp,1,npar);    double **gradg, **trgradg;
   fclose(ficresprob);    double age,agelim;
   fclose(ficresprobcov);    int theta;
   fclose(ficresprobcor);   
   fflush(ficgp);    pstamp(ficresvpl);
   fflush(fichtmcov);    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 }    fprintf(ficresvpl,"# Age");
     for(i=1; i<=nlstate;i++)
         fprintf(ficresvpl," %1d-%1d",i,i);
 /******************* Printing html file ***********/    fprintf(ficresvpl,"\n");
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \  
                   int lastpass, int stepm, int weightopt, char model[],\    xp=vector(1,npar);
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\    dnewm=matrix(1,nlstate,1,npar);
                   int popforecast, int estepm ,\    doldm=matrix(1,nlstate,1,nlstate);
                   double jprev1, double mprev1,double anprev1, \   
                   double jprev2, double mprev2,double anprev2){    hstepm=1*YEARM; /* Every year of age */
   int jj1, k1, i1, cpt;    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
   /*char optionfilehtm[FILENAMELENGTH];*/    agelim = AGESUP;
 /*   if((fichtm=fopen(optionfilehtm,"a"))==NULL)    { */    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 /*     printf("Problem with %s \n",optionfilehtm), exit(0); */      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 /*     fprintf(ficlog,"Problem with %s \n",optionfilehtm), exit(0); */      if (stepm >= YEARM) hstepm=1;
 /*   } */      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
       gradg=matrix(1,npar,1,nlstate);
    fprintf(fichtm,"<ul><li><h4>Result files (first order: no variance)</h4>\n \      gp=vector(1,nlstate);
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n \      gm=vector(1,nlstate);
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n \  
  - Stable prevalence in each health state: <a href=\"%s\">%s</a> <br>\n \      for(theta=1; theta <=npar; theta++){
  - Life expectancies by age and initial health status (estepm=%2d months): \        for(i=1; i<=npar; i++){ /* Computes gradient */
    <a href=\"%s\">%s</a> <br>\n</li>", \          xp[i] = x[i] + (i==theta ?delti[theta]:0);
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"),\        }
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"),\        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"),\        for(i=1;i<=nlstate;i++)
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));          gp[i] = prlim[i][i];
      
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");        for(i=1; i<=npar; i++) /* Computes gradient */
           xp[i] = x[i] - (i==theta ?delti[theta]:0);
  m=cptcoveff;        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}        for(i=1;i<=nlstate;i++)
           gm[i] = prlim[i][i];
  jj1=0;  
  for(k1=1; k1<=m;k1++){        for(i=1;i<=nlstate;i++)
    for(i1=1; i1<=ncodemax[k1];i1++){          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
      jj1++;      } /* End theta */
      if (cptcovn > 0) {  
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");      trgradg =matrix(1,nlstate,1,npar);
        for (cpt=1; cpt<=cptcoveff;cpt++)   
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);      for(j=1; j<=nlstate;j++)
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");        for(theta=1; theta <=npar; theta++)
      }          trgradg[j][theta]=gradg[theta][j];
      /* 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> \      for(i=1;i<=nlstate;i++)
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);             varpl[i][(int)age] =0.;
      /* Quasi-incidences */      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: %s%d2.png<br> \      for(i=1;i<=nlstate;i++)
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);         varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
        /* Stable prevalence in each health state */  
        for(cpt=1; cpt<nlstate;cpt++){      fprintf(ficresvpl,"%.0f ",age );
          fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br> \      for(i=1; i<=nlstate;i++)
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
        }      fprintf(ficresvpl,"\n");
      for(cpt=1; cpt<=nlstate;cpt++) {      free_vector(gp,1,nlstate);
         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): %s%d%d.png <br> \      free_vector(gm,1,nlstate);
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);      free_matrix(gradg,1,npar,1,nlstate);
      }      free_matrix(trgradg,1,nlstate,1,npar);
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \    } /* End age */
 health expectancies in states (1) and (2): %s%d.png<br>\  
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);    free_vector(xp,1,npar);
    } /* end i1 */    free_matrix(doldm,1,nlstate,1,npar);
  }/* End k1 */    free_matrix(dnewm,1,nlstate,1,nlstate);
  fprintf(fichtm,"</ul>");  
   }
   
  fprintf(fichtm,"\n<br><li><h4> Result files (second order: variances)</h4>\n\  /************ Variance of one-step probabilities  ******************/
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n\  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[])
  - 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\    int i, j=0,  i1, k1, l1, t, tj;
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n\    int k2, l2, j1,  z1;
  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"%s\">%s</a><br>\n\    int k=0,l, cptcode;
  - Health expectancies with their variances (no covariance): <a href=\"%s\">%s</a> <br>\n\    int first=1, first1;
  - Standard deviation of stable prevalences: <a href=\"%s\">%s</a> <br>\n",\    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
          rfileres,rfileres,\    double **dnewm,**doldm;
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"),\    double *xp;
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"),\    double *gp, *gm;
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"),\    double **gradg, **trgradg;
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"),\    double **mu;
          subdirf2(fileres,"t"),subdirf2(fileres,"t"),\    double age,agelim, cov[NCOVMAX];
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
     int theta;
 /*  if(popforecast==1) fprintf(fichtm,"\n */    char fileresprob[FILENAMELENGTH];
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */    char fileresprobcov[FILENAMELENGTH];
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */    char fileresprobcor[FILENAMELENGTH];
 /*      <br>",fileres,fileres,fileres,fileres); */  
 /*  else  */    double ***varpij;
 /*    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(fichtm," <ul><li><b>Graphs</b></li><p>");    strcpy(fileresprob,"prob");
     strcat(fileresprob,fileres);
  m=cptcoveff;    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}      printf("Problem with resultfile: %s\n", fileresprob);
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
  jj1=0;    }
  for(k1=1; k1<=m;k1++){    strcpy(fileresprobcov,"probcov");
    for(i1=1; i1<=ncodemax[k1];i1++){    strcat(fileresprobcov,fileres);
      jj1++;    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
      if (cptcovn > 0) {      printf("Problem with resultfile: %s\n", fileresprobcov);
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
        for (cpt=1; cpt<=cptcoveff;cpt++)     }
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    strcpy(fileresprobcor,"probcor");
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");    strcat(fileresprobcor,fileres);
      }    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
      for(cpt=1; cpt<=nlstate;cpt++) {      printf("Problem with resultfile: %s\n", fileresprobcor);
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 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);      printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
      }    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
    } /* end i1 */    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
  }/* End k1 */    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
  fprintf(fichtm,"</ul>");    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
  fflush(fichtm);    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 }    pstamp(ficresprob);
     fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 /******************* Gnuplot file **************/    fprintf(ficresprob,"# Age");
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){    pstamp(ficresprobcov);
     fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
   char dirfileres[132],optfileres[132];    fprintf(ficresprobcov,"# Age");
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;    pstamp(ficresprobcor);
   int ng;    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */    fprintf(ficresprobcor,"# Age");
 /*     printf("Problem with file %s",optionfilegnuplot); */  
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */  
 /*   } */    for(i=1; i<=nlstate;i++)
       for(j=1; j<=(nlstate+ndeath);j++){
   /*#ifdef windows */        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
   fprintf(ficgp,"cd \"%s\" \n",pathc);        fprintf(ficresprobcov," p%1d-%1d ",i,j);
     /*#endif */        fprintf(ficresprobcor," p%1d-%1d ",i,j);
   m=pow(2,cptcoveff);      }  
    /* fprintf(ficresprob,"\n");
   strcpy(dirfileres,optionfilefiname);    fprintf(ficresprobcov,"\n");
   strcpy(optfileres,"vpl");    fprintf(ficresprobcor,"\n");
  /* 1eme*/   */
   for (cpt=1; cpt<= nlstate ; cpt ++) {   xp=vector(1,npar);
    for (k1=1; k1<= m ; k1 ++) {    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
      fprintf(ficgp,"set xlabel \"Age\" \n\    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 set ylabel \"Probability\" \n\    first=1;
 set ter png small\n\    fprintf(ficgp,"\n# Routine varprob");
 set size 0.65,0.65\n\    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);    fprintf(fichtm,"\n");
   
      for (i=1; i<= nlstate ; i ++) {    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
        else fprintf(ficgp," \%%*lf (\%%*lf)");    file %s<br>\n",optionfilehtmcov);
      }    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
      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);  and drawn. It helps understanding how is the covariance between two incidences.\
      for (i=1; i<= nlstate ; i ++) {   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");    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. \
        else fprintf(ficgp," \%%*lf (\%%*lf)");  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
      }   would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
      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);   standard deviations wide on each axis. <br>\
      for (i=1; i<= nlstate ; i ++) {   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
        else fprintf(ficgp," \%%*lf (\%%*lf)");  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \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));    cov[1]=1;
    }    tj=cptcoveff;
   }    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
   /*2 eme*/    j1=0;
       for(t=1; t<=tj;t++){
   for (k1=1; k1<= m ; k1 ++) {       for(i1=1; i1<=ncodemax[t];i1++){
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);        j1++;
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);        if  (cptcovn>0) {
               fprintf(ficresprob, "\n#********** Variable ");
     for (i=1; i<= nlstate+1 ; i ++) {          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
       k=2*i;          fprintf(ficresprob, "**********\n#\n");
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);          fprintf(ficresprobcov, "\n#********** Variable ");
       for (j=1; j<= nlstate+1 ; j ++) {          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");          fprintf(ficresprobcov, "**********\n#\n");
         else fprintf(ficgp," \%%*lf (\%%*lf)");         
       }             fprintf(ficgp, "\n#********** Variable ");
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);          fprintf(ficgp, "**********\n#\n");
       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 ++) {         
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
         else fprintf(ficgp," \%%*lf (\%%*lf)");          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
       }             fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
       fprintf(ficgp,"\" t\"\" w l 0,");         
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);          fprintf(ficresprobcor, "\n#********** Variable ");    
       for (j=1; j<= nlstate+1 ; j ++) {          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");          fprintf(ficresprobcor, "**********\n#");    
         else fprintf(ficgp," \%%*lf (\%%*lf)");        }
       }          
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");        for (age=bage; age<=fage; age ++){
       else fprintf(ficgp,"\" t\"\" w l 0,");          cov[2]=age;
     }          for (k=1; k<=cptcovn;k++) {
   }            cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
             }
   /*3eme*/          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
             for (k=1; k<=cptcovprod;k++)
   for (k1=1; k1<= m ; k1 ++) {             cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
     for (cpt=1; cpt<= nlstate ; cpt ++) {         
       k=2+nlstate*(2*cpt-2);          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
       fprintf(ficgp,"set ter png small\n\          gp=vector(1,(nlstate)*(nlstate+ndeath));
 set size 0.65,0.65\n\          gm=vector(1,(nlstate)*(nlstate+ndeath));
 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);          for(theta=1; theta <=npar; theta++){
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");            for(i=1; i<=npar; i++)
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);              xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
         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) ");            pmij(pmmij,cov,ncovmodel,xp,nlstate);
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);           
                     k=0;
       */            for(i=1; i<= (nlstate); i++){
       for (i=1; i< nlstate ; i ++) {              for(j=1; j<=(nlstate+ndeath);j++){
         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);                k=k+1;
                         gp[k]=pmmij[i][j];
       }               }
     }            }
   }           
               for(i=1; i<=npar; i++)
   /* CV preval stable (period) */              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
   for (k1=1; k1<= m ; k1 ++) {      
     for (cpt=1; cpt<=nlstate ; cpt ++) {            pmij(pmmij,cov,ncovmodel,xp,nlstate);
       k=3;            k=0;
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);            for(i=1; i<=(nlstate); i++){
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\              for(j=1; j<=(nlstate+ndeath);j++){
 set ter png small\nset size 0.65,0.65\n\                k=k+1;
 unset log y\n\                gm[k]=pmmij[i][j];
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);              }
                   }
       for (i=1; i< nlstate ; i ++)       
         fprintf(ficgp,"+$%d",k+i+1);            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);              gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                 }
       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(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
       for (i=1; i< nlstate ; i ++) {            for(theta=1; theta <=npar; theta++)
         l=3+(nlstate+ndeath)*cpt;              trgradg[j][theta]=gradg[theta][j];
         fprintf(ficgp,"+$%d",l+i+1);         
       }          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);             matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
     }           free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
   }            free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
             free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
   /* proba elementaires */          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
   for(i=1,jk=1; i <=nlstate; i++){  
     for(k=1; k <=(nlstate+ndeath); k++){          pmij(pmmij,cov,ncovmodel,x,nlstate);
       if (k != i) {         
         for(j=1; j <=ncovmodel; j++){          k=0;
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);          for(i=1; i<=(nlstate); i++){
           jk++;             for(j=1; j<=(nlstate+ndeath);j++){
           fprintf(ficgp,"\n");              k=k+1;
         }              mu[k][(int) age]=pmmij[i][j];
       }            }
     }          }
    }          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
             for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/              varpij[i][j][(int)age] = doldm[i][j];
      for(jk=1; jk <=m; jk++) {  
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);           /*printf("\n%d ",(int)age);
        if (ng==2)            for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
        else            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
          fprintf(ficgp,"\nset title \"Probability\"\n");            }*/
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);  
        i=1;          fprintf(ficresprob,"\n%d ",(int)age);
        for(k2=1; k2<=nlstate; k2++) {          fprintf(ficresprobcov,"\n%d ",(int)age);
          k3=i;          fprintf(ficresprobcor,"\n%d ",(int)age);
          for(k=1; k<=(nlstate+ndeath); k++) {  
            if (k != k2){          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
              if(ng==2)            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
              else            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
              ij=1;          }
              for(j=3; j <=ncovmodel; j++) {          i=0;
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {          for (k=1; k<=(nlstate);k++){
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);            for (l=1; l<=(nlstate+ndeath);l++){
                  ij++;              i=i++;
                }              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                else              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);              for (j=1; j<=i;j++){
              }                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
              fprintf(ficgp,")/(1");                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                            }
              for(k1=1; k1 <=nlstate; k1++){               }
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);          }/* end of loop for state */
                ij=1;        } /* end of loop for age */
                for(j=3; j <=ncovmodel; j++){  
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {        /* Confidence intervalle of pij  */
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);        /*
                    ij++;          fprintf(ficgp,"\nset noparametric;unset label");
                  }          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                  else          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][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);
                }          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                fprintf(ficgp,")");          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
              }          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);        */
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");  
              i=i+ncovmodel;        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
            }        first1=1;
          } /* end k */        for (k2=1; k2<=(nlstate);k2++){
        } /* end k2 */          for (l2=1; l2<=(nlstate+ndeath);l2++){
      } /* end jk */            if(l2==k2) continue;
    } /* end ng */            j=(k2-1)*(nlstate+ndeath)+l2;
    fflush(ficgp);             for (k1=1; k1<=(nlstate);k1++){
 }  /* end gnuplot */              for (l1=1; l1<=(nlstate+ndeath);l1++){
                 if(l1==k1) continue;
                 i=(k1-1)*(nlstate+ndeath)+l1;
 /*************** Moving average **************/                if(i<=j) continue;
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){                for (age=bage; age<=fage; age ++){
                   if ((int)age %5==0){
   int i, cpt, cptcod;                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
   int modcovmax =1;                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
   int mobilavrange, mob;                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
   double age;                    mu1=mu[i][(int) age]/stepm*YEARM ;
                     mu2=mu[j][(int) age]/stepm*YEARM;
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose                     c12=cv12/sqrt(v1*v2);
                            a covariate has 2 modalities */                    /* Computing eigen value of matrix of covariance */
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){                    /* Eigen vectors */
     if(mobilav==1) mobilavrange=5; /* default */                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
     else mobilavrange=mobilav;                    /*v21=sqrt(1.-v11*v11); *//* error */
     for (age=bage; age<=fage; age++)                    v21=(lc1-v1)/cv12*v11;
       for (i=1; i<=nlstate;i++)                    v12=-v21;
         for (cptcod=1;cptcod<=modcovmax;cptcod++)                    v22=v11;
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];                    tnalp=v21/v11;
     /* We keep the original values on the extreme ages bage, fage and for                     if(first1==1){
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2                      first1=0;
        we use a 5 terms etc. until the borders are no more concerned.                       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);
     */                     }
     for (mob=3;mob <=mobilavrange;mob=mob+2){                    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);
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){                    /*printf(fignu*/
         for (i=1; i<=nlstate;i++){                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
           for (cptcod=1;cptcod<=modcovmax;cptcod++){                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];                    if(first==1){
               for (cpt=1;cpt<=(mob-1)/2;cpt++){                      first=0;
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];                      fprintf(ficgp,"\nset parametric;unset label");
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];                      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);
               }                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
           }   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
         }  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
       }/* end age */                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
     }/* end mob */                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   }else return -1;                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   return 0;                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 }/* End movingaverage */                      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                       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);
 /************** Forecasting ******************/                      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",\
 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){                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
   /* proj1, year, month, day of starting projection                               mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
      agemin, agemax range of age                    }else{
      dateprev1 dateprev2 range of dates during which prevalence is computed                      first=0;
      anproj2 year of en of projection (same day and month as proj1).                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
   */                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
   int *popage;                      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 agec; /* generic age */                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
   double *popeffectif,*popcount;                    }/* if first */
   double ***p3mat;                  } /* age mod 5 */
   double ***mobaverage;                } /* end loop age */
   char fileresf[FILENAMELENGTH];                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                 first=1;
   agelim=AGESUP;              } /*l12 */
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);            } /* k12 */
            } /*l1 */
   strcpy(fileresf,"f");         }/* k1 */
   strcat(fileresf,fileres);      } /* loop covariates */
   if((ficresf=fopen(fileresf,"w"))==NULL) {    }
     printf("Problem with forecast resultfile: %s\n", fileresf);    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
   }    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
   printf("Computing forecasting: result on file '%s' \n", fileresf);    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);    free_vector(xp,1,npar);
     fclose(ficresprob);
   if (cptcoveff==0) ncodemax[cptcoveff]=1;    fclose(ficresprobcov);
     fclose(ficresprobcor);
   if (mobilav!=0) {    fflush(ficgp);
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    fflush(fichtmcov);
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){  }
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);  
       printf(" Error in movingaverage mobilav=%d\n",mobilav);  
     }  /******************* Printing html file ***********/
   }  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                     int lastpass, int stepm, int weightopt, char model[],\
   stepsize=(int) (stepm+YEARM-1)/YEARM;                    int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
   if (stepm<=12) stepsize=1;                    int popforecast, int estepm ,\
   if(estepm < stepm){                    double jprev1, double mprev1,double anprev1, \
     printf ("Problem %d lower than %d\n",estepm, stepm);                    double jprev2, double mprev2,double anprev2){
   }    int jj1, k1, i1, cpt;
   else  hstepm=estepm;     
      fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
   hstepm=hstepm/stepm;      <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and  </ul>");
                                fractional in yp1 */     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
   anprojmean=yp;   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
   yp2=modf((yp1*12),&yp);             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
   mprojmean=yp;     fprintf(fichtm,"\
   yp1=modf((yp2*30.5),&yp);   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
   jprojmean=yp;             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
   if(jprojmean==0) jprojmean=1;     fprintf(fichtm,"\
   if(mprojmean==0) jprojmean=1;   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
              subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
   i1=cptcoveff;     fprintf(fichtm,"\
   if (cptcovn < 1){i1=1;}   - (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): \
        <a href=\"%s\">%s</a> <br>\n",
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);              estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
        fprintf(fichtm,"\
   fprintf(ficresf,"#****** Routine prevforecast **\n");   - Population projections by age and states: \
      <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 /*            if (h==(int)(YEARM*yearp)){ */  
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){  
       k=k+1;   m=cptcoveff;
       fprintf(ficresf,"\n#******");   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
       for(j=1;j<=cptcoveff;j++) {  
         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]]);   jj1=0;
       }   for(k1=1; k1<=m;k1++){
       fprintf(ficresf,"******\n");     for(i1=1; i1<=ncodemax[k1];i1++){
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");       jj1++;
       for(j=1; j<=nlstate+ndeath;j++){        if (cptcovn > 0) {
         for(i=1; i<=nlstate;i++)                       fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
           fprintf(ficresf," p%d%d",i,j);         for (cpt=1; cpt<=cptcoveff;cpt++)
         fprintf(ficresf," p.%d",j);           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
       }         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {        }
         fprintf(ficresf,"\n");       /* Pij */
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+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> \
   <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
         for (agec=fage; agec>=(ageminpar-1); agec--){        /* Quasi-incidences */
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);        fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
           nhstepm = nhstepm/hstepm;    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> \
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
           oldm=oldms;savm=savms;         /* Period (stable) prevalence in each health state */
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);           for(cpt=1; cpt<nlstate;cpt++){
                    fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
           for (h=0; h<=nhstepm; h++){  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
             if (h*hstepm/YEARM*stepm ==yearp) {         }
               fprintf(ficresf,"\n");       for(cpt=1; cpt<=nlstate;cpt++) {
               for(j=1;j<=cptcoveff;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,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);       }
             }      } /* end i1 */
             for(j=1; j<=nlstate+ndeath;j++) {   }/* End k1 */
               ppij=0.;   fprintf(fichtm,"</ul>");
               for(i=1; i<=nlstate;i++) {  
                 if (mobilav==1)   
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];   fprintf(fichtm,"\
                 else {  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                 }  
                 if (h*hstepm/YEARM*stepm== yearp) {   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);           subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                 }   fprintf(fichtm,"\
               } /* end i */   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
               if (h*hstepm/YEARM*stepm==yearp) {           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                 fprintf(ficresf," %.3f", ppij);  
               }   fprintf(fichtm,"\
             }/* end j */   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
           } /* end h */           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   fprintf(fichtm,"\
         } /* end agec */   - 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): \
       } /* end yearp */     <a href=\"%s\">%s</a> <br>\n</li>",
     } /* end cptcod */             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
   } /* end  cptcov */   fprintf(fichtm,"\
           - (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): \
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);     <a href=\"%s\">%s</a> <br>\n</li>",
              estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
   fclose(ficresf);   fprintf(fichtm,"\
 }   - 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"));
 /************** Forecasting *****not tested NB*************/   fprintf(fichtm,"\
 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){   - 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",
              subdirf2(fileres,"t"),subdirf2(fileres,"t"));
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;   fprintf(fichtm,"\
   int *popage;   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
   double calagedatem, agelim, kk1, kk2;           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
   double *popeffectif,*popcount;  
   double ***p3mat,***tabpop,***tabpopprev;  /*  if(popforecast==1) fprintf(fichtm,"\n */
   double ***mobaverage;  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
   char filerespop[FILENAMELENGTH];  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
   /*      <br>",fileres,fileres,fileres,fileres); */
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  /*  else  */
   tabpopprev= ma3x(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); */
   agelim=AGESUP;   fflush(fichtm);
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
     
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);   m=cptcoveff;
      if (cptcovn < 1) {m=1;ncodemax[1]=1;}
     
   strcpy(filerespop,"pop");    jj1=0;
   strcat(filerespop,fileres);   for(k1=1; k1<=m;k1++){
   if((ficrespop=fopen(filerespop,"w"))==NULL) {     for(i1=1; i1<=ncodemax[k1];i1++){
     printf("Problem with forecast resultfile: %s\n", filerespop);       jj1++;
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);       if (cptcovn > 0) {
   }         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
   printf("Computing forecasting: result on file '%s' \n", filerespop);         for (cpt=1; cpt<=cptcoveff;cpt++)
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
          fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   if (cptcoveff==0) ncodemax[cptcoveff]=1;       }
        for(cpt=1; cpt<=nlstate;cpt++) {
   if (mobilav!=0) {         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);       }
       printf(" Error in movingaverage mobilav=%d\n",mobilav);       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
     }  health expectancies in states (1) and (2): %s%d.png<br>\
   }  <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
      } /* end i1 */
   stepsize=(int) (stepm+YEARM-1)/YEARM;   }/* End k1 */
   if (stepm<=12) stepsize=1;   fprintf(fichtm,"</ul>");
      fflush(fichtm);
   agelim=AGESUP;  }
     
   hstepm=1;  /******************* Gnuplot file **************/
   hstepm=hstepm/stepm;   void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
     
   if (popforecast==1) {    char dirfileres[132],optfileres[132];
     if((ficpop=fopen(popfile,"r"))==NULL) {    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
       printf("Problem with population file : %s\n",popfile);exit(0);    int ng;
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
     }   /*     printf("Problem with file %s",optionfilegnuplot); */
     popage=ivector(0,AGESUP);  /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
     popeffectif=vector(0,AGESUP);  /*   } */
     popcount=vector(0,AGESUP);  
         /*#ifdef windows */
     i=1;       fprintf(ficgp,"cd \"%s\" \n",pathc);
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;      /*#endif */
        m=pow(2,cptcoveff);
     imx=i;  
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];    strcpy(dirfileres,optionfilefiname);
   }    strcpy(optfileres,"vpl");
    /* 1eme*/
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){    for (cpt=1; cpt<= nlstate ; cpt ++) {
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){     for (k1=1; k1<= m ; k1 ++) {
       k=k+1;       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
       fprintf(ficrespop,"\n#******");       fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
       for(j=1;j<=cptcoveff;j++) {       fprintf(ficgp,"set xlabel \"Age\" \n\
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  set ylabel \"Probability\" \n\
       }  set ter png small\n\
       fprintf(ficrespop,"******\n");  set size 0.65,0.65\n\
       fprintf(ficrespop,"# Age");  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);  
       if (popforecast==1)  fprintf(ficrespop," [Population]");       for (i=1; i<= nlstate ; i ++) {
                if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       for (cpt=0; cpt<=0;cpt++) {          else fprintf(ficgp," \%%*lf (\%%*lf)");
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);          }
                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 (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){        for (i=1; i<= nlstate ; i ++) {
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);          if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
           nhstepm = nhstepm/hstepm;          else fprintf(ficgp," \%%*lf (\%%*lf)");
                  }
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);       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);
           oldm=oldms;savm=savms;       for (i=1; i<= nlstate ; i ++) {
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);           if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                  else fprintf(ficgp," \%%*lf (\%%*lf)");
           for (h=0; h<=nhstepm; h++){       }  
             if (h==(int) (calagedatem+YEARM*cpt)) {       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,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);     }
             }     }
             for(j=1; j<=nlstate+ndeath;j++) {    /*2 eme*/
               kk1=0.;kk2=0;   
               for(i=1; i<=nlstate;i++) {                  for (k1=1; k1<= m ; k1 ++) {
                 if (mobilav==1)       fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
                 else {     
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];      for (i=1; i<= nlstate+1 ; i ++) {
                 }        k=2*i;
               }        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
               if (h==(int)(calagedatem+12*cpt)){        for (j=1; j<= nlstate+1 ; j ++) {
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   /*fprintf(ficrespop," %.3f", kk1);          else fprintf(ficgp," \%%*lf (\%%*lf)");
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/        }  
               }        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
             }        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
             for(i=1; i<=nlstate;i++){        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
               kk1=0.;        for (j=1; j<= nlstate+1 ; j ++) {
                 for(j=1; j<=nlstate;j++){          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];           else fprintf(ficgp," \%%*lf (\%%*lf)");
                 }        }  
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];        fprintf(ficgp,"\" t\"\" w l 0,");
             }        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 ++) {
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)           if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);          else fprintf(ficgp," \%%*lf (\%%*lf)");
           }        }  
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
         }        else fprintf(ficgp,"\" t\"\" w l 0,");
       }      }
      }
   /******/   
     /*3eme*/
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {    
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);       for (k1=1; k1<= m ; k1 ++) {
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){       for (cpt=1; cpt<= nlstate ; cpt ++) {
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);         /*       k=2+nlstate*(2*cpt-2); */
           nhstepm = nhstepm/hstepm;         k=2+(nlstate+1)*(cpt-1);
                   fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        fprintf(ficgp,"set ter png small\n\
           oldm=oldms;savm=savms;  set size 0.65,0.65\n\
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);    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);
           for (h=0; h<=nhstepm; h++){        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
             if (h==(int) (calagedatem+YEARM*cpt)) {          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);          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(j=1; j<=nlstate+ndeath;j++) {          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
               kk1=0.;kk2=0;          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
               for(i=1; i<=nlstate;i++) {                       
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];            */
               }        for (i=1; i< nlstate ; i ++) {
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                  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);
             }          /*      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);*/
           }         
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        }
         }        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
       }      }
    }     }
   }   
      /* CV preval stable (period) */
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    for (k1=1; k1<= m ; k1 ++) {
       for (cpt=1; cpt<=nlstate ; cpt ++) {
   if (popforecast==1) {        k=3;
     free_ivector(popage,0,AGESUP);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
     free_vector(popeffectif,0,AGESUP);        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
     free_vector(popcount,0,AGESUP);  set ter png small\nset size 0.65,0.65\n\
   }  unset log y\n\
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);       
   fclose(ficrespop);        for (i=1; i< nlstate ; i ++)
 } /* End of popforecast */          fprintf(ficgp,"+$%d",k+i+1);
         fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
 int fileappend(FILE *fichier, char *optionfich)       
 {        l=3+(nlstate+ndeath)*cpt;
   if((fichier=fopen(optionfich,"a"))==NULL) {        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
     printf("Problem with file: %s\n", optionfich);        for (i=1; i< nlstate ; i ++) {
     fprintf(ficlog,"Problem with file: %s\n", optionfich);          l=3+(nlstate+ndeath)*cpt;
     return (0);          fprintf(ficgp,"+$%d",l+i+1);
   }        }
   fflush(fichier);        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
   return (1);      }
 }    }  
    
     /* proba elementaires */
 /**************** function prwizard **********************/    for(i=1,jk=1; i <=nlstate; i++){
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)      for(k=1; k <=(nlstate+ndeath); k++){
 {        if (k != i) {
           for(j=1; j <=ncovmodel; j++){
   /* Wizard to print covariance matrix template */            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
             jk++;
   char ca[32], cb[32], cc[32];            fprintf(ficgp,"\n");
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;          }
   int numlinepar;        }
       }
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");     }
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");  
   for(i=1; i <=nlstate; i++){     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
     jj=0;       for(jk=1; jk <=m; jk++) {
     for(j=1; j <=nlstate+ndeath; j++){         fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
       if(j==i) continue;         if (ng==2)
       jj++;           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
       /*ca[0]= k+'a'-1;ca[1]='\0';*/         else
       printf("%1d%1d",i,j);           fprintf(ficgp,"\nset title \"Probability\"\n");
       fprintf(ficparo,"%1d%1d",i,j);         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
       for(k=1; k<=ncovmodel;k++){         i=1;
         /*        printf(" %lf",param[i][j][k]); */         for(k2=1; k2<=nlstate; k2++) {
         /*        fprintf(ficparo," %lf",param[i][j][k]); */           k3=i;
         printf(" 0.");           for(k=1; k<=(nlstate+ndeath); k++) {
         fprintf(ficparo," 0.");             if (k != k2){
       }               if(ng==2)
       printf("\n");                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
       fprintf(ficparo,"\n");               else
     }                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
   }               ij=1;
   printf("# Scales (for hessian or gradient estimation)\n");               for(j=3; j <=ncovmodel; j++) {
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/                    fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
   for(i=1; i <=nlstate; i++){                   ij++;
     jj=0;                 }
     for(j=1; j <=nlstate+ndeath; j++){                 else
       if(j==i) continue;                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
       jj++;               }
       fprintf(ficparo,"%1d%1d",i,j);               fprintf(ficgp,")/(1");
       printf("%1d%1d",i,j);               
       fflush(stdout);               for(k1=1; k1 <=nlstate; k1++){  
       for(k=1; k<=ncovmodel;k++){                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
         /*      printf(" %le",delti3[i][j][k]); */                 ij=1;
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */                 for(j=3; j <=ncovmodel; j++){
         printf(" 0.");                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
         fprintf(ficparo," 0.");                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
       }                     ij++;
       numlinepar++;                   }
       printf("\n");                   else
       fprintf(ficparo,"\n");                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
     }                 }
   }                 fprintf(ficgp,")");
   printf("# Covariance matrix\n");               }
 /* # 121 Var(a12)\n\ */               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 /* # 122 Cov(b12,a12) Var(b12)\n\ */               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */               i=i+ncovmodel;
 /* # 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\ */           } /* end k */
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */         } /* end k2 */
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */       } /* end jk */
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */     } /* end ng */
   fflush(stdout);     fflush(ficgp);
   fprintf(ficparo,"# Covariance matrix\n");  }  /* end gnuplot */
   /* # 121 Var(a12)\n\ */  
   /* # 122 Cov(b12,a12) Var(b12)\n\ */  
   /* #   ...\n\ */  /*************** Moving average **************/
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
     
   for(itimes=1;itimes<=2;itimes++){    int i, cpt, cptcod;
     jj=0;    int modcovmax =1;
     for(i=1; i <=nlstate; i++){    int mobilavrange, mob;
       for(j=1; j <=nlstate+ndeath; j++){    double age;
         if(j==i) continue;  
         for(k=1; k<=ncovmodel;k++){    modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
           jj++;                             a covariate has 2 modalities */
           ca[0]= k+'a'-1;ca[1]='\0';    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
           if(itimes==1){  
             printf("#%1d%1d%d",i,j,k);    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
             fprintf(ficparo,"#%1d%1d%d",i,j,k);      if(mobilav==1) mobilavrange=5; /* default */
           }else{      else mobilavrange=mobilav;
             printf("%1d%1d%d",i,j,k);      for (age=bage; age<=fage; age++)
             fprintf(ficparo,"%1d%1d%d",i,j,k);        for (i=1; i<=nlstate;i++)
             /*  printf(" %.5le",matcov[i][j]); */          for (cptcod=1;cptcod<=modcovmax;cptcod++)
           }            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
           ll=0;      /* We keep the original values on the extreme ages bage, fage and for
           for(li=1;li <=nlstate; li++){         fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
             for(lj=1;lj <=nlstate+ndeath; lj++){         we use a 5 terms etc. until the borders are no more concerned.
               if(lj==li) continue;      */
               for(lk=1;lk<=ncovmodel;lk++){      for (mob=3;mob <=mobilavrange;mob=mob+2){
                 ll++;        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                 if(ll<=jj){          for (i=1; i<=nlstate;i++){
                   cb[0]= lk +'a'-1;cb[1]='\0';            for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   if(ll<jj){              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                     if(itimes==1){                for (cpt=1;cpt<=(mob-1)/2;cpt++){
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                     }else{                }
                       printf(" 0.");              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                       fprintf(ficparo," 0.");            }
                     }          }
                   }else{        }/* end age */
                     if(itimes==1){      }/* end mob */
                       printf(" Var(%s%1d%1d)",ca,i,j);    }else return -1;
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);    return 0;
                     }else{  }/* End movingaverage */
                       printf(" 0.");  
                       fprintf(ficparo," 0.");  
                     }  /************** Forecasting ******************/
                   }  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){
                 }    /* proj1, year, month, day of starting projection
               } /* end lk */       agemin, agemax range of age
             } /* end lj */       dateprev1 dateprev2 range of dates during which prevalence is computed
           } /* end li */       anproj2 year of en of projection (same day and month as proj1).
           printf("\n");    */
           fprintf(ficparo,"\n");    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
           numlinepar++;    int *popage;
         } /* end k*/    double agec; /* generic age */
       } /*end j */    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
     } /* end i */    double *popeffectif,*popcount;
   } /* end itimes */    double ***p3mat;
     double ***mobaverage;
 } /* end of prwizard */    char fileresf[FILENAMELENGTH];
   
     agelim=AGESUP;
 /***********************************************/    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 /**************** Main Program *****************/   
 /***********************************************/    strcpy(fileresf,"f");
     strcat(fileresf,fileres);
 int main(int argc, char *argv[])    if((ficresf=fopen(fileresf,"w"))==NULL) {
 {      printf("Problem with forecast resultfile: %s\n", fileresf);
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;    }
   int jj, ll, li, lj, lk, imk;    printf("Computing forecasting: result on file '%s' \n", fileresf);
   int numlinepar=0; /* Current linenumber of parameter file */    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
   int itimes;  
     if (cptcoveff==0) ncodemax[cptcoveff]=1;
   char ca[32], cb[32], cc[32];  
   /*  FILE *fichtm; *//* Html File */    if (mobilav!=0) {
   /* FILE *ficgp;*/ /*Gnuplot File */      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   double agedeb, agefin,hf;      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
         printf(" Error in movingaverage mobilav=%d\n",mobilav);
   double fret;      }
   double **xi,tmp,delta;    }
   
   double dum; /* Dummy variable */    stepsize=(int) (stepm+YEARM-1)/YEARM;
   double ***p3mat;    if (stepm<=12) stepsize=1;
   double ***mobaverage;    if(estepm < stepm){
   int *indx;      printf ("Problem %d lower than %d\n",estepm, stepm);
   char line[MAXLINE], linepar[MAXLINE];    }
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];    else  hstepm=estepm;  
   char pathr[MAXLINE];   
   int firstobs=1, lastobs=10;    hstepm=hstepm/stepm;
   int sdeb, sfin; /* Status at beginning and end */    yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
   int c,  h , cpt,l;                                 fractional in yp1 */
   int ju,jl, mi;    anprojmean=yp;
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;    yp2=modf((yp1*12),&yp);
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;     mprojmean=yp;
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */    yp1=modf((yp2*30.5),&yp);
   int mobilav=0,popforecast=0;    jprojmean=yp;
   int hstepm, nhstepm;    if(jprojmean==0) jprojmean=1;
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;    if(mprojmean==0) jprojmean=1;
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;  
     i1=cptcoveff;
   double bage, fage, age, agelim, agebase;    if (cptcovn < 1){i1=1;}
   double ftolpl=FTOL;   
   double **prlim;    fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
   double *severity;   
   double ***param; /* Matrix of parameters */    fprintf(ficresf,"#****** Routine prevforecast **\n");
   double  *p;  
   double **matcov; /* Matrix of covariance */  /*            if (h==(int)(YEARM*yearp)){ */
   double ***delti3; /* Scale */    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
   double *delti; /* Scale */      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   double ***eij, ***vareij;        k=k+1;
   double **varpl; /* Variances of prevalence limits by age */        fprintf(ficresf,"\n#******");
   double *epj, vepp;        for(j=1;j<=cptcoveff;j++) {
   double kk1, kk2;          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 dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;        }
         fprintf(ficresf,"******\n");
   char *alph[]={"a","a","b","c","d","e"}, str[4];        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
         for(j=1; j<=nlstate+ndeath;j++){
           for(i=1; i<=nlstate;i++)              
   char z[1]="c", occ;            fprintf(ficresf," p%d%d",i,j);
           fprintf(ficresf," p.%d",j);
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];        }
   char strstart[80], *strt, strtend[80];        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
   char *stratrunc;          fprintf(ficresf,"\n");
   int lstra;          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
   
   long total_usecs;          for (agec=fage; agec>=(ageminpar-1); agec--){
              nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
 /*   setlocale (LC_ALL, ""); */            nhstepm = nhstepm/hstepm;
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 /*   textdomain (PACKAGE); */            oldm=oldms;savm=savms;
 /*   setlocale (LC_CTYPE, ""); */            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 /*   setlocale (LC_MESSAGES, ""); */         
             for (h=0; h<=nhstepm; h++){
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */              if (h*hstepm/YEARM*stepm ==yearp) {
   (void) gettimeofday(&start_time,&tzp);                fprintf(ficresf,"\n");
   curr_time=start_time;                for(j=1;j<=cptcoveff;j++)
   tm = *localtime(&start_time.tv_sec);                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   tmg = *gmtime(&start_time.tv_sec);                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
   strcpy(strstart,asctime(&tm));              }
               for(j=1; j<=nlstate+ndeath;j++) {
 /*  printf("Localtime (at start)=%s",strstart); */                ppij=0.;
 /*  tp.tv_sec = tp.tv_sec +86400; */                for(i=1; i<=nlstate;i++) {
 /*  tm = *localtime(&start_time.tv_sec); */                  if (mobilav==1)
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */                  else {
 /*   tmg.tm_hour=tmg.tm_hour + 1; */                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 /*   tp.tv_sec = mktime(&tmg); */                  }
 /*   strt=asctime(&tmg); */                  if (h*hstepm/YEARM*stepm== yearp) {
 /*   printf("Time(after) =%s",strstart);  */                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
 /*  (void) time (&time_value);                  }
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);                } /* end i */
 *  tm = *localtime(&time_value);                if (h*hstepm/YEARM*stepm==yearp) {
 *  strstart=asctime(&tm);                  fprintf(ficresf," %.3f", ppij);
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);                 }
 */              }/* end j */
             } /* end h */
   nberr=0; /* Number of errors and warnings */            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   nbwarn=0;          } /* end agec */
   getcwd(pathcd, size);        } /* end yearp */
       } /* end cptcod */
   printf("\n%s\n%s",version,fullversion);    } /* end  cptcov */
   if(argc <=1){         
     printf("\nEnter the parameter file name: ");    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     scanf("%s",pathtot);  
   }    fclose(ficresf);
   else{  }
     strcpy(pathtot,argv[1]);  
   }  /************** Forecasting *****not tested NB*************/
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/  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){
   /*cygwin_split_path(pathtot,path,optionfile);   
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
   /* cutv(path,optionfile,pathtot,'\\');*/    int *popage;
     double calagedatem, agelim, kk1, kk2;
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);    double *popeffectif,*popcount;
   printf("pathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);    double ***p3mat,***tabpop,***tabpopprev;
   chdir(path);    double ***mobaverage;
   strcpy(command,"mkdir ");    char filerespop[FILENAMELENGTH];
   strcat(command,optionfilefiname);  
   if((outcmd=system(command)) != 0){    tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */    agelim=AGESUP;
     /* fclose(ficlog); */    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 /*     exit(1); */   
   }    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 /*   if((imk=mkdir(optionfilefiname))<0){ */   
 /*     perror("mkdir"); */   
 /*   } */    strcpy(filerespop,"pop");
     strcat(filerespop,fileres);
   /*-------- arguments in the command line --------*/    if((ficrespop=fopen(filerespop,"w"))==NULL) {
       printf("Problem with forecast resultfile: %s\n", filerespop);
   /* Log file */      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
   strcat(filelog, optionfilefiname);    }
   strcat(filelog,".log");    /* */    printf("Computing forecasting: result on file '%s' \n", filerespop);
   if((ficlog=fopen(filelog,"w"))==NULL)    {    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
     printf("Problem with logfile %s\n",filelog);  
     goto end;    if (cptcoveff==0) ncodemax[cptcoveff]=1;
   }  
   fprintf(ficlog,"Log filename:%s\n",filelog);    if (mobilav!=0) {
   fprintf(ficlog,"\n%s\n%s",version,fullversion);      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficlog,"\nEnter the parameter file name: ");      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
   fprintf(ficlog,"pathtot=%s\n\        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
  path=%s \n\        printf(" Error in movingaverage mobilav=%d\n",mobilav);
  optionfile=%s\n\      }
  optionfilext=%s\n\    }
  optionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);  
     stepsize=(int) (stepm+YEARM-1)/YEARM;
   printf("Local time (at start):%s",strstart);    if (stepm<=12) stepsize=1;
   fprintf(ficlog,"Local time (at start): %s",strstart);   
   fflush(ficlog);    agelim=AGESUP;
 /*   (void) gettimeofday(&curr_time,&tzp); */   
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */    hstepm=1;
     hstepm=hstepm/stepm;
   /* */   
   strcpy(fileres,"r");    if (popforecast==1) {
   strcat(fileres, optionfilefiname);      if((ficpop=fopen(popfile,"r"))==NULL) {
   strcat(fileres,".txt");    /* Other files have txt extension */        printf("Problem with population file : %s\n",popfile);exit(0);
         fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
   /*---------arguments file --------*/      }
       popage=ivector(0,AGESUP);
   if((ficpar=fopen(optionfile,"r"))==NULL)    {      popeffectif=vector(0,AGESUP);
     printf("Problem with optionfile %s\n",optionfile);      popcount=vector(0,AGESUP);
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);     
     fflush(ficlog);      i=1;  
     goto end;      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
   }     
       imx=i;
       for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
     }
   strcpy(filereso,"o");  
   strcat(filereso,fileres);    for(cptcov=1,k=0;cptcov<=i2;cptcov++){
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
     printf("Problem with Output resultfile: %s\n", filereso);        k=k+1;
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);        fprintf(ficrespop,"\n#******");
     fflush(ficlog);        for(j=1;j<=cptcoveff;j++) {
     goto end;          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   }        }
         fprintf(ficrespop,"******\n");
   /* Reads comments: lines beginning with '#' */        fprintf(ficrespop,"# Age");
   numlinepar=0;        for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
   while((c=getc(ficpar))=='#' && c!= EOF){        if (popforecast==1)  fprintf(ficrespop," [Population]");
     ungetc(c,ficpar);       
     fgets(line, MAXLINE, ficpar);        for (cpt=0; cpt<=0;cpt++) {
     numlinepar++;          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
     puts(line);         
     fputs(line,ficparo);          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
     fputs(line,ficlog);            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
   }            nhstepm = nhstepm/hstepm;
   ungetc(c,ficpar);           
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   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);            oldm=oldms;savm=savms;
   numlinepar++;            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   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);            for (h=0; h<=nhstepm; h++){
   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);              if (h==(int) (calagedatem+YEARM*cpt)) {
   fflush(ficlog);                fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   while((c=getc(ficpar))=='#' && c!= EOF){              }
     ungetc(c,ficpar);              for(j=1; j<=nlstate+ndeath;j++) {
     fgets(line, MAXLINE, ficpar);                kk1=0.;kk2=0;
     numlinepar++;                for(i=1; i<=nlstate;i++) {              
     puts(line);                  if (mobilav==1)
     fputs(line,ficparo);                    kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
     fputs(line,ficlog);                  else {
   }                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
   ungetc(c,ficpar);                  }
                 }
                    if (h==(int)(calagedatem+12*cpt)){
   covar=matrix(0,NCOVMAX,1,n);                   tabpop[(int)(agedeb)][j][cptcod]=kk1;
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/                    /*fprintf(ficrespop," %.3f", kk1);
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;                      if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                 }
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */              }
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */              for(i=1; i<=nlstate;i++){
                  kk1=0.;
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */                  for(j=1; j<=nlstate;j++){
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
     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);                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
     fclose (ficparo);              }
     fclose (ficlog);  
     exit(0);              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
   }                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
   /* Read guess parameters */            }
   /* Reads comments: lines beginning with '#' */            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   while((c=getc(ficpar))=='#' && c!= EOF){          }
     ungetc(c,ficpar);        }
     fgets(line, MAXLINE, ficpar);   
     numlinepar++;    /******/
     puts(line);  
     fputs(line,ficparo);        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
     fputs(line,ficlog);          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   }          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
   ungetc(c,ficpar);            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
             nhstepm = nhstepm/hstepm;
   param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);           
   for(i=1; i <=nlstate; i++){            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     j=0;            oldm=oldms;savm=savms;
     for(jj=1; jj <=nlstate+ndeath; jj++){            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
       if(jj==i) continue;            for (h=0; h<=nhstepm; h++){
       j++;              if (h==(int) (calagedatem+YEARM*cpt)) {
       fscanf(ficpar,"%1d%1d",&i1,&j1);                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
       if ((i1 != i) && (j1 != j)){              }
         printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);              for(j=1; j<=nlstate+ndeath;j++) {
         exit(1);                kk1=0.;kk2=0;
       }                for(i=1; i<=nlstate;i++) {              
       fprintf(ficparo,"%1d%1d",i1,j1);                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
       if(mle==1)                }
         printf("%1d%1d",i,j);                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
       fprintf(ficlog,"%1d%1d",i,j);              }
       for(k=1; k<=ncovmodel;k++){            }
         fscanf(ficpar," %lf",&param[i][j][k]);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         if(mle==1){          }
           printf(" %lf",param[i][j][k]);        }
           fprintf(ficlog," %lf",param[i][j][k]);     }
         }    }
         else   
           fprintf(ficlog," %lf",param[i][j][k]);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         fprintf(ficparo," %lf",param[i][j][k]);  
       }    if (popforecast==1) {
       fscanf(ficpar,"\n");      free_ivector(popage,0,AGESUP);
       numlinepar++;      free_vector(popeffectif,0,AGESUP);
       if(mle==1)      free_vector(popcount,0,AGESUP);
         printf("\n");    }
       fprintf(ficlog,"\n");    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       fprintf(ficparo,"\n");    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     }    fclose(ficrespop);
   }    } /* End of popforecast */
   fflush(ficlog);  
   int fileappend(FILE *fichier, char *optionfich)
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/  {
     if((fichier=fopen(optionfich,"a"))==NULL) {
   p=param[1][1];      printf("Problem with file: %s\n", optionfich);
         fprintf(ficlog,"Problem with file: %s\n", optionfich);
   /* Reads comments: lines beginning with '#' */      return (0);
   while((c=getc(ficpar))=='#' && c!= EOF){    }
     ungetc(c,ficpar);    fflush(fichier);
     fgets(line, MAXLINE, ficpar);    return (1);
     numlinepar++;  }
     puts(line);  
     fputs(line,ficparo);  
     fputs(line,ficlog);  /**************** function prwizard **********************/
   }  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
   ungetc(c,ficpar);  {
   
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    /* Wizard to print covariance matrix template */
   /* delti=vector(1,npar); *//* Scale of each paramater (output from hesscov) */  
   for(i=1; i <=nlstate; i++){    char ca[32], cb[32], cc[32];
     for(j=1; j <=nlstate+ndeath-1; j++){    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
       fscanf(ficpar,"%1d%1d",&i1,&j1);    int numlinepar;
       if ((i1-i)*(j1-j)!=0){  
         printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         exit(1);    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       }    for(i=1; i <=nlstate; i++){
       printf("%1d%1d",i,j);      jj=0;
       fprintf(ficparo,"%1d%1d",i1,j1);      for(j=1; j <=nlstate+ndeath; j++){
       fprintf(ficlog,"%1d%1d",i1,j1);        if(j==i) continue;
       for(k=1; k<=ncovmodel;k++){        jj++;
         fscanf(ficpar,"%le",&delti3[i][j][k]);        /*ca[0]= k+'a'-1;ca[1]='\0';*/
         printf(" %le",delti3[i][j][k]);        printf("%1d%1d",i,j);
         fprintf(ficparo," %le",delti3[i][j][k]);        fprintf(ficparo,"%1d%1d",i,j);
         fprintf(ficlog," %le",delti3[i][j][k]);        for(k=1; k<=ncovmodel;k++){
       }          /*        printf(" %lf",param[i][j][k]); */
       fscanf(ficpar,"\n");          /*        fprintf(ficparo," %lf",param[i][j][k]); */
       numlinepar++;          printf(" 0.");
       printf("\n");          fprintf(ficparo," 0.");
       fprintf(ficparo,"\n");        }
       fprintf(ficlog,"\n");        printf("\n");
     }        fprintf(ficparo,"\n");
   }      }
   fflush(ficlog);    }
     printf("# Scales (for hessian or gradient estimation)\n");
   delti=delti3[1][1];    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
     npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
     for(i=1; i <=nlstate; i++){
   /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */      jj=0;
         for(j=1; j <=nlstate+ndeath; j++){
   /* Reads comments: lines beginning with '#' */        if(j==i) continue;
   while((c=getc(ficpar))=='#' && c!= EOF){        jj++;
     ungetc(c,ficpar);        fprintf(ficparo,"%1d%1d",i,j);
     fgets(line, MAXLINE, ficpar);        printf("%1d%1d",i,j);
     numlinepar++;        fflush(stdout);
     puts(line);        for(k=1; k<=ncovmodel;k++){
     fputs(line,ficparo);          /*      printf(" %le",delti3[i][j][k]); */
     fputs(line,ficlog);          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
   }          printf(" 0.");
   ungetc(c,ficpar);          fprintf(ficparo," 0.");
           }
   matcov=matrix(1,npar,1,npar);        numlinepar++;
   for(i=1; i <=npar; i++){        printf("\n");
     fscanf(ficpar,"%s",&str);        fprintf(ficparo,"\n");
     if(mle==1)      }
       printf("%s",str);    }
     fprintf(ficlog,"%s",str);    printf("# Covariance matrix\n");
     fprintf(ficparo,"%s",str);  /* # 121 Var(a12)\n\ */
     for(j=1; j <=i; j++){  /* # 122 Cov(b12,a12) Var(b12)\n\ */
       fscanf(ficpar," %le",&matcov[i][j]);  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
       if(mle==1){  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
         printf(" %.5le",matcov[i][j]);  /* # 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\ */
       fprintf(ficlog," %.5le",matcov[i][j]);  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
       fprintf(ficparo," %.5le",matcov[i][j]);  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
     }    fflush(stdout);
     fscanf(ficpar,"\n");    fprintf(ficparo,"# Covariance matrix\n");
     numlinepar++;    /* # 121 Var(a12)\n\ */
     if(mle==1)    /* # 122 Cov(b12,a12) Var(b12)\n\ */
       printf("\n");    /* #   ...\n\ */
     fprintf(ficlog,"\n");    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
     fprintf(ficparo,"\n");   
   }    for(itimes=1;itimes<=2;itimes++){
   for(i=1; i <=npar; i++)      jj=0;
     for(j=i+1;j<=npar;j++)      for(i=1; i <=nlstate; i++){
       matcov[i][j]=matcov[j][i];        for(j=1; j <=nlstate+ndeath; j++){
              if(j==i) continue;
   if(mle==1)          for(k=1; k<=ncovmodel;k++){
     printf("\n");            jj++;
   fprintf(ficlog,"\n");            ca[0]= k+'a'-1;ca[1]='\0';
             if(itimes==1){
   fflush(ficlog);              printf("#%1d%1d%d",i,j,k);
               fprintf(ficparo,"#%1d%1d%d",i,j,k);
   /*-------- Rewriting paramater file ----------*/            }else{
   strcpy(rfileres,"r");    /* "Rparameterfile */              printf("%1d%1d%d",i,j,k);
   strcat(rfileres,optionfilefiname);    /* Parameter file first name*/              fprintf(ficparo,"%1d%1d%d",i,j,k);
   strcat(rfileres,".");    /* */              /*  printf(" %.5le",matcov[i][j]); */
   strcat(rfileres,optionfilext);    /* Other files have txt extension */            }
   if((ficres =fopen(rfileres,"w"))==NULL) {            ll=0;
     printf("Problem writing new parameter file: %s\n", fileres);goto end;            for(li=1;li <=nlstate; li++){
     fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;              for(lj=1;lj <=nlstate+ndeath; lj++){
   }                if(lj==li) continue;
   fprintf(ficres,"#%s\n",version);                for(lk=1;lk<=ncovmodel;lk++){
                       ll++;
   /*-------- data file ----------*/                  if(ll<=jj){
   if((fic=fopen(datafile,"r"))==NULL)    {                    cb[0]= lk +'a'-1;cb[1]='\0';
     printf("Problem with datafile: %s\n", datafile);goto end;                    if(ll<jj){
     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;                      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);
   n= lastobs;                      }else{
   severity = vector(1,maxwav);                        printf(" 0.");
   outcome=imatrix(1,maxwav+1,1,n);                        fprintf(ficparo," 0.");
   num=lvector(1,n);                      }
   moisnais=vector(1,n);                    }else{
   annais=vector(1,n);                      if(itimes==1){
   moisdc=vector(1,n);                        printf(" Var(%s%1d%1d)",ca,i,j);
   andc=vector(1,n);                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
   agedc=vector(1,n);                      }else{
   cod=ivector(1,n);                        printf(" 0.");
   weight=vector(1,n);                        fprintf(ficparo," 0.");
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */                      }
   mint=matrix(1,maxwav,1,n);                    }
   anint=matrix(1,maxwav,1,n);                  }
   s=imatrix(1,maxwav+1,1,n);                } /* end lk */
   tab=ivector(1,NCOVMAX);              } /* end lj */
   ncodemax=ivector(1,8);            } /* end li */
             printf("\n");
   i=1;            fprintf(ficparo,"\n");
   while (fgets(line, MAXLINE, fic) != NULL)    {            numlinepar++;
     if ((i >= firstobs) && (i <=lastobs)) {          } /* end k*/
                 } /*end j */
       for (j=maxwav;j>=1;j--){      } /* end i */
         cutv(stra, strb,line,' '); s[j][i]=atoi(strb);     } /* end itimes */
         strcpy(line,stra);  
         cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);  } /* end of prwizard */
         cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);  /******************* Gompertz Likelihood ******************************/
       }  double gompertz(double x[])
           {
       cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);    double A,B,L=0.0,sump=0.,num=0.;
       cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);    int i,n=0; /* n is the size of the sample */
   
       cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);    for (i=0;i<=imx-1 ; i++) {
       cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);      sump=sump+weight[i];
       /*    sump=sump+1;*/
       cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);      num=num+1;
       for (j=ncovcol;j>=1;j--){    }
         cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);   
       }    
       lstra=strlen(stra);    /* for (i=0; i<=imx; i++)
       if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */       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]);*/
         stratrunc = &(stra[lstra-9]);  
         num[i]=atol(stratrunc);    for (i=1;i<=imx ; i++)
       }      {
       else        if (cens[i] == 1 && wav[i]>1)
         num[i]=atol(stra);          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                
       /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){        if (cens[i] == 0 && wav[i]>1)
         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;}*/          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);  
       i=i+1;       
     }        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
   }        if (wav[i] > 1 ) { /* ??? */
   /* printf("ii=%d", ij);          L=L+A*weight[i];
      scanf("%d",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]);*/
   imx=i-1; /* Number of individuals */        }
       }
   /* for (i=1; i<=imx; i++){  
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
     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;    return -2*L*num/sump;
     }*/  }
    /*  for (i=1; i<=imx; i++){  
      if (s[4][i]==9)  s[4][i]=-1;   /******************* Printing html file ***********/
      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]));}*/  void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                       int lastpass, int stepm, int weightopt, char model[],\
  for (i=1; i<=imx; i++)                    int imx,  double p[],double **matcov,double agemortsup){
      int i,k;
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;  
      else weight[i]=1;*/    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);
   /* Calculation of the number of parameter from char model*/    for (i=1;i<=2;i++)
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */      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]));
   Tprod=ivector(1,15);     fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
   Tvaraff=ivector(1,15);     fprintf(fichtm,"</ul>");
   Tvard=imatrix(1,15,1,2);  
   Tage=ivector(1,15);        fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
      
   if (strlen(model) >1){ /* If there is at least 1 covariate */   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>");
     j=0, j1=0, k1=1, k2=1;  
     j=nbocc(model,'+'); /* j=Number of '+' */   for (k=agegomp;k<(agemortsup-2);k++)
     j1=nbocc(model,'*'); /* j1=Number of '*' */     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]);
     cptcovn=j+1;   
     cptcovprod=j1; /*Number of products */   
         fflush(fichtm);
     strcpy(modelsav,model);   }
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){  
       printf("Error. Non available option model=%s ",model);  /******************* Gnuplot file **************/
       fprintf(ficlog,"Error. Non available option model=%s ",model);  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
       goto end;  
     }    char dirfileres[132],optfileres[132];
         int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     /* This loop fills the array Tvar from the string 'model'.*/    int ng;
   
     for(i=(j+1); i>=1;i--){  
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */     /*#ifdef windows */
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */    fprintf(ficgp,"cd \"%s\" \n",pathc);
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/      /*#endif */
       /*scanf("%d",i);*/  
       if (strchr(strb,'*')) {  /* Model includes a product */  
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/    strcpy(dirfileres,optionfilefiname);
         if (strcmp(strc,"age")==0) { /* Vn*age */    strcpy(optfileres,"vpl");
           cptcovprod--;    fprintf(ficgp,"set out \"graphmort.png\"\n ");
           cutv(strb,stre,strd,'V');    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/    fprintf(ficgp, "set ter png small\n set log y\n");
           cptcovage++;    fprintf(ficgp, "set size 0.65,0.65\n");
             Tage[cptcovage]=i;    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
             /*printf("stre=%s ", stre);*/  
         }  }
         else if (strcmp(strd,"age")==0) { /* or age*Vn */  
           cptcovprod--;  
           cutv(strb,stre,strc,'V');  
           Tvar[i]=atoi(stre);  
           cptcovage++;  
           Tage[cptcovage]=i;  /***********************************************/
         }  /**************** Main Program *****************/
         else {  /* Age is not in the model */  /***********************************************/
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/  
           Tvar[i]=ncovcol+k1;  int main(int argc, char *argv[])
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */  {
           Tprod[k1]=i;    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
           Tvard[k1][1]=atoi(strc); /* m*/    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
           Tvard[k1][2]=atoi(stre); /* n */    int linei, month, year,iout;
           Tvar[cptcovn+k2]=Tvard[k1][1];    int jj, ll, li, lj, lk, imk;
           Tvar[cptcovn+k2+1]=Tvard[k1][2];     int numlinepar=0; /* Current linenumber of parameter file */
           for (k=1; k<=lastobs;k++)     int itimes;
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];    int NDIM=2;
           k1++;  
           k2=k2+2;    char ca[32], cb[32], cc[32];
         }    char dummy[]="                         ";
       }    /*  FILE *fichtm; *//* Html File */
       else { /* no more sum */    /* FILE *ficgp;*/ /*Gnuplot File */
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/    struct stat info;
        /*  scanf("%d",i);*/    double agedeb, agefin,hf;
       cutv(strd,strc,strb,'V');    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
       Tvar[i]=atoi(strc);  
       }    double fret;
       strcpy(modelsav,stra);      double **xi,tmp,delta;
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);  
         scanf("%d",i);*/    double dum; /* Dummy variable */
     } /* end of loop + */    double ***p3mat;
   } /* end model */    double ***mobaverage;
       int *indx;
   /*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 line[MAXLINE], linepar[MAXLINE];
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
     char pathr[MAXLINE], pathimach[MAXLINE];
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);    char **bp, *tok, *val; /* pathtot */
   printf("cptcovprod=%d ", cptcovprod);    int firstobs=1, lastobs=10;
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);    int sdeb, sfin; /* Status at beginning and end */
     int c,  h , cpt,l;
   scanf("%d ",i);    int ju,jl, mi;
   fclose(fic);*/    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
     int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
     /*  if(mle==1){*/    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
   if (weightopt != 1) { /* Maximisation without weights*/    int mobilav=0,popforecast=0;
     for(i=1;i<=n;i++) weight[i]=1.0;    int hstepm, nhstepm;
   }    int agemortsup;
     /*-calculation of age at interview from date of interview and age at death -*/    float  sumlpop=0.;
   agev=matrix(1,maxwav,1,imx);    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;
   for (i=1; i<=imx; i++) {  
     for(m=2; (m<= maxwav); m++) {    double bage, fage, age, agelim, agebase;
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){    double ftolpl=FTOL;
         anint[m][i]=9999;    double **prlim;
         s[m][i]=-1;    double *severity;
       }    double ***param; /* Matrix of parameters */
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){    double  *p;
         nberr++;    double **matcov; /* Matrix of covariance */
         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 ***delti3; /* Scale */
         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 *delti; /* Scale */
         s[m][i]=-1;    double ***eij, ***vareij;
       }    double **varpl; /* Variances of prevalence limits by age */
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){    double *epj, vepp;
         nberr++;    double kk1, kk2;
         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]);     double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
         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]);     double **ximort;
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */    char *alph[]={"a","a","b","c","d","e"}, str[4];
       }    int *dcwave;
     }  
   }    char z[1]="c", occ;
   
   for (i=1; i<=imx; i++)  {    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);    char  *strt, strtend[80];
     for(m=firstpass; (m<= lastpass); m++){    char *stratrunc;
       if(s[m][i] >0){    int lstra;
         if (s[m][i] >= nlstate+1) {  
           if(agedc[i]>0)    long total_usecs;
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)   
               agev[m][i]=agedc[i];  /*   setlocale (LC_ALL, ""); */
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
             else {  /*   textdomain (PACKAGE); */
               if ((int)andc[i]!=9999){  /*   setlocale (LC_CTYPE, ""); */
                 nbwarn++;  /*   setlocale (LC_MESSAGES, ""); */
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);  
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                 agev[m][i]=-1;    (void) gettimeofday(&start_time,&tzp);
               }    curr_time=start_time;
             }    tm = *localtime(&start_time.tv_sec);
         }    tmg = *gmtime(&start_time.tv_sec);
         else if(s[m][i] !=9){ /* Standard case, age in fractional    strcpy(strstart,asctime(&tm));
                                  years but with the precision of a  
                                  month */  /*  printf("Localtime (at start)=%s",strstart); */
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);  /*  tp.tv_sec = tp.tv_sec +86400; */
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)  /*  tm = *localtime(&start_time.tv_sec); */
             agev[m][i]=1;  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
           else if(agev[m][i] <agemin){   /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
             agemin=agev[m][i];  /*   tmg.tm_hour=tmg.tm_hour + 1; */
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/  /*   tp.tv_sec = mktime(&tmg); */
           }  /*   strt=asctime(&tmg); */
           else if(agev[m][i] >agemax){  /*   printf("Time(after) =%s",strstart);  */
             agemax=agev[m][i];  /*  (void) time (&time_value);
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
           }  *  tm = *localtime(&time_value);
           /*agev[m][i]=anint[m][i]-annais[i];*/  *  strstart=asctime(&tm);
           /*     agev[m][i] = age[i]+2*m;*/  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
         }  */
         else { /* =9 */  
           agev[m][i]=1;    nberr=0; /* Number of errors and warnings */
           s[m][i]=-1;    nbwarn=0;
         }    getcwd(pathcd, size);
       }  
       else /*= 0 Unknown */    printf("\n%s\n%s",version,fullversion);
         agev[m][i]=1;    if(argc <=1){
     }      printf("\nEnter the parameter file name: ");
           fgets(pathr,FILENAMELENGTH,stdin);
   }      i=strlen(pathr);
   for (i=1; i<=imx; i++)  {      if(pathr[i-1]=='\n')
     for(m=firstpass; (m<=lastpass); m++){        pathr[i-1]='\0';
       if (s[m][i] > (nlstate+ndeath)) {     for (tok = pathr; tok != NULL; ){
         nberr++;        printf("Pathr |%s|\n",pathr);
         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);             while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
         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);             printf("val= |%s| pathr=%s\n",val,pathr);
         goto end;        strcpy (pathtot, val);
       }        if(pathr[0] == '\0') break; /* Dirty */
     }      }
   }    }
     else{
   /*for (i=1; i<=imx; i++){      strcpy(pathtot,argv[1]);
   for (m=firstpass; (m<lastpass); m++){    }
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 }    /*cygwin_split_path(pathtot,path,optionfile);
       printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 }*/    /* cutv(path,optionfile,pathtot,'\\');*/
   
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);    /* Split argv[0], imach program to get pathimach */
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);     printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
     split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   free_vector(severity,1,maxwav);    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   free_imatrix(outcome,1,maxwav+1,1,n);   /*   strcpy(pathimach,argv[0]); */
   free_vector(moisnais,1,n);    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
   free_vector(annais,1,n);    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
   /* free_matrix(mint,1,maxwav,1,n);    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
      free_matrix(anint,1,maxwav,1,n);*/    chdir(path); /* Can be a relative path */
   free_vector(moisdc,1,n);    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
   free_vector(andc,1,n);      printf("Current directory %s!\n",pathcd);
     strcpy(command,"mkdir ");
        strcat(command,optionfilefiname);
   wav=ivector(1,imx);    if((outcmd=system(command)) != 0){
   dh=imatrix(1,lastpass-firstpass+1,1,imx);      printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
   bh=imatrix(1,lastpass-firstpass+1,1,imx);      /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
   mw=imatrix(1,lastpass-firstpass+1,1,imx);      /* fclose(ficlog); */
      /*     exit(1); */
   /* Concatenates waves */    }
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);  /*   if((imk=mkdir(optionfilefiname))<0){ */
   /*     perror("mkdir"); */
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */  /*   } */
   
   Tcode=ivector(1,100);    /*-------- arguments in the command line --------*/
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);   
   ncodemax[1]=1;    /* Log file */
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);    strcat(filelog, optionfilefiname);
           strcat(filelog,".log");    /* */
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of     if((ficlog=fopen(filelog,"w"))==NULL)    {
                                  the estimations*/      printf("Problem with logfile %s\n",filelog);
   h=0;      goto end;
   m=pow(2,cptcoveff);    }
      fprintf(ficlog,"Log filename:%s\n",filelog);
   for(k=1;k<=cptcoveff; k++){    fprintf(ficlog,"\n%s\n%s",version,fullversion);
     for(i=1; i <=(m/pow(2,k));i++){    fprintf(ficlog,"\nEnter the parameter file name: \n");
       for(j=1; j <= ncodemax[k]; j++){    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){   path=%s \n\
           h++;   optionfile=%s\n\
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;   optionfilext=%s\n\
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
         }   
       }    printf("Local time (at start):%s",strstart);
     }    fprintf(ficlog,"Local time (at start): %s",strstart);
   }     fflush(ficlog);
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);   /*   (void) gettimeofday(&curr_time,&tzp); */
      codtab[1][2]=1;codtab[2][2]=2; */  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   /* for(i=1; i <=m ;i++){   
      for(k=1; k <=cptcovn; k++){    /* */
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);    strcpy(fileres,"r");
      }    strcat(fileres, optionfilefiname);
      printf("\n");    strcat(fileres,".txt");    /* Other files have txt extension */
      }  
      scanf("%d",i);*/    /*---------arguments file --------*/
       
   /*------------ gnuplot -------------*/    if((ficpar=fopen(optionfile,"r"))==NULL)    {
   strcpy(optionfilegnuplot,optionfilefiname);      printf("Problem with optionfile %s\n",optionfile);
   strcat(optionfilegnuplot,".gp");      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {      fflush(ficlog);
     printf("Problem with file %s",optionfilegnuplot);      goto end;
   }    }
   else{  
     fprintf(ficgp,"\n# %s\n", version);   
     fprintf(ficgp,"# %s\n", optionfilegnuplot);   
     fprintf(ficgp,"set missing 'NaNq'\n");    strcpy(filereso,"o");
   }    strcat(filereso,fileres);
   /*  fclose(ficgp);*/    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
   /*--------- index.htm --------*/      printf("Problem with Output resultfile: %s\n", filereso);
       fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */      fflush(ficlog);
   strcat(optionfilehtm,".htm");      goto end;
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {    }
     printf("Problem with %s \n",optionfilehtm), exit(0);  
   }    /* Reads comments: lines beginning with '#' */
     numlinepar=0;
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */    while((c=getc(ficpar))=='#' && c!= EOF){
   strcat(optionfilehtmcov,"-cov.htm");      ungetc(c,ficpar);
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {      fgets(line, MAXLINE, ficpar);
     printf("Problem with %s \n",optionfilehtmcov), exit(0);      numlinepar++;
   }      puts(line);
   else{      fputs(line,ficparo);
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \      fputs(line,ficlog);
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    }
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\    ungetc(c,ficpar);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);  
   }    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);
     numlinepar++;
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \    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);
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    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);
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\    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);
 \n\    fflush(ficlog);
 <hr  size=\"2\" color=\"#EC5E5E\">\    while((c=getc(ficpar))=='#' && c!= EOF){
  <ul><li><h4>Parameter files</h4>\n\      ungetc(c,ficpar);
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\      fgets(line, MAXLINE, ficpar);
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\      numlinepar++;
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\      puts(line);
  - Date and time at start: %s</ul>\n",\      fputs(line,ficparo);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\      fputs(line,ficlog);
           fileres,fileres,\    }
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);    ungetc(c,ficpar);
   fflush(fichtm);  
      
   strcpy(pathr,path);    covar=matrix(0,NCOVMAX,1,n);
   strcat(pathr,optionfilefiname);    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
   chdir(optionfilefiname); /* Move to directory named optionfile */    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
     
   /* Calculates basic frequencies. Computes observed prevalence at single age    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
      and prints on file fileres'p'. */    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
   
   fprintf(fichtm,"\n");    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\    delti=delti3[1][1];
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
           imx,agemin,agemax,jmin,jmax,jmean);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      fclose (ficparo);
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */      fclose (ficlog);
           goto end;
          exit(0);
   /* 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] */    else if(mle==-3) {
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
       printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/      fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
   likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
   printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);      matcov=matrix(1,npar,1,npar);
   for (k=1; k<=npar;k++)    }
     printf(" %d %8.5f",k,p[k]);    else{
   printf("\n");      /* Read guess parameters */
   globpr=1; /* to print the contributions */      /* 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("Second 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);
   if(mle>=1){ /* Could be 1 or 2 */        fputs(line,ficparo);
     mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);        fputs(line,ficlog);
   }      }
           ungetc(c,ficpar);
   /*--------- 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);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         for(i=1; i <=nlstate; i++){
         j=0;
   fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        for(jj=1; jj <=nlstate+ndeath; jj++){
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");          if(jj==i) continue;
   fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");          j++;
   for(i=1,jk=1; i <=nlstate; i++){          fscanf(ficpar,"%1d%1d",&i1,&j1);
     for(k=1; k <=(nlstate+ndeath); k++){          if ((i1 != i) && (j1 != j)){
       if (k != i) {            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
         printf("%d%d ",i,k);  It might be a problem of design; if ncovcol and the model are correct\n \
         fprintf(ficlog,"%d%d ",i,k);  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
         fprintf(ficres,"%1d%1d ",i,k);            exit(1);
         for(j=1; j <=ncovmodel; j++){          }
           printf("%f ",p[jk]);          fprintf(ficparo,"%1d%1d",i1,j1);
           fprintf(ficlog,"%f ",p[jk]);          if(mle==1)
           fprintf(ficres,"%f ",p[jk]);            printf("%1d%1d",i,j);
           jk++;           fprintf(ficlog,"%1d%1d",i,j);
         }          for(k=1; k<=ncovmodel;k++){
         printf("\n");            fscanf(ficpar," %lf",&param[i][j][k]);
         fprintf(ficlog,"\n");            if(mle==1){
         fprintf(ficres,"\n");              printf(" %lf",param[i][j][k]);
       }              fprintf(ficlog," %lf",param[i][j][k]);
     }            }
   }            else
   if(mle!=0){              fprintf(ficlog," %lf",param[i][j][k]);
     /* Computing hessian and covariance matrix */            fprintf(ficparo," %lf",param[i][j][k]);
     ftolhess=ftol; /* Usually correct */          }
     hesscov(matcov, p, npar, delti, ftolhess, func);          fscanf(ficpar,"\n");
   }          numlinepar++;
   fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");          if(mle==1)
   printf("# Scales (for hessian or gradient estimation)\n");            printf("\n");
   fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");          fprintf(ficlog,"\n");
   for(i=1,jk=1; i <=nlstate; i++){          fprintf(ficparo,"\n");
     for(j=1; j <=nlstate+ndeath; j++){        }
       if (j!=i) {      }  
         fprintf(ficres,"%1d%1d",i,j);      fflush(ficlog);
         printf("%1d%1d",i,j);  
         fprintf(ficlog,"%1d%1d",i,j);      p=param[1][1];
         for(k=1; k<=ncovmodel;k++){     
           printf(" %.5e",delti[jk]);      /* Reads comments: lines beginning with '#' */
           fprintf(ficlog," %.5e",delti[jk]);      while((c=getc(ficpar))=='#' && c!= EOF){
           fprintf(ficres," %.5e",delti[jk]);        ungetc(c,ficpar);
           jk++;        fgets(line, MAXLINE, ficpar);
         }        numlinepar++;
         printf("\n");        puts(line);
         fprintf(ficlog,"\n");        fputs(line,ficparo);
         fprintf(ficres,"\n");        fputs(line,ficlog);
       }      }
     }      ungetc(c,ficpar);
   }  
          for(i=1; i <=nlstate; i++){
   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");        for(j=1; j <=nlstate+ndeath-1; j++){
   if(mle>=1)          fscanf(ficpar,"%1d%1d",&i1,&j1);
     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");          if ((i1-i)*(j1-j)!=0){
   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("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 /* # 121 Var(a12)\n\ */            exit(1);
 /* # 122 Cov(b12,a12) Var(b12)\n\ */          }
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */          printf("%1d%1d",i,j);
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */          fprintf(ficparo,"%1d%1d",i1,j1);
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */          fprintf(ficlog,"%1d%1d",i1,j1);
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */          for(k=1; k<=ncovmodel;k++){
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */            fscanf(ficpar,"%le",&delti3[i][j][k]);
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */            printf(" %le",delti3[i][j][k]);
             fprintf(ficparo," %le",delti3[i][j][k]);
             fprintf(ficlog," %le",delti3[i][j][k]);
 /* Just to have a covariance matrix which will be more understandable          }
    even is we still don't want to manage dictionary of variables          fscanf(ficpar,"\n");
 */          numlinepar++;
   for(itimes=1;itimes<=2;itimes++){          printf("\n");
     jj=0;          fprintf(ficparo,"\n");
     for(i=1; i <=nlstate; i++){          fprintf(ficlog,"\n");
       for(j=1; j <=nlstate+ndeath; j++){        }
         if(j==i) continue;      }
         for(k=1; k<=ncovmodel;k++){      fflush(ficlog);
           jj++;  
           ca[0]= k+'a'-1;ca[1]='\0';      delti=delti3[1][1];
           if(itimes==1){  
             if(mle>=1)  
               printf("#%1d%1d%d",i,j,k);      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
             fprintf(ficlog,"#%1d%1d%d",i,j,k);   
             fprintf(ficres,"#%1d%1d%d",i,j,k);      /* Reads comments: lines beginning with '#' */
           }else{      while((c=getc(ficpar))=='#' && c!= EOF){
             if(mle>=1)        ungetc(c,ficpar);
               printf("%1d%1d%d",i,j,k);        fgets(line, MAXLINE, ficpar);
             fprintf(ficlog,"%1d%1d%d",i,j,k);        numlinepar++;
             fprintf(ficres,"%1d%1d%d",i,j,k);        puts(line);
           }        fputs(line,ficparo);
           ll=0;        fputs(line,ficlog);
           for(li=1;li <=nlstate; li++){      }
             for(lj=1;lj <=nlstate+ndeath; lj++){      ungetc(c,ficpar);
               if(lj==li) continue;   
               for(lk=1;lk<=ncovmodel;lk++){      matcov=matrix(1,npar,1,npar);
                 ll++;      for(i=1; i <=npar; i++){
                 if(ll<=jj){        fscanf(ficpar,"%s",&str);
                   cb[0]= lk +'a'-1;cb[1]='\0';        if(mle==1)
                   if(ll<jj){          printf("%s",str);
                     if(itimes==1){        fprintf(ficlog,"%s",str);
                       if(mle>=1)        fprintf(ficparo,"%s",str);
                         printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);        for(j=1; j <=i; j++){
                       fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);          fscanf(ficpar," %le",&matcov[i][j]);
                       fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);          if(mle==1){
                     }else{            printf(" %.5le",matcov[i][j]);
                       if(mle>=1)          }
                         printf(" %.5e",matcov[jj][ll]);           fprintf(ficlog," %.5le",matcov[i][j]);
                       fprintf(ficlog," %.5e",matcov[jj][ll]);           fprintf(ficparo," %.5le",matcov[i][j]);
                       fprintf(ficres," %.5e",matcov[jj][ll]);         }
                     }        fscanf(ficpar,"\n");
                   }else{        numlinepar++;
                     if(itimes==1){        if(mle==1)
                       if(mle>=1)          printf("\n");
                         printf(" Var(%s%1d%1d)",ca,i,j);        fprintf(ficlog,"\n");
                       fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);        fprintf(ficparo,"\n");
                       fprintf(ficres," Var(%s%1d%1d)",ca,i,j);      }
                     }else{      for(i=1; i <=npar; i++)
                       if(mle>=1)        for(j=i+1;j<=npar;j++)
                         printf(" %.5e",matcov[jj][ll]);           matcov[i][j]=matcov[j][i];
                       fprintf(ficlog," %.5e",matcov[jj][ll]);      
                       fprintf(ficres," %.5e",matcov[jj][ll]);       if(mle==1)
                     }        printf("\n");
                   }      fprintf(ficlog,"\n");
                 }     
               } /* end lk */      fflush(ficlog);
             } /* end lj */     
           } /* end li */      /*-------- Rewriting parameter file ----------*/
           if(mle>=1)      strcpy(rfileres,"r");    /* "Rparameterfile */
             printf("\n");      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
           fprintf(ficlog,"\n");      strcat(rfileres,".");    /* */
           fprintf(ficres,"\n");      strcat(rfileres,optionfilext);    /* Other files have txt extension */
           numlinepar++;      if((ficres =fopen(rfileres,"w"))==NULL) {
         } /* end k*/        printf("Problem writing new parameter file: %s\n", fileres);goto end;
       } /*end j */        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
     } /* end i */      }
   } /* end itimes */      fprintf(ficres,"#%s\n",version);
     }    /* End of mle != -3 */
   fflush(ficlog);  
   fflush(ficres);    /*-------- data file ----------*/
     if((fic=fopen(datafile,"r"))==NULL)    {
   while((c=getc(ficpar))=='#' && c!= EOF){      printf("Problem while opening datafile: %s\n", datafile);goto end;
     ungetc(c,ficpar);      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
     fgets(line, MAXLINE, ficpar);    }
     puts(line);  
     fputs(line,ficparo);    n= lastobs;
   }    severity = vector(1,maxwav);
   ungetc(c,ficpar);    outcome=imatrix(1,maxwav+1,1,n);
     num=lvector(1,n);
   estepm=0;    moisnais=vector(1,n);
   fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);    annais=vector(1,n);
   if (estepm==0 || estepm < stepm) estepm=stepm;    moisdc=vector(1,n);
   if (fage <= 2) {    andc=vector(1,n);
     bage = ageminpar;    agedc=vector(1,n);
     fage = agemaxpar;    cod=ivector(1,n);
   }    weight=vector(1,n);
        for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
   fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");    mint=matrix(1,maxwav,1,n);
   fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);    anint=matrix(1,maxwav,1,n);
   fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);    s=imatrix(1,maxwav+1,1,n);
        tab=ivector(1,NCOVMAX);
   while((c=getc(ficpar))=='#' && c!= EOF){    ncodemax=ivector(1,8);
     ungetc(c,ficpar);  
     fgets(line, MAXLINE, ficpar);    i=1;
     puts(line);    linei=0;
     fputs(line,ficparo);    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
   }      linei=linei+1;
   ungetc(c,ficpar);      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
           if(line[j] == '\t')
   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);          line[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);      }
   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);      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
   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);      };
          line[j+1]=0;  /* Trims blanks at end of line */
   while((c=getc(ficpar))=='#' && c!= EOF){      if(line[0]=='#'){
     ungetc(c,ficpar);        fprintf(ficlog,"Comment line\n%s\n",line);
     fgets(line, MAXLINE, ficpar);        printf("Comment line\n%s\n",line);
     puts(line);        continue;
     fputs(line,ficparo);      }
   }  
   ungetc(c,ficpar);      for (j=maxwav;j>=1;j--){
          cutv(stra, strb,line,' ');
         errno=0;
   dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;        lval=strtol(strb,&endptr,10);
   dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
         if( strb[0]=='\0' || (*endptr != '\0')){
   fscanf(ficpar,"pop_based=%d\n",&popbased);          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);
   fprintf(ficparo,"pop_based=%d\n",popbased);             exit(1);
   fprintf(ficres,"pop_based=%d\n",popbased);           }
           s[j][i]=lval;
   while((c=getc(ficpar))=='#' && c!= EOF){       
     ungetc(c,ficpar);        strcpy(line,stra);
     fgets(line, MAXLINE, ficpar);        cutv(stra, strb,line,' ');
     puts(line);        if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     fputs(line,ficparo);        }
   }        else  if(iout=sscanf(strb,"%s.") != 0){
   ungetc(c,ficpar);          month=99;
           year=9999;
   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);        }else{
   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("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);
   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);          exit(1);
   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);        anint[j][i]= (double) year;
   /* day and month of proj2 are not used but only year anproj2.*/        mint[j][i]= (double)month;
         strcpy(line,stra);
   while((c=getc(ficpar))=='#' && c!= EOF){      } /* ENd Waves */
     ungetc(c,ficpar);     
     fgets(line, MAXLINE, ficpar);      cutv(stra, strb,line,' ');
     puts(line);      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     fputs(line,ficparo);      }
   }      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
   ungetc(c,ficpar);        month=99;
         year=9999;
   fscanf(ficpar,"popforecast=%d popfile=%s popfiledate=%lf/%lf/%lf last-popfiledate=%lf/%lf/%lf\n",&popforecast,popfile,&jpyram,&mpyram,&anpyram,&jpyram1,&mpyram1,&anpyram1);      }else{
   fprintf(ficparo,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);        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);
   fprintf(ficres,"popforecast=%d popfile=%s popfiledate=%.lf/%.lf/%.lf last-popfiledate=%.lf/%.lf/%.lf\n",popforecast,popfile,jpyram,mpyram,anpyram,jpyram1,mpyram1,anpyram1);        exit(1);
       }
   /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/      andc[i]=(double) year;
   /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/      moisdc[i]=(double) month;
       strcpy(line,stra);
   replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */     
   printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);      cutv(stra, strb,line,' ');
       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
   printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\      }
                model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\      else  if(iout=sscanf(strb,"%s.") != 0){
                jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);        month=99;
          year=9999;
   /*------------ free_vector  -------------*/      }else{
   /*  chdir(path); */        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);
   free_ivector(wav,1,imx);      }
   free_imatrix(dh,1,lastpass-firstpass+1,1,imx);      annais[i]=(double)(year);
   free_imatrix(bh,1,lastpass-firstpass+1,1,imx);      moisnais[i]=(double)(month);
   free_imatrix(mw,1,lastpass-firstpass+1,1,imx);         strcpy(line,stra);
   free_lvector(num,1,n);     
   free_vector(agedc,1,n);      cutv(stra, strb,line,' ');
   /*free_matrix(covar,0,NCOVMAX,1,n);*/      errno=0;
   /*free_matrix(covar,1,NCOVMAX,1,n);*/      dval=strtod(strb,&endptr);
   fclose(ficparo);      if( strb[0]=='\0' || (*endptr != '\0')){
   fclose(ficres);        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);
       }
   /*--------------- Prevalence limit  (stable prevalence) --------------*/      weight[i]=dval;
         strcpy(line,stra);
   strcpy(filerespl,"pl");     
   strcat(filerespl,fileres);      for (j=ncovcol;j>=1;j--){
   if((ficrespl=fopen(filerespl,"w"))==NULL) {        cutv(stra, strb,line,' ');
     printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;        errno=0;
     fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;        lval=strtol(strb,&endptr,10);
   }        if( strb[0]=='\0' || (*endptr != '\0')){
   printf("Computing stable prevalence: result on file '%s' \n", filerespl);          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 stable prevalence: result on file '%s' \n", filerespl);          exit(1);
   fprintf(ficrespl,"#Stable prevalence \n");        }
   fprintf(ficrespl,"#Age ");        if(lval <-1 || lval >1){
   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);          printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
   fprintf(ficrespl,"\n");   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
      for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
   prlim=matrix(1,nlstate,1,nlstate);   For example, for multinomial values like 1, 2 and 3,\n \
    build V1=0 V2=0 for the reference value (1),\n \
   agebase=ageminpar;          V1=1 V2=0 for (2) \n \
   agelim=agemaxpar;   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
   ftolpl=1.e-10;   output of IMaCh is often meaningless.\n \
   i1=cptcoveff;   Exiting.\n",lval,linei, i,line,j);
   if (cptcovn < 1){i1=1;}          exit(1);
         }
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){        covar[j][i]=(double)(lval);
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){        strcpy(line,stra);
       k=k+1;      }
       /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/      lstra=strlen(stra);
       fprintf(ficrespl,"\n#******");     
       printf("\n#******");      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
       fprintf(ficlog,"\n#******");        stratrunc = &(stra[lstra-9]);
       for(j=1;j<=cptcoveff;j++) {        num[i]=atol(stratrunc);
         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]]);      else
         fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        num[i]=atol(stra);
       }      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
       fprintf(ficrespl,"******\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])); ij=ij+1;}*/
       printf("******\n");     
       fprintf(ficlog,"******\n");      i=i+1;
             } /* End loop reading  data */
       for (age=agebase; age<=agelim; age++){    fclose(fic);
         prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);    /* printf("ii=%d", ij);
         fprintf(ficrespl,"%.0f ",age );       scanf("%d",i);*/
         for(j=1;j<=cptcoveff;j++)    imx=i-1; /* Number of individuals */
           fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
         for(i=1; i<=nlstate;i++)    /* for (i=1; i<=imx; i++){
           fprintf(ficrespl," %.5f", prlim[i][i]);      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
         fprintf(ficrespl,"\n");      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;
     }      }*/
   }     /*  for (i=1; i<=imx; i++){
   fclose(ficrespl);       if (s[4][i]==9)  s[4][i]=-1;
        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]));}*/
   /*------------- h Pij x at various ages ------------*/   
       /* for (i=1; i<=imx; i++) */
   strcpy(filerespij,"pij");  strcat(filerespij,fileres);   
   if((ficrespij=fopen(filerespij,"w"))==NULL) {     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
     printf("Problem with Pij resultfile: %s\n", filerespij);goto end;       else weight[i]=1;*/
     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;  
   }    /* Calculation of the number of parameters from char model */
   printf("Computing pij: result on file '%s' \n", filerespij);    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);    Tprod=ivector(1,15);
       Tvaraff=ivector(1,15);
   stepsize=(int) (stepm+YEARM-1)/YEARM;    Tvard=imatrix(1,15,1,2);
   /*if (stepm<=24) stepsize=2;*/    Tage=ivector(1,15);      
      
   agelim=AGESUP;    if (strlen(model) >1){ /* If there is at least 1 covariate */
   hstepm=stepsize*YEARM; /* Every year of age */      j=0, j1=0, k1=1, k2=1;
   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */       j=nbocc(model,'+'); /* j=Number of '+' */
       j1=nbocc(model,'*'); /* j1=Number of '*' */
   /* hstepm=1;   aff par mois*/      cptcovn=j+1;
       cptcovprod=j1; /*Number of products */
   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++){      strcpy(modelsav,model);
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
       k=k+1;        printf("Error. Non available option model=%s ",model);
       fprintf(ficrespij,"\n#****** ");        fprintf(ficlog,"Error. Non available option model=%s ",model);
       for(j=1;j<=cptcoveff;j++)         goto end;
         fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      }
       fprintf(ficrespij,"******\n");     
               /* This loop fills the array Tvar from the string 'model'.*/
       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */  
         nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */       for(i=(j+1); i>=1;i--){
         nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
         if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
         /*        nhstepm=nhstepm*YEARM; aff par mois*/        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
         /*scanf("%d",i);*/
         p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        if (strchr(strb,'*')) {  /* Model includes a product */
         oldm=oldms;savm=savms;          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
         hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);            if (strcmp(strc,"age")==0) { /* Vn*age */
         fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");            cptcovprod--;
         for(i=1; i<=nlstate;i++)            cutv(strb,stre,strd,'V');
           for(j=1; j<=nlstate+ndeath;j++)            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
             fprintf(ficrespij," %1d-%1d",i,j);            cptcovage++;
         fprintf(ficrespij,"\n");              Tage[cptcovage]=i;
         for (h=0; h<=nhstepm; h++){              /*printf("stre=%s ", stre);*/
           fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );          }
           for(i=1; i<=nlstate;i++)          else if (strcmp(strd,"age")==0) { /* or age*Vn */
             for(j=1; j<=nlstate+ndeath;j++)            cptcovprod--;
               fprintf(ficrespij," %.5f", p3mat[i][j][h]);            cutv(strb,stre,strc,'V');
           fprintf(ficrespij,"\n");            Tvar[i]=atoi(stre);
         }            cptcovage++;
         free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            Tage[cptcovage]=i;
         fprintf(ficrespij,"\n");          }
       }          else {  /* Age is not in the model */
     }            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
   }            Tvar[i]=ncovcol+k1;
             cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
   varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax);            Tprod[k1]=i;
             Tvard[k1][1]=atoi(strc); /* m*/
   fclose(ficrespij);            Tvard[k1][2]=atoi(stre); /* n */
             Tvar[cptcovn+k2]=Tvard[k1][1];
   probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);            Tvar[cptcovn+k2+1]=Tvard[k1][2];
             for (k=1; k<=lastobs;k++)
   /*---------- Forecasting ------------------*/              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
   /*if((stepm == 1) && (strcmp(model,".")==0)){*/            k1++;
   if(prevfcast==1){            k2=k2+2;
     /*    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 { /* no more sum */
 /*      }  */          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 /*      else{ */         /*  scanf("%d",i);*/
 /*        erreur=108; */        cutv(strd,strc,strb,'V');
 /*        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); */        Tvar[i]=atoi(strc);
 /*        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,stra);  
   }        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
             scanf("%d",i);*/
       } /* end of loop + */
   /*---------- Health expectancies and variances ------------*/    } /* end model */
    
   strcpy(filerest,"t");    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
   strcat(filerest,fileres);      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
   if((ficrest=fopen(filerest,"w"))==NULL) {  
     printf("Problem with total LE resultfile: %s\n", filerest);goto end;    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
     fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;    printf("cptcovprod=%d ", cptcovprod);
   }    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
   printf("Computing Total LEs with variances: file '%s' \n", filerest);   
   fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest);     scanf("%d ",i);*/
   
       /*  if(mle==1){*/
   strcpy(filerese,"e");    if (weightopt != 1) { /* Maximisation without weights*/
   strcat(filerese,fileres);      for(i=1;i<=n;i++) weight[i]=1.0;
   if((ficreseij=fopen(filerese,"w"))==NULL) {    }
     printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);      /*-calculation of age at interview from date of interview and age at death -*/
     fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);    agev=matrix(1,maxwav,1,imx);
   }  
   printf("Computing Health Expectancies: result on file '%s' \n", filerese);    for (i=1; i<=imx; i++) {
   fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);      for(m=2; (m<= maxwav); m++) {
         if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
   strcpy(fileresv,"v");          anint[m][i]=9999;
   strcat(fileresv,fileres);          s[m][i]=-1;
   if((ficresvij=fopen(fileresv,"w"))==NULL) {        }
     printf("Problem with variance resultfile: %s\n", fileresv);exit(0);        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
     fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);          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);
   printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);          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);
   fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);          s[m][i]=-1;
         }
   /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
   prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);          nberr++;
   /*  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",\          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]);
 ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);          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 */
         }
   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);    for (i=1; i<=imx; i++)  {
       printf(" Error in movingaverage mobilav=%d\n",mobilav);      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
     }      for(m=firstpass; (m<= lastpass); m++){
   }        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
           if (s[m][i] >= nlstate+1) {
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){            if(agedc[i]>0)
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
       k=k+1;                 agev[m][i]=agedc[i];
       fprintf(ficrest,"\n#****** ");            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
       for(j=1;j<=cptcoveff;j++)               else {
         fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);                if ((int)andc[i]!=9999){
       fprintf(ficrest,"******\n");                  nbwarn++;
                   printf("Warning negative age at death: %ld line:%d\n",num[i],i);
       fprintf(ficreseij,"\n#****** ");                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
       for(j=1;j<=cptcoveff;j++)                   agev[m][i]=-1;
         fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);                }
       fprintf(ficreseij,"******\n");              }
           }
       fprintf(ficresvij,"\n#****** ");          else if(s[m][i] !=9){ /* Standard case, age in fractional
       for(j=1;j<=cptcoveff;j++)                                    years but with the precision of a month */
         fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
       fprintf(ficresvij,"******\n");            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
               agev[m][i]=1;
       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);            else if(agev[m][i] <agemin){
       oldm=oldms;savm=savms;              agemin=agev[m][i];
       evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov);                /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
              }
       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);            else if(agev[m][i] >agemax){
       oldm=oldms;savm=savms;              agemax=agev[m][i];
       varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav);              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
       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);            /*agev[m][i]=anint[m][i]-annais[i];*/
       }            /*     agev[m][i] = age[i]+2*m;*/
           }
            else { /* =9 */
       fprintf(ficrest,"#Total LEs with variances: e.. (std) ");            agev[m][i]=1;
       for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);            s[m][i]=-1;
       fprintf(ficrest,"\n");          }
         }
       epj=vector(1,nlstate+1);        else /*= 0 Unknown */
       for(age=bage; age <=fage ;age++){          agev[m][i]=1;
         prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      }
         if (popbased==1) {     
           if(mobilav ==0){    }
             for(i=1; i<=nlstate;i++)    for (i=1; i<=imx; i++)  {
               prlim[i][i]=probs[(int)age][i][k];      for(m=firstpass; (m<=lastpass); m++){
           }else{ /* mobilav */         if (s[m][i] > (nlstate+ndeath)) {
             for(i=1; i<=nlstate;i++)          nberr++;
               prlim[i][i]=mobaverage[(int)age][i][k];          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(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;
                 }
         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];    /*for (i=1; i<=imx; i++){
             /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/    for (m=firstpass; (m<lastpass); m++){
           }       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
           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];    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
         fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
         for(j=1;j <=nlstate;j++){  
           fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));    agegomp=(int)agemin;
         }    free_vector(severity,1,maxwav);
         fprintf(ficrest,"\n");    free_imatrix(outcome,1,maxwav+1,1,n);
       }    free_vector(moisnais,1,n);
       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);    free_vector(annais,1,n);
       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);    /* free_matrix(mint,1,maxwav,1,n);
       free_vector(epj,1,nlstate+1);       free_matrix(anint,1,maxwav,1,n);*/
     }    free_vector(moisdc,1,n);
   }    free_vector(andc,1,n);
   free_vector(weight,1,n);  
   free_imatrix(Tvard,1,15,1,2);     
   free_imatrix(s,1,maxwav+1,1,n);    wav=ivector(1,imx);
   free_matrix(anint,1,maxwav,1,n);     dh=imatrix(1,lastpass-firstpass+1,1,imx);
   free_matrix(mint,1,maxwav,1,n);    bh=imatrix(1,lastpass-firstpass+1,1,imx);
   free_ivector(cod,1,n);    mw=imatrix(1,lastpass-firstpass+1,1,imx);
   free_ivector(tab,1,NCOVMAX);     
   fclose(ficreseij);    /* Concatenates waves */
   fclose(ficresvij);    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
   fclose(ficrest);  
   fclose(ficpar);    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
     
   /*------- Variance of stable prevalence------*/       Tcode=ivector(1,100);
     nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
   strcpy(fileresvpl,"vpl");    ncodemax[1]=1;
   strcat(fileresvpl,fileres);    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
   if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {       
     printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
     exit(0);                                   the estimations*/
   }    h=0;
   printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);    m=pow(2,cptcoveff);
    
   for(cptcov=1,k=0;cptcov<=i1;cptcov++){    for(k=1;k<=cptcoveff; k++){
     for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      for(i=1; i <=(m/pow(2,k));i++){
       k=k+1;        for(j=1; j <= ncodemax[k]; j++){
       fprintf(ficresvpl,"\n#****** ");          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
       for(j=1;j<=cptcoveff;j++)             h++;
         fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
       fprintf(ficresvpl,"******\n");            /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
                 }
       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);    }
       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
     }       codtab[1][2]=1;codtab[2][2]=2; */
   }    /* for(i=1; i <=m ;i++){
        for(k=1; k <=cptcovn; k++){
   fclose(ficresvpl);       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
        }
   /*---------- End : free ----------------*/       printf("\n");
   free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);       }
   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);       scanf("%d",i);*/
   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);     
   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);    /*------------ gnuplot -------------*/
       strcpy(optionfilegnuplot,optionfilefiname);
   free_matrix(covar,0,NCOVMAX,1,n);    if(mle==-3)
   free_matrix(matcov,1,npar,1,npar);      strcat(optionfilegnuplot,"-mort");
   /*free_vector(delti,1,npar);*/    strcat(optionfilegnuplot,".gp");
   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);   
   free_matrix(agev,1,maxwav,1,imx);    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);      printf("Problem with file %s",optionfilegnuplot);
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    }
   free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);    else{
       fprintf(ficgp,"\n# %s\n", version);
   free_ivector(ncodemax,1,8);      fprintf(ficgp,"# %s\n", optionfilegnuplot);
   free_ivector(Tvar,1,15);      fprintf(ficgp,"set missing 'NaNq'\n");
   free_ivector(Tprod,1,15);    }
   free_ivector(Tvaraff,1,15);    /*  fclose(ficgp);*/
   free_ivector(Tage,1,15);    /*--------- index.htm --------*/
   free_ivector(Tcode,1,100);  
     strcpy(optionfilehtm,optionfilefiname); /* Main html file */
   fflush(fichtm);    if(mle==-3)
   fflush(ficgp);      strcat(optionfilehtm,"-mort");
       strcat(optionfilehtm,".htm");
     if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
   if((nberr >0) || (nbwarn>0)){      printf("Problem with %s \n",optionfilehtm), exit(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{    strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
     printf("End of Imach\n");    strcat(optionfilehtmcov,"-cov.htm");
     fprintf(ficlog,"End of Imach\n");    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
   }      printf("Problem with %s \n",optionfilehtmcov), exit(0);
   printf("See log file on %s\n",filelog);    }
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */    else{
   (void) gettimeofday(&end_time,&tzp);    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
   tm = *localtime(&end_time.tv_sec);  <hr size=\"2\" color=\"#EC5E5E\"> \n\
   tmg = *gmtime(&end_time.tv_sec);  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
   strcpy(strtend,asctime(&tm));            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
   printf("Local time at start %s\nLocaltime 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));    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\
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));  \n\
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);  <hr  size=\"2\" color=\"#EC5E5E\">\
   /*  printf("Total time was %d uSec.\n", total_usecs);*/   <ul><li><h4>Parameter files</h4>\n\
 /*   if(fileappend(fichtm,optionfilehtm)){ */   - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);   - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
   fclose(fichtm);   - Log file of the run: <a href=\"%s\">%s</a><br>\n\
   fclose(fichtmcov);   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
   fclose(ficgp);   - Date and time at start: %s</ul>\n",\
   fclose(ficlog);            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
   /*------ End -----------*/            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
             fileres,fileres,\
   chdir(path);            filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
   strcpy(plotcmd,GNUPLOTPROGRAM);    fflush(fichtm);
   strcat(plotcmd," ");  
   strcat(plotcmd,optionfilegnuplot);    strcpy(pathr,path);
   printf("Starting graphs with: %s",plotcmd);fflush(stdout);    strcat(pathr,optionfilefiname);
   if((outcmd=system(plotcmd)) != 0){    chdir(optionfilefiname); /* Move to directory named optionfile */
     printf(" Problem with gnuplot\n");   
   }    /* Calculates basic frequencies. Computes observed prevalence at single age
   printf(" Wait...");       and prints on file fileres'p'. */
   while (z[0] != 'q') {    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
     /* chdir(path); */  
     printf("\nType e to edit output files, g to graph again and q for exiting: ");    fprintf(fichtm,"\n");
     scanf("%s",z);    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 /*     if (z[0] == 'c') system("./imach"); */  Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
     if (z[0] == 'e') system(optionfilehtm);  Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
     else if (z[0] == 'g') system(plotcmd);            imx,agemin,agemax,jmin,jmax,jmean);
     else if (z[0] == 'q') exit(0);    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
   }      oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
   end:      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
   while (z[0] != 'q') {      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     printf("\nType  q for exiting: ");      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
     scanf("%s",z);     
   }     
 }    /* 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.95  
changed lines
  Added in v.1.125


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