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

version 1.99, 2004/06/05 08:57:40 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.99  2004/06/05 08:57:40  brouard    Revision 1.125  2006/04/04 15:20:31  lievre
   *** empty log message ***    Errors in calculation of health expectancies. Age was not initialized.
     Forecasting file added.
   Revision 1.98  2004/05/16 15:05:56  brouard  
   New version 0.97 . First attempt to estimate force of mortality    Revision 1.124  2006/03/22 17:13:53  lievre
   directly from the data i.e. without the need of knowing the health    Parameters are printed with %lf instead of %f (more numbers after the comma).
   state at each age, but using a Gompertz model: log u =a + b*age .    The log-likelihood is printed in the log file
   This is the basic analysis of mortality and should be done before any  
   other analysis, in order to test if the mortality estimated from the    Revision 1.123  2006/03/20 10:52:43  brouard
   cross-longitudinal survey is different from the mortality estimated    * imach.c (Module): <title> changed, corresponds to .htm file
   from other sources like vital statistic data.    name. <head> headers where missing.
   
   The same imach parameter file can be used but the option for mle should be -3.    * imach.c (Module): Weights can have a decimal point as for
     English (a comma might work with a correct LC_NUMERIC environment,
   Agnès, who wrote this part of the code, tried to keep most of the    otherwise the weight is truncated).
   former routines in order to include the new code within the former code.    Modification of warning when the covariates values are not 0 or
     1.
   The output is very simple: only an estimate of the intercept and of    Version 0.98g
   the slope with 95% confident intervals.  
     Revision 1.122  2006/03/20 09:45:41  brouard
   Current limitations:    (Module): Weights can have a decimal point as for
   A) Even if you enter covariates, i.e. with the    English (a comma might work with a correct LC_NUMERIC environment,
   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.    otherwise the weight is truncated).
   B) There is no computation of Life Expectancy nor Life Table.    Modification of warning when the covariates values are not 0 or
     1.
   Revision 1.97  2004/02/20 13:25:42  lievre    Version 0.98g
   Version 0.96d. Population forecasting command line is (temporarily)  
   suppressed.    Revision 1.121  2006/03/16 17:45:01  lievre
     * imach.c (Module): Comments concerning covariates added
   Revision 1.96  2003/07/15 15:38:55  brouard  
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is    * imach.c (Module): refinements in the computation of lli if
   rewritten within the same printf. Workaround: many printfs.    status=-2 in order to have more reliable computation if stepm is
     not 1 month. Version 0.98f
   Revision 1.95  2003/07/08 07:54:34  brouard  
   * imach.c (Repository):    Revision 1.120  2006/03/16 15:10:38  lievre
   (Repository): Using imachwizard code to output a more meaningful covariance    (Module): refinements in the computation of lli if
   matrix (cov(a12,c31) instead of numbers.    status=-2 in order to have more reliable computation if stepm is
     not 1 month. Version 0.98f
   Revision 1.94  2003/06/27 13:00:02  brouard  
   Just cleaning    Revision 1.119  2006/03/15 17:42:26  brouard
     (Module): Bug if status = -2, the loglikelihood was
   Revision 1.93  2003/06/25 16:33:55  brouard    computed as likelihood omitting the logarithm. Version O.98e
   (Module): On windows (cygwin) function asctime_r doesn't  
   exist so I changed back to asctime which exists.    Revision 1.118  2006/03/14 18:20:07  brouard
   (Module): Version 0.96b    (Module): varevsij Comments added explaining the second
     table of variances if popbased=1 .
   Revision 1.92  2003/06/25 16:30:45  brouard    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   (Module): On windows (cygwin) function asctime_r doesn't    (Module): Function pstamp added
   exist so I changed back to asctime which exists.    (Module): Version 0.98d
   
   Revision 1.91  2003/06/25 15:30:29  brouard    Revision 1.117  2006/03/14 17:16:22  brouard
   * imach.c (Repository): Duplicated warning errors corrected.    (Module): varevsij Comments added explaining the second
   (Repository): Elapsed time after each iteration is now output. It    table of variances if popbased=1 .
   helps to forecast when convergence will be reached. Elapsed time    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   is stamped in powell.  We created a new html file for the graphs    (Module): Function pstamp added
   concerning matrix of covariance. It has extension -cov.htm.    (Module): Version 0.98d
   
   Revision 1.90  2003/06/24 12:34:15  brouard    Revision 1.116  2006/03/06 10:29:27  brouard
   (Module): Some bugs corrected for windows. Also, when    (Module): Variance-covariance wrong links and
   mle=-1 a template is output in file "or"mypar.txt with the design    varian-covariance of ej. is needed (Saito).
   of the covariance matrix to be input.  
     Revision 1.115  2006/02/27 12:17:45  brouard
   Revision 1.89  2003/06/24 12:30:52  brouard    (Module): One freematrix added in mlikeli! 0.98c
   (Module): Some bugs corrected for windows. Also, when  
   mle=-1 a template is output in file "or"mypar.txt with the design    Revision 1.114  2006/02/26 12:57:58  brouard
   of the covariance matrix to be input.    (Module): Some improvements in processing parameter
     filename with strsep.
   Revision 1.88  2003/06/23 17:54:56  brouard  
   * 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.    Revision 1.113  2006/02/24 14:20:24  brouard
     (Module): Memory leaks checks with valgrind and:
   Revision 1.87  2003/06/18 12:26:01  brouard    datafile was not closed, some imatrix were not freed and on matrix
   Version 0.96    allocation too.
   
   Revision 1.86  2003/06/17 20:04:08  brouard    Revision 1.112  2006/01/30 09:55:26  brouard
   (Module): Change position of html and gnuplot routines and added    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   routine fileappend.  
     Revision 1.111  2006/01/25 20:38:18  brouard
   Revision 1.85  2003/06/17 13:12:43  brouard    (Module): Lots of cleaning and bugs added (Gompertz)
   * imach.c (Repository): Check when date of death was earlier that    (Module): Comments can be added in data file. Missing date values
   current date of interview. It may happen when the death was just    can be a simple dot '.'.
   prior to the death. In this case, dh was negative and likelihood  
   was wrong (infinity). We still send an "Error" but patch by    Revision 1.110  2006/01/25 00:51:50  brouard
   assuming that the date of death was just one stepm after the    (Module): Lots of cleaning and bugs added (Gompertz)
   interview.  
   (Repository): Because some people have very long ID (first column)    Revision 1.109  2006/01/24 19:37:15  brouard
   we changed int to long in num[] and we added a new lvector for    (Module): Comments (lines starting with a #) are allowed in data.
   memory allocation. But we also truncated to 8 characters (left  
   truncation)    Revision 1.108  2006/01/19 18:05:42  lievre
   (Repository): No more line truncation errors.    Gnuplot problem appeared...
     To be fixed
   Revision 1.84  2003/06/13 21:44:43  brouard  
   * imach.c (Repository): Replace "freqsummary" at a correct    Revision 1.107  2006/01/19 16:20:37  brouard
   place. It differs from routine "prevalence" which may be called    Test existence of gnuplot in imach path
   many times. Probs is memory consuming and must be used with  
   parcimony.    Revision 1.106  2006/01/19 13:24:36  brouard
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    Some cleaning and links added in html output
   
   Revision 1.83  2003/06/10 13:39:11  lievre    Revision 1.105  2006/01/05 20:23:19  lievre
   *** empty log message ***    *** empty log message ***
   
   Revision 1.82  2003/06/05 15:57:20  brouard    Revision 1.104  2005/09/30 16:11:43  lievre
   Add log in  imach.c and  fullversion number is now printed.    (Module): sump fixed, loop imx fixed, and simplifications.
     (Module): If the status is missing at the last wave but we know
 */    that the person is alive, then we can code his/her status as -2
 /*    (instead of missing=-1 in earlier versions) and his/her
    Interpolated Markov Chain    contributions to the likelihood is 1 - Prob of dying from last
     health status (= 1-p13= p11+p12 in the easiest case of somebody in
   Short summary of the programme:    the healthy state at last known wave). Version is 0.98
     
   This program computes Healthy Life Expectancies from    Revision 1.103  2005/09/30 15:54:49  lievre
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    (Module): sump fixed, loop imx fixed, and simplifications.
   first survey ("cross") where individuals from different ages are  
   interviewed on their health status or degree of disability (in the    Revision 1.102  2004/09/15 17:31:30  brouard
   case of a health survey which is our main interest) -2- at least a    Add the possibility to read data file including tab characters.
   second wave of interviews ("longitudinal") which measure each change  
   (if any) in individual health status.  Health expectancies are    Revision 1.101  2004/09/15 10:38:38  brouard
   computed from the time spent in each health state according to a    Fix on curr_time
   model. More health states you consider, more time is necessary to reach the  
   Maximum Likelihood of the parameters involved in the model.  The    Revision 1.100  2004/07/12 18:29:06  brouard
   simplest model is the multinomial logistic model where pij is the    Add version for Mac OS X. Just define UNIX in Makefile
   probability to be observed in state j at the second wave  
   conditional to be observed in state i at the first wave. Therefore    Revision 1.99  2004/06/05 08:57:40  brouard
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    *** empty log message ***
   '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.98  2004/05/16 15:05:56  brouard
   where the markup *Covariates have to be included here again* invites    New version 0.97 . First attempt to estimate force of mortality
   you to do it.  More covariates you add, slower the    directly from the data i.e. without the need of knowing the health
   convergence.    state at each age, but using a Gompertz model: log u =a + b*age .
     This is the basic analysis of mortality and should be done before any
   The advantage of this computer programme, compared to a simple    other analysis, in order to test if the mortality estimated from the
   multinomial logistic model, is clear when the delay between waves is not    cross-longitudinal survey is different from the mortality estimated
   identical for each individual. Also, if a individual missed an    from other sources like vital statistic data.
   intermediate interview, the information is lost, but taken into  
   account using an interpolation or extrapolation.      The same imach parameter file can be used but the option for mle should be -3.
   
   hPijx is the probability to be observed in state i at age x+h    Agnès, who wrote this part of the code, tried to keep most of the
   conditional to the observed state i at age x. The delay 'h' can be    former routines in order to include the new code within the former code.
   split into an exact number (nh*stepm) of unobserved intermediate  
   states. This elementary transition (by month, quarter,    The output is very simple: only an estimate of the intercept and of
   semester or year) is modelled as a multinomial logistic.  The hPx    the slope with 95% confident intervals.
   matrix is simply the matrix product of nh*stepm elementary matrices  
   and the contribution of each individual to the likelihood is simply    Current limitations:
   hPijx.    A) Even if you enter covariates, i.e. with the
     model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   Also this programme outputs the covariance matrix of the parameters but also    B) There is no computation of Life Expectancy nor Life Table.
   of the life expectancies. It also computes the stable prevalence.   
       Revision 1.97  2004/02/20 13:25:42  lievre
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    Version 0.96d. Population forecasting command line is (temporarily)
            Institut national d'études démographiques, Paris.    suppressed.
   This software have been partly granted by Euro-REVES, a concerted action  
   from the European Union.    Revision 1.96  2003/07/15 15:38:55  brouard
   It is copyrighted identically to a GNU software product, ie programme and    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   software can be distributed freely for non commercial use. Latest version    rewritten within the same printf. Workaround: many printfs.
   can be accessed at http://euroreves.ined.fr/imach .  
     Revision 1.95  2003/07/08 07:54:34  brouard
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    * imach.c (Repository):
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    (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
   main    Just cleaning
   read parameterfile  
   read datafile    Revision 1.93  2003/06/25 16:33:55  brouard
   concatwav    (Module): On windows (cygwin) function asctime_r doesn't
   freqsummary    exist so I changed back to asctime which exists.
   if (mle >= 1)    (Module): Version 0.96b
     mlikeli  
   print results files    Revision 1.92  2003/06/25 16:30:45  brouard
   if mle==1     (Module): On windows (cygwin) function asctime_r doesn't
      computes hessian    exist so I changed back to asctime which exists.
   read end of parameter file: agemin, agemax, bage, fage, estepm  
       begin-prev-date,...    Revision 1.91  2003/06/25 15:30:29  brouard
   open gnuplot file    * imach.c (Repository): Duplicated warning errors corrected.
   open html file    (Repository): Elapsed time after each iteration is now output. It
   stable prevalence    helps to forecast when convergence will be reached. Elapsed time
    for age prevalim()    is stamped in powell.  We created a new html file for the graphs
   h Pij x    concerning matrix of covariance. It has extension -cov.htm.
   variance of p varprob  
   forecasting if prevfcast==1 prevforecast call prevalence()    Revision 1.90  2003/06/24 12:34:15  brouard
   health expectancies    (Module): Some bugs corrected for windows. Also, when
   Variance-covariance of DFLE    mle=-1 a template is output in file "or"mypar.txt with the design
   prevalence()    of the covariance matrix to be input.
    movingaverage()  
   varevsij()     Revision 1.89  2003/06/24 12:30:52  brouard
   if popbased==1 varevsij(,popbased)    (Module): Some bugs corrected for windows. Also, when
   total life expectancies    mle=-1 a template is output in file "or"mypar.txt with the design
   Variance of stable prevalence    of the covariance matrix to be input.
  end  
 */    Revision 1.88  2003/06/23 17:54:56  brouard
     * 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.
   
     Revision 1.87  2003/06/18 12:26:01  brouard
      Version 0.96
 #include <math.h>  
 #include <stdio.h>    Revision 1.86  2003/06/17 20:04:08  brouard
 #include <stdlib.h>    (Module): Change position of html and gnuplot routines and added
 #include <unistd.h>    routine fileappend.
   
 /* #include <sys/time.h> */    Revision 1.85  2003/06/17 13:12:43  brouard
 #include <time.h>    * imach.c (Repository): Check when date of death was earlier that
 #include "timeval.h"    current date of interview. It may happen when the death was just
     prior to the death. In this case, dh was negative and likelihood
 /* #include <libintl.h> */    was wrong (infinity). We still send an "Error" but patch by
 /* #define _(String) gettext (String) */    assuming that the date of death was just one stepm after the
     interview.
 #define MAXLINE 256    (Repository): Because some people have very long ID (first column)
 #define GNUPLOTPROGRAM "gnuplot"    we changed int to long in num[] and we added a new lvector for
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/    memory allocation. But we also truncated to 8 characters (left
 #define FILENAMELENGTH 132    truncation)
 /*#define DEBUG*/    (Repository): No more line truncation errors.
 /*#define windows*/  
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */    Revision 1.84  2003/06/13 21:44:43  brouard
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */    * imach.c (Repository): Replace "freqsummary" at a correct
     place. It differs from routine "prevalence" which may be called
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */    many times. Probs is memory consuming and must be used with
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */    parcimony.
     Version 0.95a3 (should output exactly the same maximization than 0.8a2)
 #define NINTERVMAX 8  
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */    Revision 1.83  2003/06/10 13:39:11  lievre
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */    *** empty log message ***
 #define NCOVMAX 8 /* Maximum number of covariates */  
 #define MAXN 20000    Revision 1.82  2003/06/05 15:57:20  brouard
 #define YEARM 12. /* Number of months per year */    Add log in  imach.c and  fullversion number is now printed.
 #define AGESUP 130  
 #define AGEBASE 40  */
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */  /*
 #ifdef unix     Interpolated Markov Chain
 #define DIRSEPARATOR '/'  
 #define ODIRSEPARATOR '\\'    Short summary of the programme:
 #else   
 #define DIRSEPARATOR '\\'    This program computes Healthy Life Expectancies from
 #define ODIRSEPARATOR '/'    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
 #endif    first survey ("cross") where individuals from different ages are
     interviewed on their health status or degree of disability (in the
 /* $Id$ */    case of a health survey which is our main interest) -2- at least a
 /* $State$ */    second wave of interviews ("longitudinal") which measure each change
     (if any) in individual health status.  Health expectancies are
 char version[]="Imach version 0.97b, May 2004, INED-EUROREVES ";    computed from the time spent in each health state according to a
 char fullversion[]="$Revision$ $Date$";     model. More health states you consider, more time is necessary to reach the
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */    Maximum Likelihood of the parameters involved in the model.  The
 int nvar;    simplest model is the multinomial logistic model where pij is the
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;    probability to be observed in state j at the second wave
 int npar=NPARMAX;    conditional to be observed in state i at the first wave. Therefore
 int nlstate=2; /* Number of live states */    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
 int ndeath=1; /* Number of dead states */    'age' is age and 'sex' is a covariate. If you want to have a more
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */    complex model than "constant and age", you should modify the program
 int popbased=0;    where the markup *Covariates have to be included here again* invites
     you to do it.  More covariates you add, slower the
 int *wav; /* Number of waves for this individuual 0 is possible */    convergence.
 int maxwav; /* Maxim number of waves */  
 int jmin, jmax; /* min, max spacing between 2 waves */    The advantage of this computer programme, compared to a simple
 int gipmx, gsw; /* Global variables on the number of contributions     multinomial logistic model, is clear when the delay between waves is not
                    to the likelihood and the sum of weights (done by funcone)*/    identical for each individual. Also, if a individual missed an
 int mle, weightopt;    intermediate interview, the information is lost, but taken into
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */    account using an interpolation or extrapolation.  
 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    hPijx is the probability to be observed in state i at age x+h
            * wave mi and wave mi+1 is not an exact multiple of stepm. */    conditional to the observed state i at age x. The delay 'h' can be
 double jmean; /* Mean space between 2 waves */    split into an exact number (nh*stepm) of unobserved intermediate
 double **oldm, **newm, **savm; /* Working pointers to matrices */    states. This elementary transition (by month, quarter,
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */    semester or year) is modelled as a multinomial logistic.  The hPx
 FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;    matrix is simply the matrix product of nh*stepm elementary matrices
 FILE *ficlog, *ficrespow;    and the contribution of each individual to the likelihood is simply
 int globpr; /* Global variable for printing or not */    hPijx.
 double fretone; /* Only one call to likelihood */  
 long ipmx; /* Number of contributions */    Also this programme outputs the covariance matrix of the parameters but also
 double sw; /* Sum of weights */    of the life expectancies. It also computes the period (stable) prevalence.
 char filerespow[FILENAMELENGTH];   
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 FILE *ficresilk;             Institut national d'études démographiques, Paris.
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;    This software have been partly granted by Euro-REVES, a concerted action
 FILE *ficresprobmorprev;    from the European Union.
 FILE *fichtm, *fichtmcov; /* Html File */    It is copyrighted identically to a GNU software product, ie programme and
 FILE *ficreseij;    software can be distributed freely for non commercial use. Latest version
 char filerese[FILENAMELENGTH];    can be accessed at http://euroreves.ined.fr/imach .
 FILE  *ficresvij;  
 char fileresv[FILENAMELENGTH];    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 FILE  *ficresvpl;    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 char fileresvpl[FILENAMELENGTH];   
 char title[MAXLINE];    **********************************************************************/
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];  /*
 char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH];    main
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];     read parameterfile
 char command[FILENAMELENGTH];    read datafile
 int  outcmd=0;    concatwav
     freqsummary
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];    if (mle >= 1)
       mlikeli
 char filelog[FILENAMELENGTH]; /* Log file */    print results files
 char filerest[FILENAMELENGTH];    if mle==1
 char fileregp[FILENAMELENGTH];       computes hessian
 char popfile[FILENAMELENGTH];    read end of parameter file: agemin, agemax, bage, fage, estepm
         begin-prev-date,...
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;    open gnuplot file
     open html file
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;    period (stable) prevalence
 struct timezone tzp;     for age prevalim()
 extern int gettimeofday();    h Pij x
 struct tm tmg, tm, tmf, *gmtime(), *localtime();    variance of p varprob
 long time_value;    forecasting if prevfcast==1 prevforecast call prevalence()
 extern long time();    health expectancies
 char strcurr[80], strfor[80];    Variance-covariance of DFLE
     prevalence()
 #define NR_END 1     movingaverage()
 #define FREE_ARG char*    varevsij()
 #define FTOL 1.0e-10    if popbased==1 varevsij(,popbased)
     total life expectancies
 #define NRANSI     Variance of period (stable) prevalence
 #define ITMAX 200    end
   */
 #define TOL 2.0e-4   
   
 #define CGOLD 0.3819660   
 #define ZEPS 1.0e-10    
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   #include <math.h>
   #include <stdio.h>
 #define GOLD 1.618034   #include <stdlib.h>
 #define GLIMIT 100.0   #include <string.h>
 #define TINY 1.0e-20   #include <unistd.h>
   
 static double maxarg1,maxarg2;  #include <limits.h>
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  #include <sys/types.h>
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  #include <sys/stat.h>
     #include <errno.h>
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  extern int errno;
 #define rint(a) floor(a+0.5)  
   /* #include <sys/time.h> */
 static double sqrarg;  #include <time.h>
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  #include "timeval.h"
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   
 int agegomp= AGEGOMP;  /* #include <libintl.h> */
   /* #define _(String) gettext (String) */
 int imx;   
 int stepm=1;  #define MAXLINE 256
 /* Stepm, step in month: minimum step interpolation*/  
   #define GNUPLOTPROGRAM "gnuplot"
 int estepm;  /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  #define FILENAMELENGTH 132
   
 int m,nb;  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 long *num;  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 double **pmmij, ***probs;  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
 double *ageexmed,*agecens;  
 double dateintmean=0;  #define NINTERVMAX 8
   #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 double *weight;  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 int **s; /* Status */  #define NCOVMAX 8 /* Maximum number of covariates */
 double *agedc, **covar, idx;  #define MAXN 20000
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  #define YEARM 12. /* Number of months per year */
   #define AGESUP 130
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  #define AGEBASE 40
 double ftolhess; /* Tolerance for computing hessian */  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
   #ifdef UNIX
 /**************** split *************************/  #define DIRSEPARATOR '/'
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  #define CHARSEPARATOR "/"
 {  #define ODIRSEPARATOR '\\'
   /* From a file name with full path (either Unix or Windows) we extract the directory (dirc)  #else
      the name of the file (name), its extension only (ext) and its first part of the name (finame)  #define DIRSEPARATOR '\\'
   */   #define CHARSEPARATOR "\\"
   char  *ss;                            /* pointer */  #define ODIRSEPARATOR '/'
   int   l1, l2;                         /* length counters */  #endif
   
   l1 = strlen(path );                   /* length of path */  /* $Id$ */
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  /* $State$ */
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  
   if ( ss == NULL ) {                   /* no directory, so use current */  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  char fullversion[]="$Revision$ $Date$";
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  char strstart[80];
     /* get current working directory */  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
     /*    extern  char* getcwd ( char *buf , int len);*/  int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  int nvar;
       return( GLOCK_ERROR_GETCWD );  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
     }  int npar=NPARMAX;
     strcpy( name, path );               /* we've got it */  int nlstate=2; /* Number of live states */
   } else {                              /* strip direcotry from path */  int ndeath=1; /* Number of dead states */
     ss++;                               /* after this, the filename */  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
     l2 = strlen( ss );                  /* length of filename */  int popbased=0;
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  
     strcpy( name, ss );         /* save file name */  int *wav; /* Number of waves for this individuual 0 is possible */
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  int maxwav; /* Maxim number of waves */
     dirc[l1-l2] = 0;                    /* add zero */  int jmin, jmax; /* min, max spacing between 2 waves */
   }  int ijmin, ijmax; /* Individuals having jmin and jmax */
   l1 = strlen( dirc );                  /* length of directory */  int gipmx, gsw; /* Global variables on the number of contributions
   /*#ifdef windows                     to the likelihood and the sum of weights (done by funcone)*/
   if ( dirc[l1-1] != '\\' ) { dirc[l1] = '\\'; dirc[l1+1] = 0; }  int mle, weightopt;
 #else  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
   if ( dirc[l1-1] != '/' ) { dirc[l1] = '/'; dirc[l1+1] = 0; }  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 #endif  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
   */             * wave mi and wave mi+1 is not an exact multiple of stepm. */
   ss = strrchr( name, '.' );            /* find last / */  double jmean; /* Mean space between 2 waves */
   if (ss >0){  double **oldm, **newm, **savm; /* Working pointers to matrices */
     ss++;  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
     strcpy(ext,ss);                     /* save extension */  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
     l1= strlen( name);  FILE *ficlog, *ficrespow;
     l2= strlen(ss)+1;  int globpr; /* Global variable for printing or not */
     strncpy( finame, name, l1-l2);  double fretone; /* Only one call to likelihood */
     finame[l1-l2]= 0;  long ipmx; /* Number of contributions */
   }  double sw; /* Sum of weights */
   return( 0 );                          /* we're done */  char filerespow[FILENAMELENGTH];
 }  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
   FILE *ficresilk;
   FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 /******************************************/  FILE *ficresprobmorprev;
   FILE *fichtm, *fichtmcov; /* Html File */
 void replace_back_to_slash(char *s, char*t)  FILE *ficreseij;
 {  char filerese[FILENAMELENGTH];
   int i;  FILE *ficresstdeij;
   int lg=0;  char fileresstde[FILENAMELENGTH];
   i=0;  FILE *ficrescveij;
   lg=strlen(t);  char filerescve[FILENAMELENGTH];
   for(i=0; i<= lg; i++) {  FILE  *ficresvij;
     (s[i] = t[i]);  char fileresv[FILENAMELENGTH];
     if (t[i]== '\\') s[i]='/';  FILE  *ficresvpl;
   }  char fileresvpl[FILENAMELENGTH];
 }  char title[MAXLINE];
   char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 int nbocc(char *s, char occ)  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 {  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
   int i,j=0;  char command[FILENAMELENGTH];
   int lg=20;  int  outcmd=0;
   i=0;  
   lg=strlen(s);  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
   for(i=0; i<= lg; i++) {  
   if  (s[i] == occ ) j++;  char filelog[FILENAMELENGTH]; /* Log file */
   }  char filerest[FILENAMELENGTH];
   return j;  char fileregp[FILENAMELENGTH];
 }  char popfile[FILENAMELENGTH];
   
 void cutv(char *u,char *v, char*t, char occ)  char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 {  
   /* cuts string t into u and v where u is ended by char occ excluding it  struct timeval start_time, end_time, curr_time, last_time, forecast_time;
      and v is after occ excluding it too : ex cutv(u,v,"abcdef2ghi2j",2)  struct timezone tzp;
      gives u="abcedf" and v="ghi2j" */  extern int gettimeofday();
   int i,lg,j,p=0;  struct tm tmg, tm, tmf, *gmtime(), *localtime();
   i=0;  long time_value;
   for(j=0; j<=strlen(t)-1; j++) {  extern long time();
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;  char strcurr[80], strfor[80];
   }  
   char *endptr;
   lg=strlen(t);  long lval;
   for(j=0; j<p; j++) {  double dval;
     (u[j] = t[j]);  
   }  #define NR_END 1
      u[p]='\0';  #define FREE_ARG char*
   #define FTOL 1.0e-10
    for(j=0; j<= lg; j++) {  
     if (j>=(p+1))(v[j-p-1] = t[j]);  #define NRANSI
   }  #define ITMAX 200
 }  
   #define TOL 2.0e-4
 /********************** nrerror ********************/  
   #define CGOLD 0.3819660
 void nrerror(char error_text[])  #define ZEPS 1.0e-10
 {  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
   fprintf(stderr,"ERREUR ...\n");  
   fprintf(stderr,"%s\n",error_text);  #define GOLD 1.618034
   exit(EXIT_FAILURE);  #define GLIMIT 100.0
 }  #define TINY 1.0e-20
 /*********************** vector *******************/  
 double *vector(int nl, int nh)  static double maxarg1,maxarg2;
 {  #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
   double *v;  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));   
   if (!v) nrerror("allocation failure in vector");  #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
   return v-nl+NR_END;  #define rint(a) floor(a+0.5)
 }  
   static double sqrarg;
 /************************ free vector ******************/  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 void free_vector(double*v, int nl, int nh)  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
 {  int agegomp= AGEGOMP;
   free((FREE_ARG)(v+nl-NR_END));  
 }  int imx;
   int stepm=1;
 /************************ivector *******************************/  /* Stepm, step in month: minimum step interpolation*/
 int *ivector(long nl,long nh)  
 {  int estepm;
   int *v;  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));  
   if (!v) nrerror("allocation failure in ivector");  int m,nb;
   return v-nl+NR_END;  long *num;
 }  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
   double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 /******************free ivector **************************/  double **pmmij, ***probs;
 void free_ivector(int *v, long nl, long nh)  double *ageexmed,*agecens;
 {  double dateintmean=0;
   free((FREE_ARG)(v+nl-NR_END));  
 }  double *weight;
   int **s; /* Status */
 /************************lvector *******************************/  double *agedc, **covar, idx;
 long *lvector(long nl,long nh)  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
 {  double *lsurv, *lpop, *tpop;
   long *v;  
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
   if (!v) nrerror("allocation failure in ivector");  double ftolhess; /* Tolerance for computing hessian */
   return v-nl+NR_END;  
 }  /**************** split *************************/
   static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
 /******************free lvector **************************/  {
 void free_lvector(long *v, long nl, long nh)    /* 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)
   free((FREE_ARG)(v+nl-NR_END));    */
 }    char  *ss;                            /* pointer */
     int   l1, l2;                         /* length counters */
 /******************* imatrix *******************************/  
 int **imatrix(long nrl, long nrh, long ncl, long nch)     l1 = strlen(path );                   /* length of path */
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */     if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 {     ss= strrchr( path, DIRSEPARATOR );            /* find last / */
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;     if ( ss == NULL ) {                   /* no directory, so determine current directory */
   int **m;       strcpy( name, path );               /* we got the fullname name because no directory */
         /*if(strrchr(path, ODIRSEPARATOR )==NULL)
   /* allocate pointers to rows */         printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));       /* get current working directory */
   if (!m) nrerror("allocation failure 1 in matrix()");       /*    extern  char* getcwd ( char *buf , int len);*/
   m += NR_END;       if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
   m -= nrl;         return( GLOCK_ERROR_GETCWD );
         }
         /* got dirc from getcwd*/
   /* allocate rows and set pointers to them */       printf(" DIRC = %s \n",dirc);
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));     } else {                              /* strip direcotry from path */
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");       ss++;                               /* after this, the filename */
   m[nrl] += NR_END;       l2 = strlen( ss );                  /* length of filename */
   m[nrl] -= ncl;       if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
         strcpy( name, ss );         /* save file name */
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;       strncpy( dirc, path, l1 - l2 );     /* now the directory */
         dirc[l1-l2] = 0;                    /* add zero */
   /* return pointer to array of pointers to rows */       printf(" DIRC2 = %s \n",dirc);
   return m;     }
 }     /* We add a separator at the end of dirc if not exists */
     l1 = strlen( dirc );                  /* length of directory */
 /****************** free_imatrix *************************/    if( dirc[l1-1] != DIRSEPARATOR ){
 void free_imatrix(m,nrl,nrh,ncl,nch)      dirc[l1] =  DIRSEPARATOR;
       int **m;      dirc[l1+1] = 0;
       long nch,ncl,nrh,nrl;       printf(" DIRC3 = %s \n",dirc);
      /* free an int matrix allocated by imatrix() */     }
 {     ss = strrchr( name, '.' );            /* find last / */
   free((FREE_ARG) (m[nrl]+ncl-NR_END));     if (ss >0){
   free((FREE_ARG) (m+nrl-NR_END));       ss++;
 }       strcpy(ext,ss);                     /* save extension */
       l1= strlen( name);
 /******************* matrix *******************************/      l2= strlen(ss)+1;
 double **matrix(long nrl, long nrh, long ncl, long nch)      strncpy( finame, name, l1-l2);
 {      finame[l1-l2]= 0;
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;    }
   double **m;  
     return( 0 );                          /* we're done */
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  }
   if (!m) nrerror("allocation failure 1 in matrix()");  
   m += NR_END;  
   m -= nrl;  /******************************************/
   
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  void replace_back_to_slash(char *s, char*t)
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  {
   m[nrl] += NR_END;    int i;
   m[nrl] -= ncl;    int lg=0;
     i=0;
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    lg=strlen(t);
   return m;    for(i=0; i<= lg; i++) {
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])       (s[i] = t[i]);
    */      if (t[i]== '\\') s[i]='/';
 }    }
   }
 /*************************free matrix ************************/  
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)  int nbocc(char *s, char occ)
 {  {
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    int i,j=0;
   free((FREE_ARG)(m+nrl-NR_END));    int lg=20;
 }    i=0;
     lg=strlen(s);
 /******************* ma3x *******************************/    for(i=0; i<= lg; i++) {
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)    if  (s[i] == occ ) j++;
 {    }
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;    return j;
   double ***m;  }
   
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  void cutv(char *u,char *v, char*t, char occ)
   if (!m) nrerror("allocation failure 1 in matrix()");  {
   m += NR_END;    /* cuts string t into u and v where u ends before first occurence of char 'occ'
   m -= nrl;       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
        gives u="abcedf" and v="ghi2j" */
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));    int i,lg,j,p=0;
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    i=0;
   m[nrl] += NR_END;    for(j=0; j<=strlen(t)-1; j++) {
   m[nrl] -= ncl;      if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
     }
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;  
     lg=strlen(t);
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));    for(j=0; j<p; j++) {
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");      (u[j] = t[j]);
   m[nrl][ncl] += NR_END;    }
   m[nrl][ncl] -= nll;       u[p]='\0';
   for (j=ncl+1; j<=nch; j++)   
     m[nrl][j]=m[nrl][j-1]+nlay;     for(j=0; j<= lg; j++) {
         if (j>=(p+1))(v[j-p-1] = t[j]);
   for (i=nrl+1; i<=nrh; i++) {    }
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;  }
     for (j=ncl+1; j<=nch; j++)   
       m[i][j]=m[i][j-1]+nlay;  /********************** nrerror ********************/
   }  
   return m;   void nrerror(char error_text[])
   /*  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)    fprintf(stderr,"ERREUR ...\n");
   */    fprintf(stderr,"%s\n",error_text);
 }    exit(EXIT_FAILURE);
   }
 /*************************free ma3x ************************/  /*********************** vector *******************/
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)  double *vector(int nl, int nh)
 {  {
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    double *v;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
   free((FREE_ARG)(m+nrl-NR_END));    if (!v) nrerror("allocation failure in vector");
 }    return v-nl+NR_END;
   }
 /*************** function subdirf ***********/  
 char *subdirf(char fileres[])  /************************ free vector ******************/
 {  void free_vector(double*v, int nl, int nh)
   /* Caution optionfilefiname is hidden */  {
   strcpy(tmpout,optionfilefiname);    free((FREE_ARG)(v+nl-NR_END));
   strcat(tmpout,"/"); /* Add to the right */  }
   strcat(tmpout,fileres);  
   return tmpout;  /************************ivector *******************************/
 }  int *ivector(long nl,long nh)
   {
 /*************** function subdirf2 ***********/    int *v;
 char *subdirf2(char fileres[], char *preop)    v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 {    if (!v) nrerror("allocation failure in ivector");
       return v-nl+NR_END;
   /* Caution optionfilefiname is hidden */  }
   strcpy(tmpout,optionfilefiname);  
   strcat(tmpout,"/");  /******************free ivector **************************/
   strcat(tmpout,preop);  void free_ivector(int *v, long nl, long nh)
   strcat(tmpout,fileres);  {
   return tmpout;    free((FREE_ARG)(v+nl-NR_END));
 }  }
   
 /*************** function subdirf3 ***********/  /************************lvector *******************************/
 char *subdirf3(char fileres[], char *preop, char *preop2)  long *lvector(long nl,long nh)
 {  {
       long *v;
   /* Caution optionfilefiname is hidden */    v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
   strcpy(tmpout,optionfilefiname);    if (!v) nrerror("allocation failure in ivector");
   strcat(tmpout,"/");    return v-nl+NR_END;
   strcat(tmpout,preop);  }
   strcat(tmpout,preop2);  
   strcat(tmpout,fileres);  /******************free lvector **************************/
   return tmpout;  void free_lvector(long *v, long nl, long nh)
 }  {
     free((FREE_ARG)(v+nl-NR_END));
 /***************** f1dim *************************/  }
 extern int ncom;   
 extern double *pcom,*xicom;  /******************* imatrix *******************************/
 extern double (*nrfunc)(double []);   int **imatrix(long nrl, long nrh, long ncl, long nch)
         /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
 double f1dim(double x)   {
 {     long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
   int j;     int **m;
   double f;   
   double *xt;     /* allocate pointers to rows */
      m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
   xt=vector(1,ncom);     if (!m) nrerror("allocation failure 1 in matrix()");
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];     m += NR_END;
   f=(*nrfunc)(xt);     m -= nrl;
   free_vector(xt,1,ncom);    
   return f;    
 }     /* allocate rows and set pointers to them */
     m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
 /*****************brent *************************/    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)     m[nrl] += NR_END;
 {     m[nrl] -= ncl;
   int iter;    
   double a,b,d,etemp;    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
   double fu,fv,fw,fx;   
   double ftemp;    /* return pointer to array of pointers to rows */
   double p,q,r,tol1,tol2,u,v,w,x,xm;     return m;
   double e=0.0;   }
    
   a=(ax < cx ? ax : cx);   /****************** free_imatrix *************************/
   b=(ax > cx ? ax : cx);   void free_imatrix(m,nrl,nrh,ncl,nch)
   x=w=v=bx;         int **m;
   fw=fv=fx=(*f)(x);         long nch,ncl,nrh,nrl;
   for (iter=1;iter<=ITMAX;iter++) {        /* free an int matrix allocated by imatrix() */
     xm=0.5*(a+b);   {
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     free((FREE_ARG) (m[nrl]+ncl-NR_END));
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/    free((FREE_ARG) (m+nrl-NR_END));
     printf(".");fflush(stdout);  }
     fprintf(ficlog,".");fflush(ficlog);  
 #ifdef DEBUG  /******************* matrix *******************************/
     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);  double **matrix(long nrl, long nrh, long ncl, long nch)
     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)))) { */    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 #endif    double **m;
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){   
       *xmin=x;     m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
       return fx;     if (!m) nrerror("allocation failure 1 in matrix()");
     }     m += NR_END;
     ftemp=fu;    m -= nrl;
     if (fabs(e) > tol1) {   
       r=(x-w)*(fx-fv);     m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
       q=(x-v)*(fx-fw);     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
       p=(x-v)*q-(x-w)*r;     m[nrl] += NR_END;
       q=2.0*(q-r);     m[nrl] -= ncl;
       if (q > 0.0) p = -p;   
       q=fabs(q);     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
       etemp=e;     return m;
       e=d;     /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))      */
         d=CGOLD*(e=(x >= xm ? a-x : b-x));   }
       else {   
         d=p/q;   /*************************free matrix ************************/
         u=x+d;   void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
         if (u-a < tol2 || b-u < tol2)   {
           d=SIGN(tol1,xm-x);     free((FREE_ARG)(m[nrl]+ncl-NR_END));
       }     free((FREE_ARG)(m+nrl-NR_END));
     } else {   }
       d=CGOLD*(e=(x >= xm ? a-x : b-x));   
     }   /******************* ma3x *******************************/
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));   double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
     fu=(*f)(u);   {
     if (fu <= fx) {     long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
       if (u >= x) a=x; else b=x;     double ***m;
       SHFT(v,w,x,u)   
         SHFT(fv,fw,fx,fu)     m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
         } else {     if (!m) nrerror("allocation failure 1 in matrix()");
           if (u < x) a=u; else b=u;     m += NR_END;
           if (fu <= fw || w == x) {     m -= nrl;
             v=w;   
             w=u;     m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
             fv=fw;     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
             fw=fu;     m[nrl] += NR_END;
           } else if (fu <= fv || v == x || v == w) {     m[nrl] -= ncl;
             v=u;   
             fv=fu;     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)));
   }     if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
   nrerror("Too many iterations in brent");     m[nrl][ncl] += NR_END;
   *xmin=x;     m[nrl][ncl] -= nll;
   return fx;     for (j=ncl+1; j<=nch; j++)
 }       m[nrl][j]=m[nrl][j-1]+nlay;
    
 /****************** mnbrak ***********************/    for (i=nrl+1; i<=nrh; i++) {
       m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,       for (j=ncl+1; j<=nch; j++)
             double (*func)(double))         m[i][j]=m[i][j-1]+nlay;
 {     }
   double ulim,u,r,q, dum;    return m;
   double fu;     /*  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)
   *fa=(*func)(*ax);     */
   *fb=(*func)(*bx);   }
   if (*fb > *fa) {   
     SHFT(dum,*ax,*bx,dum)   /*************************free ma3x ************************/
       SHFT(dum,*fb,*fa,dum)   void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
       }   {
   *cx=(*bx)+GOLD*(*bx-*ax);     free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
   *fc=(*func)(*cx);     free((FREE_ARG)(m[nrl]+ncl-NR_END));
   while (*fb > *fc) {     free((FREE_ARG)(m+nrl-NR_END));
     r=(*bx-*ax)*(*fb-*fc);   }
     q=(*bx-*cx)*(*fb-*fa);   
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/   /*************** function subdirf ***********/
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));   char *subdirf(char fileres[])
     ulim=(*bx)+GLIMIT*(*cx-*bx);   {
     if ((*bx-u)*(u-*cx) > 0.0) {     /* Caution optionfilefiname is hidden */
       fu=(*func)(u);     strcpy(tmpout,optionfilefiname);
     } else if ((*cx-u)*(u-ulim) > 0.0) {     strcat(tmpout,"/"); /* Add to the right */
       fu=(*func)(u);     strcat(tmpout,fileres);
       if (fu < *fc) {     return tmpout;
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))   }
           SHFT(*fb,*fc,fu,(*func)(u))   
           }   /*************** function subdirf2 ***********/
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {   char *subdirf2(char fileres[], char *preop)
       u=ulim;   {
       fu=(*func)(u);    
     } else {     /* Caution optionfilefiname is hidden */
       u=(*cx)+GOLD*(*cx-*bx);     strcpy(tmpout,optionfilefiname);
       fu=(*func)(u);     strcat(tmpout,"/");
     }     strcat(tmpout,preop);
     SHFT(*ax,*bx,*cx,u)     strcat(tmpout,fileres);
       SHFT(*fa,*fb,*fc,fu)     return tmpout;
       }   }
 }   
   /*************** function subdirf3 ***********/
 /*************** linmin ************************/  char *subdirf3(char fileres[], char *preop, char *preop2)
   {
 int ncom;    
 double *pcom,*xicom;    /* Caution optionfilefiname is hidden */
 double (*nrfunc)(double []);     strcpy(tmpout,optionfilefiname);
      strcat(tmpout,"/");
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))     strcat(tmpout,preop);
 {     strcat(tmpout,preop2);
   double brent(double ax, double bx, double cx,     strcat(tmpout,fileres);
                double (*f)(double), double tol, double *xmin);     return tmpout;
   double f1dim(double x);   }
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,   
               double *fc, double (*func)(double));   /***************** f1dim *************************/
   int j;   extern int ncom;
   double xx,xmin,bx,ax;   extern double *pcom,*xicom;
   double fx,fb,fa;  extern double (*nrfunc)(double []);
     
   ncom=n;   double f1dim(double x)
   pcom=vector(1,n);   {
   xicom=vector(1,n);     int j;
   nrfunc=func;     double f;
   for (j=1;j<=n;j++) {     double *xt;
     pcom[j]=p[j];    
     xicom[j]=xi[j];     xt=vector(1,ncom);
   }     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
   ax=0.0;     f=(*nrfunc)(xt);
   xx=1.0;     free_vector(xt,1,ncom);
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);     return f;
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);   }
 #ifdef DEBUG  
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  /*****************brent *************************/
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
 #endif  {
   for (j=1;j<=n;j++) {     int iter;
     xi[j] *= xmin;     double a,b,d,etemp;
     p[j] += xi[j];     double fu,fv,fw,fx;
   }     double ftemp;
   free_vector(xicom,1,n);     double p,q,r,tol1,tol2,u,v,w,x,xm;
   free_vector(pcom,1,n);     double e=0.0;
 }    
     a=(ax < cx ? ax : cx);
 char *asc_diff_time(long time_sec, char ascdiff[])    b=(ax > cx ? ax : cx);
 {    x=w=v=bx;
   long sec_left, days, hours, minutes;    fw=fv=fx=(*f)(x);
   days = (time_sec) / (60*60*24);    for (iter=1;iter<=ITMAX;iter++) {
   sec_left = (time_sec) % (60*60*24);      xm=0.5*(a+b);
   hours = (sec_left) / (60*60) ;      tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
   sec_left = (sec_left) %(60*60);      /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
   minutes = (sec_left) /60;      printf(".");fflush(stdout);
   sec_left = (sec_left) % (60);      fprintf(ficlog,".");fflush(ficlog);
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);    #ifdef DEBUG
   return ascdiff;      printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
 }      fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 /*************** powell ************************/  #endif
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
             double (*func)(double []))         *xmin=x;
 {         return fx;
   void linmin(double p[], double xi[], int n, double *fret,       }
               double (*func)(double []));       ftemp=fu;
   int i,ibig,j;       if (fabs(e) > tol1) {
   double del,t,*pt,*ptt,*xit;        r=(x-w)*(fx-fv);
   double fp,fptt;        q=(x-v)*(fx-fw);
   double *xits;        p=(x-v)*q-(x-w)*r;
   int niterf, itmp;        q=2.0*(q-r);
         if (q > 0.0) p = -p;
   pt=vector(1,n);         q=fabs(q);
   ptt=vector(1,n);         etemp=e;
   xit=vector(1,n);         e=d;
   xits=vector(1,n);         if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
   *fret=(*func)(p);           d=CGOLD*(e=(x >= xm ? a-x : b-x));
   for (j=1;j<=n;j++) pt[j]=p[j];         else {
   for (*iter=1;;++(*iter)) {           d=p/q;
     fp=(*fret);           u=x+d;
     ibig=0;           if (u-a < tol2 || b-u < tol2)
     del=0.0;             d=SIGN(tol1,xm-x);
     last_time=curr_time;        }
     (void) gettimeofday(&curr_time,&tzp);      } else {
     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);        d=CGOLD*(e=(x >= xm ? a-x : b-x));
     /*    fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);      }
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);      u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
     */      fu=(*f)(u);
    for (i=1;i<=n;i++) {      if (fu <= fx) {
       printf(" %d %.12f",i, p[i]);        if (u >= x) a=x; else b=x;
       fprintf(ficlog," %d %.12lf",i, p[i]);        SHFT(v,w,x,u)
       fprintf(ficrespow," %.12lf", p[i]);          SHFT(fv,fw,fx,fu)
     }          } else {
     printf("\n");            if (u < x) a=u; else b=u;
     fprintf(ficlog,"\n");            if (fu <= fw || w == x) {
     fprintf(ficrespow,"\n");fflush(ficrespow);              v=w;
     if(*iter <=3){              w=u;
       tm = *localtime(&curr_time.tv_sec);              fv=fw;
       strcpy(strcurr,asctime(&tmf));              fw=fu;
 /*       asctime_r(&tm,strcurr); */            } else if (fu <= fv || v == x || v == w) {
       forecast_time=curr_time;              v=u;
       itmp = strlen(strcurr);              fv=fu;
       if(strcurr[itmp-1]=='\n')            }
         strcurr[itmp-1]='\0';          }
       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);    nrerror("Too many iterations in brent");
       for(niterf=10;niterf<=30;niterf+=10){    *xmin=x;
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);    return fx;
         tmf = *localtime(&forecast_time.tv_sec);  }
 /*      asctime_r(&tmf,strfor); */  
         strcpy(strfor,asctime(&tmf));  /****************** mnbrak ***********************/
         itmp = strlen(strfor);  
         if(strfor[itmp-1]=='\n')  void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
         strfor[itmp-1]='\0';              double (*func)(double))
         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);  {
         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);    double ulim,u,r,q, dum;
       }    double fu;
     }   
     for (i=1;i<=n;i++) {     *fa=(*func)(*ax);
       for (j=1;j<=n;j++) xit[j]=xi[j][i];     *fb=(*func)(*bx);
       fptt=(*fret);     if (*fb > *fa) {
 #ifdef DEBUG      SHFT(dum,*ax,*bx,dum)
       printf("fret=%lf \n",*fret);        SHFT(dum,*fb,*fa,dum)
       fprintf(ficlog,"fret=%lf \n",*fret);        }
 #endif    *cx=(*bx)+GOLD*(*bx-*ax);
       printf("%d",i);fflush(stdout);    *fc=(*func)(*cx);
       fprintf(ficlog,"%d",i);fflush(ficlog);    while (*fb > *fc) {
       linmin(p,xit,n,fret,func);       r=(*bx-*ax)*(*fb-*fc);
       if (fabs(fptt-(*fret)) > del) {       q=(*bx-*cx)*(*fb-*fa);
         del=fabs(fptt-(*fret));       u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
         ibig=i;         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
       }       ulim=(*bx)+GLIMIT*(*cx-*bx);
 #ifdef DEBUG      if ((*bx-u)*(u-*cx) > 0.0) {
       printf("%d %.12e",i,(*fret));        fu=(*func)(u);
       fprintf(ficlog,"%d %.12e",i,(*fret));      } else if ((*cx-u)*(u-ulim) > 0.0) {
       for (j=1;j<=n;j++) {        fu=(*func)(u);
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);        if (fu < *fc) {
         printf(" x(%d)=%.12e",j,xit[j]);          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);            SHFT(*fb,*fc,fu,(*func)(u))
       }            }
       for(j=1;j<=n;j++) {      } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
         printf(" p=%.12e",p[j]);        u=ulim;
         fprintf(ficlog," p=%.12e",p[j]);        fu=(*func)(u);
       }      } else {
       printf("\n");        u=(*cx)+GOLD*(*cx-*bx);
       fprintf(ficlog,"\n");        fu=(*func)(u);
 #endif      }
     }       SHFT(*ax,*bx,*cx,u)
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {        SHFT(*fa,*fb,*fc,fu)
 #ifdef DEBUG        }
       int k[2],l;  }
       k[0]=1;  
       k[1]=-1;  /*************** linmin ************************/
       printf("Max: %.12e",(*func)(p));  
       fprintf(ficlog,"Max: %.12e",(*func)(p));  int ncom;
       for (j=1;j<=n;j++) {  double *pcom,*xicom;
         printf(" %.12e",p[j]);  double (*nrfunc)(double []);
         fprintf(ficlog," %.12e",p[j]);   
       }  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
       printf("\n");  {
       fprintf(ficlog,"\n");    double brent(double ax, double bx, double cx,
       for(l=0;l<=1;l++) {                 double (*f)(double), double tol, double *xmin);
         for (j=1;j<=n;j++) {    double f1dim(double x);
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);                double *fc, double (*func)(double));
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);    int j;
         }    double xx,xmin,bx,ax;
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));    double fx,fb,fa;
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));   
       }    ncom=n;
 #endif    pcom=vector(1,n);
     xicom=vector(1,n);
     nrfunc=func;
       free_vector(xit,1,n);     for (j=1;j<=n;j++) {
       free_vector(xits,1,n);       pcom[j]=p[j];
       free_vector(ptt,1,n);       xicom[j]=xi[j];
       free_vector(pt,1,n);     }
       return;     ax=0.0;
     }     xx=1.0;
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
     for (j=1;j<=n;j++) {     *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
       ptt[j]=2.0*p[j]-pt[j];   #ifdef DEBUG
       xit[j]=p[j]-pt[j];     printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
       pt[j]=p[j];     fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
     }   #endif
     fptt=(*func)(ptt);     for (j=1;j<=n;j++) {
     if (fptt < fp) {       xi[j] *= xmin;
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);       p[j] += xi[j];
       if (t < 0.0) {     }
         linmin(p,xit,n,fret,func);     free_vector(xicom,1,n);
         for (j=1;j<=n;j++) {     free_vector(pcom,1,n);
           xi[j][ibig]=xi[j][n];   }
           xi[j][n]=xit[j];   
         }  char *asc_diff_time(long time_sec, char ascdiff[])
 #ifdef DEBUG  {
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);    long sec_left, days, hours, minutes;
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);    days = (time_sec) / (60*60*24);
         for(j=1;j<=n;j++){    sec_left = (time_sec) % (60*60*24);
           printf(" %.12e",xit[j]);    hours = (sec_left) / (60*60) ;
           fprintf(ficlog," %.12e",xit[j]);    sec_left = (sec_left) %(60*60);
         }    minutes = (sec_left) /60;
         printf("\n");    sec_left = (sec_left) % (60);
         fprintf(ficlog,"\n");    sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
 #endif    return ascdiff;
       }  }
     }   
   }   /*************** powell ************************/
 }   void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
               double (*func)(double []))
 /**** Prevalence limit (stable prevalence)  ****************/  {
     void linmin(double p[], double xi[], int n, double *fret,
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)                double (*func)(double []));
 {    int i,ibig,j;
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit    double del,t,*pt,*ptt,*xit;
      matrix by transitions matrix until convergence is reached */    double fp,fptt;
     double *xits;
   int i, ii,j,k;    int niterf, itmp;
   double min, max, maxmin, maxmax,sumnew=0.;  
   double **matprod2();    pt=vector(1,n);
   double **out, cov[NCOVMAX], **pmij();    ptt=vector(1,n);
   double **newm;    xit=vector(1,n);
   double agefin, delaymax=50 ; /* Max number of years to converge */    xits=vector(1,n);
     *fret=(*func)(p);
   for (ii=1;ii<=nlstate+ndeath;ii++)    for (j=1;j<=n;j++) pt[j]=p[j];
     for (j=1;j<=nlstate+ndeath;j++){    for (*iter=1;;++(*iter)) {
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);      fp=(*fret);
     }      ibig=0;
       del=0.0;
    cov[1]=1.;      last_time=curr_time;
        (void) gettimeofday(&curr_time,&tzp);
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */      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);
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){      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);
     newm=savm;  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
     /* Covariates have to be included here again */     for (i=1;i<=n;i++) {
      cov[2]=agefin;        printf(" %d %.12f",i, p[i]);
           fprintf(ficlog," %d %.12lf",i, p[i]);
       for (k=1; k<=cptcovn;k++) {        fprintf(ficrespow," %.12lf", p[i]);
         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]]);*/      printf("\n");
       }      fprintf(ficlog,"\n");
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];      fprintf(ficrespow,"\n");fflush(ficrespow);
       for (k=1; k<=cptcovprod;k++)      if(*iter <=3){
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        tm = *localtime(&curr_time.tv_sec);
         strcpy(strcurr,asctime(&tm));
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/  /*       asctime_r(&tm,strcurr); */
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/        forecast_time=curr_time;
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/        itmp = strlen(strcurr);
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);        if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
           strcurr[itmp-1]='\0';
     savm=oldm;        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
     oldm=newm;        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
     maxmax=0.;        for(niterf=10;niterf<=30;niterf+=10){
     for(j=1;j<=nlstate;j++){          forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
       min=1.;          tmf = *localtime(&forecast_time.tv_sec);
       max=0.;  /*      asctime_r(&tmf,strfor); */
       for(i=1; i<=nlstate; i++) {          strcpy(strfor,asctime(&tmf));
         sumnew=0;          itmp = strlen(strfor);
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];          if(strfor[itmp-1]=='\n')
         prlim[i][j]= newm[i][j]/(1-sumnew);          strfor[itmp-1]='\0';
         max=FMAX(max,prlim[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);
         min=FMIN(min,prlim[i][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);
       }        }
       maxmin=max-min;      }
       maxmax=FMAX(maxmax,maxmin);      for (i=1;i<=n;i++) {
     }        for (j=1;j<=n;j++) xit[j]=xi[j][i];
     if(maxmax < ftolpl){        fptt=(*fret);
       return prlim;  #ifdef DEBUG
     }        printf("fret=%lf \n",*fret);
   }        fprintf(ficlog,"fret=%lf \n",*fret);
 }  #endif
         printf("%d",i);fflush(stdout);
 /*************** transition probabilities ***************/         fprintf(ficlog,"%d",i);fflush(ficlog);
         linmin(p,xit,n,fret,func);
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )        if (fabs(fptt-(*fret)) > del) {
 {          del=fabs(fptt-(*fret));
   double s1, s2;          ibig=i;
   /*double t34;*/        }
   int i,j,j1, nc, ii, jj;  #ifdef DEBUG
         printf("%d %.12e",i,(*fret));
     for(i=1; i<= nlstate; i++){        fprintf(ficlog,"%d %.12e",i,(*fret));
       for(j=1; j<i;j++){        for (j=1;j<=n;j++) {
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
           /*s2 += param[i][j][nc]*cov[nc];*/          printf(" x(%d)=%.12e",j,xit[j]);
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */        }
         }        for(j=1;j<=n;j++) {
         ps[i][j]=s2;          printf(" p=%.12e",p[j]);
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */          fprintf(ficlog," p=%.12e",p[j]);
       }        }
       for(j=i+1; j<=nlstate+ndeath;j++){        printf("\n");
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){        fprintf(ficlog,"\n");
           s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];  #endif
 /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */      }
         }      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
         ps[i][j]=s2;  #ifdef DEBUG
       }        int k[2],l;
     }        k[0]=1;
     /*ps[3][2]=1;*/        k[1]=-1;
             printf("Max: %.12e",(*func)(p));
     for(i=1; i<= nlstate; i++){        fprintf(ficlog,"Max: %.12e",(*func)(p));
       s1=0;        for (j=1;j<=n;j++) {
       for(j=1; j<i; j++)          printf(" %.12e",p[j]);
         s1+=exp(ps[i][j]);          fprintf(ficlog," %.12e",p[j]);
       for(j=i+1; j<=nlstate+ndeath; j++)        }
         s1+=exp(ps[i][j]);        printf("\n");
       ps[i][i]=1./(s1+1.);        fprintf(ficlog,"\n");
       for(j=1; j<i; j++)        for(l=0;l<=1;l++) {
         ps[i][j]= exp(ps[i][j])*ps[i][i];          for (j=1;j<=n;j++) {
       for(j=i+1; j<=nlstate+ndeath; j++)            ptt[j]=p[j]+(p[j]-pt[j])*k[l];
         ps[i][j]= exp(ps[i][j])*ps[i][i];            printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */            fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
     } /* end i */          }
               printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       for(jj=1; jj<= nlstate+ndeath; jj++){        }
         ps[ii][jj]=0;  #endif
         ps[ii][ii]=1;  
       }  
     }        free_vector(xit,1,n);
             free_vector(xits,1,n);
         free_vector(ptt,1,n);
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */        free_vector(pt,1,n);
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */        return;
 /*         printf("ddd %lf ",ps[ii][jj]); */      }
 /*       } */      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
 /*       printf("\n "); */      for (j=1;j<=n;j++) {
 /*        } */        ptt[j]=2.0*p[j]-pt[j];
 /*        printf("\n ");printf("%lf ",cov[2]); */        xit[j]=p[j]-pt[j];
        /*        pt[j]=p[j];
       for(i=1; i<= npar; i++) printf("%f ",x[i]);      }
       goto end;*/      fptt=(*func)(ptt);
     return ps;      if (fptt < fp) {
 }        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
         if (t < 0.0) {
 /**************** Product of 2 matrices ******************/          linmin(p,xit,n,fret,func);
           for (j=1;j<=n;j++) {
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)            xi[j][ibig]=xi[j][n];
 {            xi[j][n]=xit[j];
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times          }
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */  #ifdef DEBUG
   /* in, b, out are matrice of pointers which should have been initialized           printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
      before: only the contents of out is modified. The function returns          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
      a pointer to pointers identical to out */          for(j=1;j<=n;j++){
   long i, j, k;            printf(" %.12e",xit[j]);
   for(i=nrl; i<= nrh; i++)            fprintf(ficlog," %.12e",xit[j]);
     for(k=ncolol; k<=ncoloh; k++)          }
       for(j=ncl,out[i][k]=0.; j<=nch; j++)          printf("\n");
         out[i][k] +=in[i][j]*b[j][k];          fprintf(ficlog,"\n");
   #endif
   return out;        }
 }      }
     }
   }
 /************* Higher Matrix Product ***************/  
   /**** Prevalence limit (stable or period prevalence)  ****************/
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )  
 {  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
   /* Computes the transition matrix starting at age 'age' over   {
      'nhstepm*hstepm*stepm' months (i.e. until    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying        matrix by transitions matrix until convergence is reached */
      nhstepm*hstepm matrices.   
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step     int i, ii,j,k;
      (typically every 2 years instead of every month which is too big     double min, max, maxmin, maxmax,sumnew=0.;
      for the memory).    double **matprod2();
      Model is determined by parameters x and covariates have to be     double **out, cov[NCOVMAX], **pmij();
      included manually here.     double **newm;
     double agefin, delaymax=50 ; /* Max number of years to converge */
      */  
     for (ii=1;ii<=nlstate+ndeath;ii++)
   int i, j, d, h, k;      for (j=1;j<=nlstate+ndeath;j++){
   double **out, cov[NCOVMAX];        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   double **newm;      }
   
   /* Hstepm could be zero and should return the unit matrix */     cov[1]=1.;
   for (i=1;i<=nlstate+ndeath;i++)   
     for (j=1;j<=nlstate+ndeath;j++){   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
       oldm[i][j]=(i==j ? 1.0 : 0.0);    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
       po[i][j][0]=(i==j ? 1.0 : 0.0);      newm=savm;
     }      /* Covariates have to be included here again */
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */       cov[2]=agefin;
   for(h=1; h <=nhstepm; h++){   
     for(d=1; d <=hstepm; d++){        for (k=1; k<=cptcovn;k++) {
       newm=savm;          cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
       /* Covariates have to be included here again */          /*      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.;        }
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];        for (k=1; k<=cptcovprod;k++)
       for (k=1; k<=cptcovage;k++)          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];  
       for (k=1; k<=cptcovprod;k++)        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
         /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
       out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/  
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/      savm=oldm;
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,       oldm=newm;
                    pmij(pmmij,cov,ncovmodel,x,nlstate));      maxmax=0.;
       savm=oldm;      for(j=1;j<=nlstate;j++){
       oldm=newm;        min=1.;
     }        max=0.;
     for(i=1; i<=nlstate+ndeath; i++)        for(i=1; i<=nlstate; i++) {
       for(j=1;j<=nlstate+ndeath;j++) {          sumnew=0;
         po[i][j][h]=newm[i][j];          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);          prlim[i][j]= newm[i][j]/(1-sumnew);
          */          max=FMAX(max,prlim[i][j]);
       }          min=FMIN(min,prlim[i][j]);
   } /* end h */        }
   return po;        maxmin=max-min;
 }        maxmax=FMAX(maxmax,maxmin);
       }
       if(maxmax < ftolpl){
 /*************** log-likelihood *************/        return prlim;
 double func( double *x)      }
 {    }
   int i, ii, j, k, mi, d, kk;  }
   double l, ll[NLSTATEMAX], cov[NCOVMAX];  
   double **out;  /*************** transition probabilities ***************/
   double sw; /* Sum of weights */  
   double lli; /* Individual log likelihood */  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
   int s1, s2;  {
   double bbh, survp;    double s1, s2;
   long ipmx;    /*double t34;*/
   /*extern weight */    int i,j,j1, nc, ii, jj;
   /* We are differentiating ll according to initial status */  
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/      for(i=1; i<= nlstate; i++){
   /*for(i=1;i<imx;i++)         for(j=1; j<i;j++){
     printf(" %d\n",s[4][i]);          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
   */            /*s2 += param[i][j][nc]*cov[nc];*/
   cov[1]=1.;            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
   /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
   for(k=1; k<=nlstate; k++) ll[k]=0.;          }
           ps[i][j]=s2;
   if(mle==1){  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){        }
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];        for(j=i+1; j<=nlstate+ndeath;j++){
       for(mi=1; mi<= wav[i]-1; mi++){          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
         for (ii=1;ii<=nlstate+ndeath;ii++)            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
           for (j=1;j<=nlstate+ndeath;j++){  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          }
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          ps[i][j]=s2;
           }        }
         for(d=0; d<dh[mi][i]; d++){      }
           newm=savm;      /*ps[3][2]=1;*/
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;     
           for (kk=1; kk<=cptcovage;kk++) {      for(i=1; i<= nlstate; i++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];        s1=0;
           }        for(j=1; j<i; j++)
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          s1+=exp(ps[i][j]);
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));        for(j=i+1; j<=nlstate+ndeath; j++)
           savm=oldm;          s1+=exp(ps[i][j]);
           oldm=newm;        ps[i][i]=1./(s1+1.);
         } /* end mult */        for(j=1; j<i; j++)
                 ps[i][j]= exp(ps[i][j])*ps[i][i];
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */        for(j=i+1; j<=nlstate+ndeath; j++)
         /* But now since version 0.9 we anticipate for bias and large stepm.          ps[i][j]= exp(ps[i][j])*ps[i][i];
          * If stepm is larger than one month (smallest stepm) and if the exact delay         /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
          * (in months) between two waves is not a multiple of stepm, we rounded to       } /* end i */
          * 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      for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
          * (i.e to dh[mi][i]-1) saved in 'savm'. The we inter(extra)polate the        for(jj=1; jj<= nlstate+ndeath; jj++){
          * probability in order to take into account the bias as a fraction of the way          ps[ii][jj]=0;
          * from savm to out if bh is neagtive or even beyond if bh is positive. bh varies          ps[ii][ii]=1;
          * -stepm/2 to stepm/2 .        }
          * For stepm=1 the results are the same as for previous versions of Imach.      }
          * For stepm > 1 the results are less biased than in previous versions.      
          */  
         s1=s[mw[mi][i]][i];  /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
         s2=s[mw[mi+1][i]][i];  /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
         bbh=(double)bh[mi][i]/(double)stepm;   /*         printf("ddd %lf ",ps[ii][jj]); */
         /* bias is positive if real duration  /*       } */
          * is higher than the multiple of stepm and negative otherwise.  /*       printf("\n "); */
          */  /*        } */
         /* 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("\n ");printf("%lf ",cov[2]); */
         if( s2 > nlstate){          /*
           /* i.e. if s2 is a death state and if the date of death is known then the contribution        for(i=1; i<= npar; i++) printf("%f ",x[i]);
              to the likelihood is the probability to die between last step unit time and current         goto end;*/
              step unit time, which is also the differences between probability to die before dh       return ps;
              and probability to die before dh-stepm .   }
              In version up to 0.92 likelihood was computed  
         as if date of death was unknown. Death was treated as any other  /**************** Product of 2 matrices ******************/
         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  double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
         to consider that at each interview the state was recorded  {
         (healthy, disable or death) and IMaCh was corrected; but when we    /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
         introduced the exact date of death then we should have modified       b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
         the contribution of an exact death to the likelihood. This new    /* in, b, out are matrice of pointers which should have been initialized
         contribution is smaller and very dependent of the step unit       before: only the contents of out is modified. The function returns
         stepm. It is no more the probability to die between last interview       a pointer to pointers identical to out */
         and month of death but the probability to survive from last    long i, j, k;
         interview up to one month before death multiplied by the    for(i=nrl; i<= nrh; i++)
         probability to die within a month. Thanks to Chris      for(k=ncolol; k<=ncoloh; k++)
         Jackson for correcting this bug.  Former versions increased        for(j=ncl,out[i][k]=0.; j<=nch; j++)
         mortality artificially. The bad side is that we add another loop          out[i][k] +=in[i][j]*b[j][k];
         which slows down the processing. The difference can be up to 10%  
         lower mortality.    return out;
           */  }
           lli=log(out[s1][s2] - savm[s1][s2]);  
         }else{  
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */  /************* Higher Matrix Product ***************/
           /*  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 ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/  {
         /*if(lli ==000.0)*/    /* Computes the transition matrix starting at age 'age' over
         /*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); */       'nhstepm*hstepm*stepm' months (i.e. until
         ipmx +=1;       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
         sw += weight[i];       nhstepm*hstepm matrices.
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
       } /* end of wave */       (typically every 2 years instead of every month which is too big
     } /* end of individual */       for the memory).
   }  else if(mle==2){       Model is determined by parameters x and covariates have to be
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){       included manually here.
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];  
       for(mi=1; mi<= wav[i]-1; mi++){       */
         for (ii=1;ii<=nlstate+ndeath;ii++)  
           for (j=1;j<=nlstate+ndeath;j++){    int i, j, d, h, k;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    double **out, cov[NCOVMAX];
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    double **newm;
           }  
         for(d=0; d<=dh[mi][i]; d++){    /* Hstepm could be zero and should return the unit matrix */
           newm=savm;    for (i=1;i<=nlstate+ndeath;i++)
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;      for (j=1;j<=nlstate+ndeath;j++){
           for (kk=1; kk<=cptcovage;kk++) {        oldm[i][j]=(i==j ? 1.0 : 0.0);
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];        po[i][j][0]=(i==j ? 1.0 : 0.0);
           }      }
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    for(h=1; h <=nhstepm; h++){
           savm=oldm;      for(d=1; d <=hstepm; d++){
           oldm=newm;        newm=savm;
         } /* end mult */        /* Covariates have to be included here again */
               cov[1]=1.;
         s1=s[mw[mi][i]][i];        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
         s2=s[mw[mi+1][i]][i];        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
         bbh=(double)bh[mi][i]/(double)stepm;         for (k=1; k<=cptcovage;k++)
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         ipmx +=1;        for (k=1; k<=cptcovprod;k++)
         sw += weight[i];          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;  
       } /* end of wave */  
     } /* end of individual */        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
   }  else if(mle==3){  /* exponential inter-extrapolation */        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];                     pmij(pmmij,cov,ncovmodel,x,nlstate));
       for(mi=1; mi<= wav[i]-1; mi++){        savm=oldm;
         for (ii=1;ii<=nlstate+ndeath;ii++)        oldm=newm;
           for (j=1;j<=nlstate+ndeath;j++){      }
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);      for(i=1; i<=nlstate+ndeath; i++)
             savm[ii][j]=(ii==j ? 1.0 : 0.0);        for(j=1;j<=nlstate+ndeath;j++) {
           }          po[i][j][h]=newm[i][j];
         for(d=0; d<dh[mi][i]; d++){          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
           newm=savm;           */
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        }
           for (kk=1; kk<=cptcovage;kk++) {    } /* end h */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    return po;
           }  }
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,  
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));  
           savm=oldm;  /*************** log-likelihood *************/
           oldm=newm;  double func( double *x)
         } /* end mult */  {
           int i, ii, j, k, mi, d, kk;
         s1=s[mw[mi][i]][i];    double l, ll[NLSTATEMAX], cov[NCOVMAX];
         s2=s[mw[mi+1][i]][i];    double **out;
         bbh=(double)bh[mi][i]/(double)stepm;     double sw; /* Sum of weights */
         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 */    double lli; /* Individual log likelihood */
         ipmx +=1;    int s1, s2;
         sw += weight[i];    double bbh, survp;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;    long ipmx;
       } /* end of wave */    /*extern weight */
     } /* end of individual */    /* We are differentiating ll according to initial status */
   }else if (mle==4){  /* ml=4 no inter-extrapolation */    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){    /*for(i=1;i<imx;i++)
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];      printf(" %d\n",s[4][i]);
       for(mi=1; mi<= wav[i]-1; mi++){    */
         for (ii=1;ii<=nlstate+ndeath;ii++)    cov[1]=1.;
           for (j=1;j<=nlstate+ndeath;j++){  
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    for(k=1; k<=nlstate; k++) ll[k]=0.;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);  
           }    if(mle==1){
         for(d=0; d<dh[mi][i]; 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];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        for(mi=1; mi<= wav[i]-1; mi++){
           for (kk=1; kk<=cptcovage;kk++) {          for (ii=1;ii<=nlstate+ndeath;ii++)
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];            for (j=1;j<=nlstate+ndeath;j++){
           }              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                       savm[ii][j]=(ii==j ? 1.0 : 0.0);
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,            }
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          for(d=0; d<dh[mi][i]; d++){
           savm=oldm;            newm=savm;
           oldm=newm;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         } /* end mult */            for (kk=1; kk<=cptcovage;kk++) {
                     cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         s1=s[mw[mi][i]][i];            }
         s2=s[mw[mi+1][i]][i];            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         if( s2 > nlstate){                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           lli=log(out[s1][s2] - savm[s1][s2]);            savm=oldm;
         }else{            oldm=newm;
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */          } /* end mult */
         }       
         ipmx +=1;          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
         sw += weight[i];          /* But now since version 0.9 we anticipate for bias at large stepm.
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;           * If stepm is larger than one month (smallest stepm) and if the exact delay
 /*      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]); */           * (in months) between two waves is not a multiple of stepm, we rounded to
       } /* end of wave */           * the nearest (and in case of equal distance, to the lowest) interval but now
     } /* end of individual */           * we keep into memory the bias bh[mi][i] and also the previous matrix product
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){           * probability in order to take into account the bias as a fraction of the way
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
       for(mi=1; mi<= wav[i]-1; mi++){           * -stepm/2 to stepm/2 .
         for (ii=1;ii<=nlstate+ndeath;ii++)           * For stepm=1 the results are the same as for previous versions of Imach.
           for (j=1;j<=nlstate+ndeath;j++){           * For stepm > 1 the results are less biased than in previous versions.
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);           */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          s1=s[mw[mi][i]][i];
           }          s2=s[mw[mi+1][i]][i];
         for(d=0; d<dh[mi][i]; d++){          bbh=(double)bh[mi][i]/(double)stepm;
           newm=savm;          /* bias bh is positive if real duration
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;           * is higher than the multiple of stepm and negative otherwise.
           for (kk=1; kk<=cptcovage;kk++) {           */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
           }          if( s2 > nlstate){
                     /* i.e. if s2 is a death state and if the date of death is known
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,               then the contribution to the likelihood is the probability to
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));               die between last step unit time and current  step unit time,
           savm=oldm;               which is also equal to probability to die before dh
           oldm=newm;               minus probability to die before dh-stepm .
         } /* end mult */               In version up to 0.92 likelihood was computed
                 as if date of death was unknown. Death was treated as any other
         s1=s[mw[mi][i]][i];          health state: the date of the interview describes the actual state
         s2=s[mw[mi+1][i]][i];          and not the date of a change in health state. The former idea was
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */          to consider that at each interview the state was recorded
         ipmx +=1;          (healthy, disable or death) and IMaCh was corrected; but when we
         sw += weight[i];          introduced the exact date of death then we should have modified
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          the contribution of an exact death to the likelihood. This new
         /*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]);*/          contribution is smaller and very dependent of the step unit
       } /* end of wave */          stepm. It is no more the probability to die between last interview
     } /* end of individual */          and month of death but the probability to survive from last
   } /* End of if */          interview up to one month before death multiplied by the
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];          probability to die within a month. Thanks to Chris
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */          Jackson for correcting this bug.  Former versions increased
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          mortality artificially. The bad side is that we add another loop
   return -l;          which slows down the processing. The difference can be up to 10%
 }          lower mortality.
             */
 /*************** log-likelihood *************/            lli=log(out[s1][s2] - savm[s1][s2]);
 double funcone( double *x)  
 {  
   /* Same as likeli but slower because of a lot of printf and if */          } else if  (s2==-2) {
   int i, ii, j, k, mi, d, kk;            for (j=1,survp=0. ; j<=nlstate; j++)
   double l, ll[NLSTATEMAX], cov[NCOVMAX];              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
   double **out;            /*survp += out[s1][j]; */
   double lli; /* Individual log likelihood */            lli= log(survp);
   double llt;          }
   int s1, s2;         
   double bbh, survp;          else if  (s2==-4) {
   /*extern weight */            for (j=3,survp=0. ; j<=nlstate; j++)  
   /* We are differentiating ll according to initial status */              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/            lli= log(survp);
   /*for(i=1;i<imx;i++)           }
     printf(" %d\n",s[4][i]);  
   */          else if  (s2==-5) {
   cov[1]=1.;            for (j=1,survp=0. ; j<=2; j++)  
               survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
   for(k=1; k<=nlstate; k++) ll[k]=0.;            lli= log(survp);
           }
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){         
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          else{
     for(mi=1; mi<= wav[i]-1; mi++){            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
       for (ii=1;ii<=nlstate+ndeath;ii++)            /*  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 (j=1;j<=nlstate+ndeath;j++){          }
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
           savm[ii][j]=(ii==j ? 1.0 : 0.0);          /*if(lli ==000.0)*/
         }          /*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); */
       for(d=0; d<dh[mi][i]; d++){          ipmx +=1;
         newm=savm;          sw += weight[i];
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         for (kk=1; kk<=cptcovage;kk++) {        } /* end of wave */
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];      } /* end of individual */
         }    }  else if(mle==2){
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         savm=oldm;        for(mi=1; mi<= wav[i]-1; mi++){
         oldm=newm;          for (ii=1;ii<=nlstate+ndeath;ii++)
       } /* end mult */            for (j=1;j<=nlstate+ndeath;j++){
                     oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       s1=s[mw[mi][i]][i];              savm[ii][j]=(ii==j ? 1.0 : 0.0);
       s2=s[mw[mi+1][i]][i];            }
       bbh=(double)bh[mi][i]/(double)stepm;           for(d=0; d<=dh[mi][i]; d++){
       /* bias is positive if real duration            newm=savm;
        * is higher than the multiple of stepm and negative otherwise.            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
        */            for (kk=1; kk<=cptcovage;kk++) {
       if( s2 > nlstate && (mle <5) ){  /* Jackson */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         lli=log(out[s1][s2] - savm[s1][s2]);            }
       } else if (mle==1){            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
       } else if(mle==2){            savm=oldm;
         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 */            oldm=newm;
       } else if(mle==3){  /* exponential inter-extrapolation */          } /* end mult */
         lli= (savm[s1][s2]>(double)1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */       
       } else if (mle==4){  /* mle=4 no inter-extrapolation */          s1=s[mw[mi][i]][i];
         lli=log(out[s1][s2]); /* Original formula */          s2=s[mw[mi+1][i]][i];
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */          bbh=(double)bh[mi][i]/(double)stepm;
         lli=log(out[s1][s2]); /* Original formula */          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 of if */          ipmx +=1;
       ipmx +=1;          sw += weight[i];
       sw += weight[i];          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;        } /* end of wave */
 /*       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 individual */
       if(globpr){    }  else if(mle==3){  /* exponential inter-extrapolation */
         fprintf(ficresilk,"%9d %6d %1d %1d %1d %1d %3d %10.6f %6.4f\      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
  %10.6f %10.6f %10.6f ", \        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],        for(mi=1; mi<= wav[i]-1; mi++){
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);          for (ii=1;ii<=nlstate+ndeath;ii++)
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){            for (j=1;j<=nlstate+ndeath;j++){
           llt +=ll[k]*gipmx/gsw;              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);              savm[ii][j]=(ii==j ? 1.0 : 0.0);
         }            }
         fprintf(ficresilk," %10.6f\n", -llt);          for(d=0; d<dh[mi][i]; d++){
       }            newm=savm;
     } /* end of wave */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   } /* end of individual */            for (kk=1; kk<=cptcovage;kk++) {
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */            }
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   if(globpr==0){ /* First time we count the contributions and weights */                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
     gipmx=ipmx;            savm=oldm;
     gsw=sw;            oldm=newm;
   }          } /* end mult */
   return -l;       
 }          s1=s[mw[mi][i]][i];
           s2=s[mw[mi+1][i]][i];
           bbh=(double)bh[mi][i]/(double)stepm;
 /*************** function likelione ***********/          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 */
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))          ipmx +=1;
 {          sw += weight[i];
   /* This routine should help understanding what is done with           ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
      the selection of individuals/waves and        } /* end of wave */
      to check the exact contribution to the likelihood.      } /* end of individual */
      Plotting could be done.    }else if (mle==4){  /* ml=4 no inter-extrapolation */
    */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   int k;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         for(mi=1; mi<= wav[i]-1; mi++){
   if(*globpri !=0){ /* Just counts and sums, no printings */          for (ii=1;ii<=nlstate+ndeath;ii++)
     strcpy(fileresilk,"ilk");             for (j=1;j<=nlstate+ndeath;j++){
     strcat(fileresilk,fileres);              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {              savm[ii][j]=(ii==j ? 1.0 : 0.0);
       printf("Problem with resultfile: %s\n", fileresilk);            }
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);          for(d=0; d<dh[mi][i]; d++){
     }            newm=savm;
     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");            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");            for (kk=1; kk<=cptcovage;kk++) {
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     for(k=1; k<=nlstate; k++)             }
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);         
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   }                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
             savm=oldm;
   *fretone=(*funcone)(p);            oldm=newm;
   if(*globpri !=0){          } /* end mult */
     fclose(ficresilk);       
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));          s1=s[mw[mi][i]][i];
     fflush(fichtm);           s2=s[mw[mi+1][i]][i];
   }           if( s2 > nlstate){
   return;            lli=log(out[s1][s2] - savm[s1][s2]);
 }          }else{
             lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
           }
 /*********** Maximum Likelihood Estimation ***************/          ipmx +=1;
           sw += weight[i];
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 {  /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
   int i,j, iter;        } /* end of wave */
   double **xi;      } /* end of individual */
   double fret;    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
   double fretone; /* Only one call to likelihood */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   /*  char filerespow[FILENAMELENGTH];*/        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   xi=matrix(1,npar,1,npar);        for(mi=1; mi<= wav[i]-1; mi++){
   for (i=1;i<=npar;i++)          for (ii=1;ii<=nlstate+ndeath;ii++)
     for (j=1;j<=npar;j++)            for (j=1;j<=nlstate+ndeath;j++){
       xi[i][j]=(i==j ? 1.0 : 0.0);              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   printf("Powell\n");  fprintf(ficlog,"Powell\n");              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   strcpy(filerespow,"pow");             }
   strcat(filerespow,fileres);          for(d=0; d<dh[mi][i]; d++){
   if((ficrespow=fopen(filerespow,"w"))==NULL) {            newm=savm;
     printf("Problem with resultfile: %s\n", filerespow);            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);            for (kk=1; kk<=cptcovage;kk++) {
   }              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   fprintf(ficrespow,"# Powell\n# iter -2*LL");            }
   for (i=1;i<=nlstate;i++)         
     for(j=1;j<=nlstate+ndeath;j++)            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   fprintf(ficrespow,"\n");            savm=oldm;
             oldm=newm;
   powell(p,xi,npar,ftol,&iter,&fret,func);          } /* end mult */
        
   fclose(ficrespow);          s1=s[mw[mi][i]][i];
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));          s2=s[mw[mi+1][i]][i];
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));          ipmx +=1;
           sw += weight[i];
 }          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/
 /**** Computes Hessian and covariance matrix ***/        } /* end of wave */
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))      } /* end of individual */
 {    } /* End of if */
   double  **a,**y,*x,pd;    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
   double **hess;    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   int i, j,jk;    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
   int *indx;    return -l;
   }
   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);  /*************** log-likelihood *************/
   void lubksb(double **a, int npar, int *indx, double b[]) ;  double funcone( double *x)
   void ludcmp(double **a, int npar, int *indx, double *d) ;  {
   double gompertz(double p[]);    /* Same as likeli but slower because of a lot of printf and if */
   hess=matrix(1,npar,1,npar);    int i, ii, j, k, mi, d, kk;
     double l, ll[NLSTATEMAX], cov[NCOVMAX];
   printf("\nCalculation of the hessian matrix. Wait...\n");    double **out;
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");    double lli; /* Individual log likelihood */
   for (i=1;i<=npar;i++){    double llt;
     printf("%d",i);fflush(stdout);    int s1, s2;
     fprintf(ficlog,"%d",i);fflush(ficlog);    double bbh, survp;
        /*extern weight */
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);    /* We are differentiating ll according to initial status */
         /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     /*  printf(" %f ",p[i]);    /*for(i=1;i<imx;i++)
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/      printf(" %d\n",s[4][i]);
   }    */
       cov[1]=1.;
   for (i=1;i<=npar;i++) {  
     for (j=1;j<=npar;j++)  {    for(k=1; k<=nlstate; k++) ll[k]=0.;
       if (j>i) {   
         printf(".%d%d",i,j);fflush(stdout);    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         hess[i][j]=hessij(p,delti,i,j,func,npar);      for(mi=1; mi<= wav[i]-1; mi++){
                 for (ii=1;ii<=nlstate+ndeath;ii++)
         hess[j][i]=hess[i][j];              for (j=1;j<=nlstate+ndeath;j++){
         /*printf(" %lf ",hess[i][j]);*/            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       }            savm[ii][j]=(ii==j ? 1.0 : 0.0);
     }          }
   }        for(d=0; d<dh[mi][i]; d++){
   printf("\n");          newm=savm;
   fprintf(ficlog,"\n");          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
           for (kk=1; kk<=cptcovage;kk++) {
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");          }
             out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   a=matrix(1,npar,1,npar);                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   y=matrix(1,npar,1,npar);          savm=oldm;
   x=vector(1,npar);          oldm=newm;
   indx=ivector(1,npar);        } /* end mult */
   for (i=1;i<=npar;i++)       
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];        s1=s[mw[mi][i]][i];
   ludcmp(a,npar,indx,&pd);        s2=s[mw[mi+1][i]][i];
         bbh=(double)bh[mi][i]/(double)stepm;
   for (j=1;j<=npar;j++) {        /* bias is positive if real duration
     for (i=1;i<=npar;i++) x[i]=0;         * is higher than the multiple of stepm and negative otherwise.
     x[j]=1;         */
     lubksb(a,npar,indx,x);        if( s2 > nlstate && (mle <5) ){  /* Jackson */
     for (i=1;i<=npar;i++){           lli=log(out[s1][s2] - savm[s1][s2]);
       matcov[i][j]=x[i];        } else if  (s2==-2) {
     }          for (j=1,survp=0. ; j<=nlstate; j++)
   }            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           lli= log(survp);
   printf("\n#Hessian matrix#\n");        }else if (mle==1){
   fprintf(ficlog,"\n#Hessian matrix#\n");          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
   for (i=1;i<=npar;i++) {         } else if(mle==2){
     for (j=1;j<=npar;j++) {           lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
       printf("%.3e ",hess[i][j]);        } else if(mle==3){  /* exponential inter-extrapolation */
       fprintf(ficlog,"%.3e ",hess[i][j]);          lli= (savm[s1][s2]>(double)1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
     }        } else if (mle==4){  /* mle=4 no inter-extrapolation */
     printf("\n");          lli=log(out[s1][s2]); /* Original formula */
     fprintf(ficlog,"\n");        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
   }          lli=log(out[s1][s2]); /* Original formula */
         } /* End of if */
   /* Recompute Inverse */        ipmx +=1;
   for (i=1;i<=npar;i++)        sw += weight[i];
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   ludcmp(a,npar,indx,&pd);  /*       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){
   /*  printf("\n#Hessian matrix recomputed#\n");          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
    %11.6f %11.6f %11.6f ", \
   for (j=1;j<=npar;j++) {                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
     for (i=1;i<=npar;i++) x[i]=0;                  2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
     x[j]=1;          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
     lubksb(a,npar,indx,x);            llt +=ll[k]*gipmx/gsw;
     for (i=1;i<=npar;i++){             fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
       y[i][j]=x[i];          }
       printf("%.3e ",y[i][j]);          fprintf(ficresilk," %10.6f\n", -llt);
       fprintf(ficlog,"%.3e ",y[i][j]);        }
     }      } /* end of wave */
     printf("\n");    } /* end of individual */
     fprintf(ficlog,"\n");    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
   }    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   */    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
     if(globpr==0){ /* First time we count the contributions and weights */
   free_matrix(a,1,npar,1,npar);      gipmx=ipmx;
   free_matrix(y,1,npar,1,npar);      gsw=sw;
   free_vector(x,1,npar);    }
   free_ivector(indx,1,npar);    return -l;
   free_matrix(hess,1,npar,1,npar);  }
   
   
 }  /*************** function likelione ***********/
   void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 /*************** hessian matrix ****************/  {
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)    /* This routine should help understanding what is done with
 {       the selection of individuals/waves and
   int i;       to check the exact contribution to the likelihood.
   int l=1, lmax=20;       Plotting could be done.
   double k1,k2;     */
   double p2[NPARMAX+1];    int k;
   double res;  
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;    if(*globpri !=0){ /* Just counts and sums, no printings */
   double fx;      strcpy(fileresilk,"ilk");
   int k=0,kmax=10;      strcat(fileresilk,fileres);
   double l1;      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
         printf("Problem with resultfile: %s\n", fileresilk);
   fx=func(x);        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
   for (i=1;i<=npar;i++) p2[i]=x[i];      }
   for(l=0 ; l <=lmax; l++){      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");
     l1=pow(10,l);      fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
     delts=delt;      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
     for(k=1 ; k <kmax; k=k+1){      for(k=1; k<=nlstate; k++)
       delt = delta*(l1*k);        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
       p2[theta]=x[theta] +delt;      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
       k1=func(p2)-fx;    }
       p2[theta]=x[theta]-delt;  
       k2=func(p2)-fx;    *fretone=(*funcone)(p);
       /*res= (k1-2.0*fx+k2)/delt/delt; */    if(*globpri !=0){
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */      fclose(ficresilk);
             fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 #ifdef DEBUG      fflush(fichtm);
       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);    return;
 #endif  }
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */  
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){  
         k=kmax;  /*********** Maximum Likelihood Estimation ***************/
       }  
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
         k=kmax; l=lmax*10.;  {
       }    int i,j, iter;
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){     double **xi;
         delts=delt;    double fret;
       }    double fretone; /* Only one call to likelihood */
     }    /*  char filerespow[FILENAMELENGTH];*/
   }    xi=matrix(1,npar,1,npar);
   delti[theta]=delts;    for (i=1;i<=npar;i++)
   return res;       for (j=1;j<=npar;j++)
           xi[i][j]=(i==j ? 1.0 : 0.0);
 }    printf("Powell\n");  fprintf(ficlog,"Powell\n");
     strcpy(filerespow,"pow");
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)    strcat(filerespow,fileres);
 {    if((ficrespow=fopen(filerespow,"w"))==NULL) {
   int i;      printf("Problem with resultfile: %s\n", filerespow);
   int l=1, l1, lmax=20;      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
   double k1,k2,k3,k4,res,fx;    }
   double p2[NPARMAX+1];    fprintf(ficrespow,"# Powell\n# iter -2*LL");
   int k;    for (i=1;i<=nlstate;i++)
       for(j=1;j<=nlstate+ndeath;j++)
   fx=func(x);        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   for (k=1; k<=2; k++) {    fprintf(ficrespow,"\n");
     for (i=1;i<=npar;i++) p2[i]=x[i];  
     p2[thetai]=x[thetai]+delti[thetai]/k;    powell(p,xi,npar,ftol,&iter,&fret,func);
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;  
     k1=func(p2)-fx;    free_matrix(xi,1,npar,1,npar);
       fclose(ficrespow);
     p2[thetai]=x[thetai]+delti[thetai]/k;    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
     k2=func(p2)-fx;    fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
     
     p2[thetai]=x[thetai]-delti[thetai]/k;  }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;  
     k3=func(p2)-fx;  /**** Computes Hessian and covariance matrix ***/
     void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
     p2[thetai]=x[thetai]-delti[thetai]/k;  {
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    double  **a,**y,*x,pd;
     k4=func(p2)-fx;    double **hess;
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */    int i, j,jk;
 #ifdef DEBUG    int *indx;
     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);    double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 #endif    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
   }    void lubksb(double **a, int npar, int *indx, double b[]) ;
   return res;    void ludcmp(double **a, int npar, int *indx, double *d) ;
 }    double gompertz(double p[]);
     hess=matrix(1,npar,1,npar);
 /************** Inverse of matrix **************/  
 void ludcmp(double **a, int n, int *indx, double *d)     printf("\nCalculation of the hessian matrix. Wait...\n");
 {     fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
   int i,imax,j,k;     for (i=1;i<=npar;i++){
   double big,dum,sum,temp;       printf("%d",i);fflush(stdout);
   double *vv;       fprintf(ficlog,"%d",i);fflush(ficlog);
       
   vv=vector(1,n);        hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
   *d=1.0;      
   for (i=1;i<=n;i++) {       /*  printf(" %f ",p[i]);
     big=0.0;           printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
     for (j=1;j<=n;j++)     }
       if ((temp=fabs(a[i][j])) > big) big=temp;    
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");     for (i=1;i<=npar;i++) {
     vv[i]=1.0/big;       for (j=1;j<=npar;j++)  {
   }         if (j>i) {
   for (j=1;j<=n;j++) {           printf(".%d%d",i,j);fflush(stdout);
     for (i=1;i<j;i++) {           fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
       sum=a[i][j];           hess[i][j]=hessij(p,delti,i,j,func,npar);
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];          
       a[i][j]=sum;           hess[j][i]=hess[i][j];    
     }           /*printf(" %lf ",hess[i][j]);*/
     big=0.0;         }
     for (i=j;i<=n;i++) {       }
       sum=a[i][j];     }
       for (k=1;k<j;k++)     printf("\n");
         sum -= a[i][k]*a[k][j];     fprintf(ficlog,"\n");
       a[i][j]=sum;   
       if ( (dum=vv[i]*fabs(sum)) >= big) {     printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
         big=dum;     fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
         imax=i;    
       }     a=matrix(1,npar,1,npar);
     }     y=matrix(1,npar,1,npar);
     if (j != imax) {     x=vector(1,npar);
       for (k=1;k<=n;k++) {     indx=ivector(1,npar);
         dum=a[imax][k];     for (i=1;i<=npar;i++)
         a[imax][k]=a[j][k];       for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
         a[j][k]=dum;     ludcmp(a,npar,indx,&pd);
       }   
       *d = -(*d);     for (j=1;j<=npar;j++) {
       vv[imax]=vv[j];       for (i=1;i<=npar;i++) x[i]=0;
     }       x[j]=1;
     indx[j]=imax;       lubksb(a,npar,indx,x);
     if (a[j][j] == 0.0) a[j][j]=TINY;       for (i=1;i<=npar;i++){
     if (j != n) {         matcov[i][j]=x[i];
       dum=1.0/(a[j][j]);       }
       for (i=j+1;i<=n;i++) a[i][j] *= dum;     }
     }   
   }     printf("\n#Hessian matrix#\n");
   free_vector(vv,1,n);  /* Doesn't work */    fprintf(ficlog,"\n#Hessian matrix#\n");
 ;    for (i=1;i<=npar;i++) {
 }       for (j=1;j<=npar;j++) {
         printf("%.3e ",hess[i][j]);
 void lubksb(double **a, int n, int *indx, double b[])         fprintf(ficlog,"%.3e ",hess[i][j]);
 {       }
   int i,ii=0,ip,j;       printf("\n");
   double sum;       fprintf(ficlog,"\n");
      }
   for (i=1;i<=n;i++) {   
     ip=indx[i];     /* Recompute Inverse */
     sum=b[ip];     for (i=1;i<=npar;i++)
     b[ip]=b[i];       for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
     if (ii)     ludcmp(a,npar,indx,&pd);
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];   
     else if (sum) ii=i;     /*  printf("\n#Hessian matrix recomputed#\n");
     b[i]=sum;   
   }     for (j=1;j<=npar;j++) {
   for (i=n;i>=1;i--) {       for (i=1;i<=npar;i++) x[i]=0;
     sum=b[i];       x[j]=1;
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];       lubksb(a,npar,indx,x);
     b[i]=sum/a[i][i];       for (i=1;i<=npar;i++){
   }         y[i][j]=x[i];
 }         printf("%.3e ",y[i][j]);
         fprintf(ficlog,"%.3e ",y[i][j]);
 /************ Frequencies ********************/      }
 void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint)      printf("\n");
 {  /* Some frequencies */      fprintf(ficlog,"\n");
       }
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;    */
   int first;  
   double ***freq; /* Frequencies */    free_matrix(a,1,npar,1,npar);
   double *pp, **prop;    free_matrix(y,1,npar,1,npar);
   double pos,posprop, k2, dateintsum=0,k2cpt=0;    free_vector(x,1,npar);
   FILE *ficresp;    free_ivector(indx,1,npar);
   char fileresp[FILENAMELENGTH];    free_matrix(hess,1,npar,1,npar);
     
   pp=vector(1,nlstate);  
   prop=matrix(1,nlstate,iagemin,iagemax+3);  }
   strcpy(fileresp,"p");  
   strcat(fileresp,fileres);  /*************** hessian matrix ****************/
   if((ficresp=fopen(fileresp,"w"))==NULL) {  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
     printf("Problem with prevalence resultfile: %s\n", fileresp);  {
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);    int i;
     exit(0);    int l=1, lmax=20;
   }    double k1,k2;
   freq= ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);    double p2[NPARMAX+1];
   j1=0;    double res;
       double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
   j=cptcoveff;    double fx;
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    int k=0,kmax=10;
     double l1;
   first=1;  
     fx=func(x);
   for(k1=1; k1<=j;k1++){    for (i=1;i<=npar;i++) p2[i]=x[i];
     for(i1=1; i1<=ncodemax[k1];i1++){    for(l=0 ; l <=lmax; l++){
       j1++;      l1=pow(10,l);
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);      delts=delt;
         scanf("%d", i);*/      for(k=1 ; k <kmax; k=k+1){
       for (i=-1; i<=nlstate+ndeath; i++)          delt = delta*(l1*k);
         for (jk=-1; jk<=nlstate+ndeath; jk++)          p2[theta]=x[theta] +delt;
           for(m=iagemin; m <= iagemax+3; m++)        k1=func(p2)-fx;
             freq[i][jk][m]=0;        p2[theta]=x[theta]-delt;
         k2=func(p2)-fx;
     for (i=1; i<=nlstate; i++)          /*res= (k1-2.0*fx+k2)/delt/delt; */
       for(m=iagemin; m <= iagemax+3; m++)        res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
         prop[i][m]=0;       
         #ifdef DEBUG
       dateintsum=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);
       k2cpt=0;        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);
       for (i=1; i<=imx; i++) {  #endif
         bool=1;        /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
         if  (cptcovn>0) {        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
           for (z1=1; z1<=cptcoveff; z1++)           k=kmax;
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])         }
               bool=0;        else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
         }          k=kmax; l=lmax*10.;
         if (bool==1){        }
           for(m=firstpass; m<=lastpass; m++){        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
             k2=anint[m][i]+(mint[m][i]/12.);          delts=delt;
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/        }
               if(agev[m][i]==0) agev[m][i]=iagemax+1;      }
               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];    delti[theta]=delts;
               if (m<lastpass) {    return res;
                 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];  }
               }  
                 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {  {
                 dateintsum=dateintsum+k2;    int i;
                 k2cpt++;    int l=1, l1, lmax=20;
               }    double k1,k2,k3,k4,res,fx;
               /*}*/    double p2[NPARMAX+1];
           }    int k;
         }  
       }    fx=func(x);
            for (k=1; k<=2; k++) {
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/      for (i=1;i<=npar;i++) p2[i]=x[i];
       p2[thetai]=x[thetai]+delti[thetai]/k;
       if  (cptcovn>0) {      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
         fprintf(ficresp, "\n#********** Variable ");       k1=func(p2)-fx;
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);   
         fprintf(ficresp, "**********\n#");      p2[thetai]=x[thetai]+delti[thetai]/k;
       }      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
       for(i=1; i<=nlstate;i++)       k2=func(p2)-fx;
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);   
       fprintf(ficresp, "\n");      p2[thetai]=x[thetai]-delti[thetai]/k;
             p2[thetaj]=x[thetaj]+delti[thetaj]/k;
       for(i=iagemin; i <= iagemax+3; i++){      k3=func(p2)-fx;
         if(i==iagemax+3){   
           fprintf(ficlog,"Total");      p2[thetai]=x[thetai]-delti[thetai]/k;
         }else{      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
           if(first==1){      k4=func(p2)-fx;
             first=0;      res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
             printf("See log file for details...\n");  #ifdef DEBUG
           }      printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
           fprintf(ficlog,"Age %d", i);      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
         for(jk=1; jk <=nlstate ; jk++){    }
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)    return res;
             pp[jk] += freq[jk][m][i];   }
         }  
         for(jk=1; jk <=nlstate ; jk++){  /************** Inverse of matrix **************/
           for(m=-1, pos=0; m <=0 ; m++)  void ludcmp(double **a, int n, int *indx, double *d)
             pos += freq[jk][m][i];  {
           if(pp[jk]>=1.e-10){    int i,imax,j,k;
             if(first==1){    double big,dum,sum,temp;
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);    double *vv;
             }   
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);    vv=vector(1,n);
           }else{    *d=1.0;
             if(first==1)    for (i=1;i<=n;i++) {
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);      big=0.0;
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);      for (j=1;j<=n;j++)
           }        if ((temp=fabs(a[i][j])) > big) big=temp;
         }      if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
       vv[i]=1.0/big;
         for(jk=1; jk <=nlstate ; jk++){    }
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)    for (j=1;j<=n;j++) {
             pp[jk] += freq[jk][m][i];      for (i=1;i<j;i++) {
         }               sum=a[i][j];
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){        for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
           pos += pp[jk];        a[i][j]=sum;
           posprop += prop[jk][i];      }
         }      big=0.0;
         for(jk=1; jk <=nlstate ; jk++){      for (i=j;i<=n;i++) {
           if(pos>=1.e-5){        sum=a[i][j];
             if(first==1)        for (k=1;k<j;k++)
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);          sum -= a[i][k]*a[k][j];
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);        a[i][j]=sum;
           }else{        if ( (dum=vv[i]*fabs(sum)) >= big) {
             if(first==1)          big=dum;
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);          imax=i;
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);        }
           }      }
           if( i <= iagemax){      if (j != imax) {
             if(pos>=1.e-5){        for (k=1;k<=n;k++) {
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);          dum=a[imax][k];
               /*probs[i][jk][j1]= pp[jk]/pos;*/          a[imax][k]=a[j][k];
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/          a[j][k]=dum;
             }        }
             else        *d = -(*d);
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);        vv[imax]=vv[j];
           }      }
         }      indx[j]=imax;
               if (a[j][j] == 0.0) a[j][j]=TINY;
         for(jk=-1; jk <=nlstate+ndeath; jk++)      if (j != n) {
           for(m=-1; m <=nlstate+ndeath; m++)        dum=1.0/(a[j][j]);
             if(freq[jk][m][i] !=0 ) {        for (i=j+1;i<=n;i++) a[i][j] *= dum;
             if(first==1)      }
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);    }
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);    free_vector(vv,1,n);  /* Doesn't work */
             }  ;
         if(i <= iagemax)  }
           fprintf(ficresp,"\n");  
         if(first==1)  void lubksb(double **a, int n, int *indx, double b[])
           printf("Others in log...\n");  {
         fprintf(ficlog,"\n");    int i,ii=0,ip,j;
       }    double sum;
     }   
   }    for (i=1;i<=n;i++) {
   dateintmean=dateintsum/k2cpt;       ip=indx[i];
        sum=b[ip];
   fclose(ficresp);      b[ip]=b[i];
   free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);      if (ii)
   free_vector(pp,1,nlstate);        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);      else if (sum) ii=i;
   /* End of Freq */      b[i]=sum;
 }    }
     for (i=n;i>=1;i--) {
 /************ Prevalence ********************/      sum=b[i];
 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 (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
 {        b[i]=sum/a[i][i];
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people    }
      in each health status at the date of interview (if between dateprev1 and dateprev2).  }
      We still use firstpass and lastpass as another selection.  
   */  void pstamp(FILE *fichier)
    {
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
   double ***freq; /* Frequencies */  }
   double *pp, **prop;  
   double pos,posprop;   /************ Frequencies ********************/
   double  y2; /* in fractional years */  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[])
   int iagemin, iagemax;  {  /* Some frequencies */
    
   iagemin= (int) agemin;    int i, m, jk, k1,i1, j1, bool, z1,z2,j;
   iagemax= (int) agemax;    int first;
   /*pp=vector(1,nlstate);*/    double ***freq; /* Frequencies */
   prop=matrix(1,nlstate,iagemin,iagemax+3);     double *pp, **prop;
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/    double pos,posprop, k2, dateintsum=0,k2cpt=0;
   j1=0;    char fileresp[FILENAMELENGTH];
      
   j=cptcoveff;    pp=vector(1,nlstate);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    prop=matrix(1,nlstate,iagemin,iagemax+3);
       strcpy(fileresp,"p");
   for(k1=1; k1<=j;k1++){    strcat(fileresp,fileres);
     for(i1=1; i1<=ncodemax[k1];i1++){    if((ficresp=fopen(fileresp,"w"))==NULL) {
       j1++;      printf("Problem with prevalence resultfile: %s\n", fileresp);
             fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
       for (i=1; i<=nlstate; i++)        exit(0);
         for(m=iagemin; m <= iagemax+3; m++)    }
           prop[i][m]=0.0;    freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
          j1=0;
       for (i=1; i<=imx; i++) { /* Each individual */   
         bool=1;    j=cptcoveff;
         if  (cptcovn>0) {    if (cptcovn<1) {j=1;ncodemax[1]=1;}
           for (z1=1; z1<=cptcoveff; z1++)   
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     first=1;
               bool=0;  
         }     for(k1=1; k1<=j;k1++){
         if (bool==1) {       for(i1=1; i1<=ncodemax[k1];i1++){
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/        j1++;
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */          scanf("%d", i);*/
               if(agev[m][i]==0) agev[m][i]=iagemax+1;        for (i=-5; i<=nlstate+ndeath; i++)  
               if(agev[m][i]==1) agev[m][i]=iagemax+2;          for (jk=-5; jk<=nlstate+ndeath; jk++)  
               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);             for(m=iagemin; m <= iagemax+3; m++)
               if (s[m][i]>0 && s[m][i]<=nlstate) {               freq[i][jk][m]=0;
                 /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/  
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];      for (i=1; i<=nlstate; i++)  
                 prop[s[m][i]][iagemax+3] += weight[i];         for(m=iagemin; m <= iagemax+3; m++)
               }           prop[i][m]=0;
             }       
           } /* end selection of waves */        dateintsum=0;
         }        k2cpt=0;
       }        for (i=1; i<=imx; i++) {
       for(i=iagemin; i <= iagemax+3; i++){            bool=1;
                   if  (cptcovn>0) {
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {             for (z1=1; z1<=cptcoveff; z1++)
           posprop += prop[jk][i];               if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
         }                 bool=0;
           }
         for(jk=1; jk <=nlstate ; jk++){               if (bool==1){
           if( i <=  iagemax){             for(m=firstpass; m<=lastpass; m++){
             if(posprop>=1.e-5){               k2=anint[m][i]+(mint[m][i]/12.);
               probs[i][jk][j1]= prop[jk][i]/posprop;              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
             }                 if(agev[m][i]==0) agev[m][i]=iagemax+1;
           }                 if(agev[m][i]==1) agev[m][i]=iagemax+2;
         }/* end jk */                 if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
       }/* end i */                 if (m<lastpass) {
     } /* end i1 */                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
   } /* end k1 */                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   }
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/               
   /*free_vector(pp,1,nlstate);*/                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);                  dateintsum=dateintsum+k2;
 }  /* End of prevalence */                  k2cpt++;
                 }
 /************* Waves Concatenation ***************/                /*}*/
             }
 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)          }
 {        }
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.         
      Death is a valid wave (if date is known).        /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i        pstamp(ficresp);
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]        if  (cptcovn>0) {
      and mw[mi+1][i]. dh depends on stepm.          fprintf(ficresp, "\n#********** Variable ");
      */          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           fprintf(ficresp, "**********\n#");
   int i, mi, m;        }
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;        for(i=1; i<=nlstate;i++)
      double sum=0., jmean=0.;*/          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
   int first;        fprintf(ficresp, "\n");
   int j, k=0,jk, ju, jl;       
   double sum=0.;        for(i=iagemin; i <= iagemax+3; i++){
   first=0;          if(i==iagemax+3){
   jmin=1e+5;            fprintf(ficlog,"Total");
   jmax=-1;          }else{
   jmean=0.;            if(first==1){
   for(i=1; i<=imx; i++){              first=0;
     mi=0;              printf("See log file for details...\n");
     m=firstpass;            }
     while(s[m][i] <= nlstate){            fprintf(ficlog,"Age %d", i);
       if(s[m][i]>=1)          }
         mw[++mi][i]=m;          for(jk=1; jk <=nlstate ; jk++){
       if(m >=lastpass)            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
         break;              pp[jk] += freq[jk][m][i];
       else          }
         m++;          for(jk=1; jk <=nlstate ; jk++){
     }/* end while */            for(m=-1, pos=0; m <=0 ; m++)
     if (s[m][i] > nlstate){              pos += freq[jk][m][i];
       mi++;     /* Death is another wave */            if(pp[jk]>=1.e-10){
       /* if(mi==0)  never been interviewed correctly before death */              if(first==1){
          /* Only death is a correct wave */              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
       mw[mi][i]=m;              }
     }              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
             }else{
     wav[i]=mi;              if(first==1)
     if(mi==0){                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
       nbwarn++;              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
       if(first==0){            }
         printf("Warning! None valid information for:%ld line=%d (skipped) and may be others, see log file\n",num[i],i);          }
         first=1;  
       }          for(jk=1; jk <=nlstate ; jk++){
       if(first==1){            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
         fprintf(ficlog,"Warning! None valid information for:%ld line=%d (skipped)\n",num[i],i);              pp[jk] += freq[jk][m][i];
       }          }      
     } /* end mi==0 */          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
   } /* End individuals */            pos += pp[jk];
             posprop += prop[jk][i];
   for(i=1; i<=imx; i++){          }
     for(mi=1; mi<wav[i];mi++){          for(jk=1; jk <=nlstate ; jk++){
       if (stepm <=0)            if(pos>=1.e-5){
         dh[mi][i]=1;              if(first==1)
       else{                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
           if (agedc[i] < 2*AGESUP) {            }else{
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);               if(first==1)
             if(j==0) j=1;  /* Survives at least one month after exam */                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
             else if(j<0){              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
               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]);            if( i <= iagemax){
               j=1; /* Temporary Dangerous patch */              if(pos>=1.e-5){
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview.\n  You MUST fix the contradiction between dates.\n",stepm);                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
               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]);                /*probs[i][jk][j1]= pp[jk]/pos;*/
               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);                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
             }              }
             k=k+1;              else
             if (j >= jmax) jmax=j;                fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
             if (j <= jmin) jmin=j;            }
             sum=sum+j;          }
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/         
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/          for(jk=-1; jk <=nlstate+ndeath; jk++)
           }            for(m=-1; m <=nlstate+ndeath; m++)
         }              if(freq[jk][m][i] !=0 ) {
         else{              if(first==1)
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
           /*      printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
           k=k+1;              }
           if (j >= jmax) jmax=j;          if(i <= iagemax)
           else if (j <= jmin)jmin=j;            fprintf(ficresp,"\n");
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */          if(first==1)
           /*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]);*/            printf("Others in log...\n");
           if(j<0){          fprintf(ficlog,"\n");
             nberr++;        }
             printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);      }
             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]);    }
           }    dateintmean=dateintsum/k2cpt;
           sum=sum+j;   
         }    fclose(ficresp);
         jk= j/stepm;    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
         jl= j -jk*stepm;    free_vector(pp,1,nlstate);
         ju= j -(jk+1)*stepm;    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */    /* End of Freq */
           if(jl==0){  }
             dh[mi][i]=jk;  
             bh[mi][i]=0;  /************ Prevalence ********************/
           }else{ /* We want a negative bias in order to only have interpolation ie  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)
                   * at the price of an extra matrix product in likelihood */  {  
             dh[mi][i]=jk+1;    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
             bh[mi][i]=ju;       in each health status at the date of interview (if between dateprev1 and dateprev2).
           }       We still use firstpass and lastpass as another selection.
         }else{    */
           if(jl <= -ju){   
             dh[mi][i]=jk;    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
             bh[mi][i]=jl;       /* bias is positive if real duration    double ***freq; /* Frequencies */
                                  * is higher than the multiple of stepm and negative otherwise.    double *pp, **prop;
                                  */    double pos,posprop;
           }    double  y2; /* in fractional years */
           else{    int iagemin, iagemax;
             dh[mi][i]=jk+1;  
             bh[mi][i]=ju;    iagemin= (int) agemin;
           }    iagemax= (int) agemax;
           if(dh[mi][i]==0){    /*pp=vector(1,nlstate);*/
             dh[mi][i]=1; /* At least one step */    prop=matrix(1,nlstate,iagemin,iagemax+3);
             bh[mi][i]=ju; /* At least one step */    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
             /*  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);*/    j1=0;
           }   
         } /* end if mle */    j=cptcoveff;
       }    if (cptcovn<1) {j=1;ncodemax[1]=1;}
     } /* end wave */   
   }    for(k1=1; k1<=j;k1++){
   jmean=sum/k;      for(i1=1; i1<=ncodemax[k1];i1++){
   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);        j1++;
   fprintf(ficlog,"Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);       
  }        for (i=1; i<=nlstate; i++)  
           for(m=iagemin; m <= iagemax+3; m++)
 /*********** Tricode ****************************/            prop[i][m]=0.0;
 void tricode(int *Tvar, int **nbcode, int imx)       
 {        for (i=1; i<=imx; i++) { /* Each individual */
             bool=1;
   int Ndum[20],ij=1, k, j, i, maxncov=19;          if  (cptcovn>0) {
   int cptcode=0;            for (z1=1; z1<=cptcoveff; z1++)
   cptcoveff=0;               if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
                  bool=0;
   for (k=0; k<maxncov; k++) Ndum[k]=0;          }
   for (k=1; k<=7; k++) ncodemax[k]=0;          if (bool==1) {
             for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {              y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum               if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                                modality*/                 if(agev[m][i]==0) agev[m][i]=iagemax+1;
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/                if(agev[m][i]==1) agev[m][i]=iagemax+2;
       Ndum[ij]++; /*store the modality */                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);
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/                if (s[m][i]>0 && s[m][i]<=nlstate) {
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable                   /*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]]);*/
                                        Tvar[j]. If V=sex and male is 0 and                   prop[s[m][i]][(int)agev[m][i]] += weight[i];
                                        female is 1, then  cptcode=1.*/                  prop[s[m][i]][iagemax+3] += weight[i];
     }                }
               }
     for (i=0; i<=cptcode; i++) {            } /* end selection of waves */
       if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */          }
     }        }
         for(i=iagemin; i <= iagemax+3; i++){  
     ij=1;          
     for (i=1; i<=ncodemax[j]; i++) {          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
       for (k=0; k<= maxncov; k++) {            posprop += prop[jk][i];
         if (Ndum[k] != 0) {          }
           nbcode[Tvar[j]][ij]=k;   
           /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */          for(jk=1; jk <=nlstate ; jk++){    
                       if( i <=  iagemax){
           ij++;              if(posprop>=1.e-5){
         }                probs[i][jk][j1]= prop[jk][i]/posprop;
         if (ij > ncodemax[j]) break;               }
       }              }
     }           }/* end jk */
   }          }/* end i */
       } /* end i1 */
  for (k=0; k< maxncov; k++) Ndum[k]=0;    } /* end k1 */
    
  for (i=1; i<=ncovmodel-2; i++) {     /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
    /* Listing of all covariables in staement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/    /*free_vector(pp,1,nlstate);*/
    ij=Tvar[i];    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
    Ndum[ij]++;  }  /* End of prevalence */
  }  
   /************* Waves Concatenation ***************/
  ij=1;  
  for (i=1; i<= maxncov; i++) {  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)
    if((Ndum[i]!=0) && (i<=ncovcol)){  {
      Tvaraff[ij]=i; /*For printing */    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
      ij++;       Death is a valid wave (if date is known).
    }       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]
         and mw[mi+1][i]. dh depends on stepm.
  cptcoveff=ij-1; /*Number of simple covariates*/       */
 }  
     int i, mi, m;
 /*********** Health Expectancies ****************/    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
        double sum=0., jmean=0.;*/
 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 )    int first;
     int j, k=0,jk, ju, jl;
 {    double sum=0.;
   /* Health expectancies */    first=0;
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;    jmin=1e+5;
   double age, agelim, hf;    jmax=-1;
   double ***p3mat,***varhe;    jmean=0.;
   double **dnewm,**doldm;    for(i=1; i<=imx; i++){
   double *xp;      mi=0;
   double **gp, **gm;      m=firstpass;
   double ***gradg, ***trgradg;      while(s[m][i] <= nlstate){
   int theta;        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
           mw[++mi][i]=m;
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);        if(m >=lastpass)
   xp=vector(1,npar);          break;
   dnewm=matrix(1,nlstate*nlstate,1,npar);        else
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);          m++;
         }/* end while */
   fprintf(ficreseij,"# Health expectancies\n");      if (s[m][i] > nlstate){
   fprintf(ficreseij,"# Age");        mi++;     /* Death is another wave */
   for(i=1; i<=nlstate;i++)        /* if(mi==0)  never been interviewed correctly before death */
     for(j=1; j<=nlstate;j++)           /* Only death is a correct wave */
       fprintf(ficreseij," %1d-%1d (SE)",i,j);        mw[mi][i]=m;
   fprintf(ficreseij,"\n");      }
   
   if(estepm < stepm){      wav[i]=mi;
     printf ("Problem %d lower than %d\n",estepm, stepm);      if(mi==0){
   }        nbwarn++;
   else  hstepm=estepm;           if(first==0){
   /* We compute the life expectancy from trapezoids spaced every estepm months          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
    * This is mainly to measure the difference between two models: for example          first=1;
    * 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         if(first==1){
    * progression in between and thus overestimating or underestimating according          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
    * to the curvature of the survival function. If, for the same date, we         }
    * estimate the model with stepm=1 month, we can keep estepm to 24 months      } /* end mi==0 */
    * to compare the new estimate of Life expectancy with the same linear     } /* End individuals */
    * hypothesis. A more precise result, taking into account a more precise  
    * curvature will be obtained if estepm is as small as stepm. */    for(i=1; i<=imx; i++){
       for(mi=1; mi<wav[i];mi++){
   /* For example we decided to compute the life expectancy with the smallest unit */        if (stepm <=0)
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.           dh[mi][i]=1;
      nhstepm is the number of hstepm from age to agelim         else{
      nstepm is the number of stepm from age to agelin.           if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
      Look at hpijx to understand the reason of that which relies in memory size            if (agedc[i] < 2*AGESUP) {
      and note for a fixed period like estepm months */              j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the              if(j==0) j=1;  /* Survives at least one month after exam */
      survival function given by stepm (the optimization length). Unfortunately it              else if(j<0){
      means that if the survival funtion is printed only each two years of age and if                nberr++;
      you sum them up and add 1 year (area under the trapezoids) you won't get the same                 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]);
      results. So we changed our mind and took the option of the best precision.                j=1; /* Temporary Dangerous patch */
   */                printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */                 fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                 fprintf(ficlog,"   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);
   agelim=AGESUP;              }
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */              k=k+1;
     /* nhstepm age range expressed in number of stepm */              if (j >= jmax){
     nstepm=(int) rint((agelim-age)*YEARM/stepm);                 jmax=j;
     /* Typically if 20 years nstepm = 20*12/6=40 stepm */                 ijmax=i;
     /* if (stepm >= YEARM) hstepm=1;*/              }
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */              if (j <= jmin){
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                jmin=j;
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);                ijmin=i;
     gp=matrix(0,nhstepm,1,nlstate*nlstate);              }
     gm=matrix(0,nhstepm,1,nlstate*nlstate);              sum=sum+j;
               /*if (j<0) printf("j=%d num=%d \n",j,i);*/
     /* Computed by stepm unit matrices, product of hstepm matrices, stored              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */            }
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);            }
            else{
             j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */  /*        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]); */
   
     /* Computing  Variances of health expectancies */            k=k+1;
             if (j >= jmax) {
      for(theta=1; theta <=npar; theta++){              jmax=j;
       for(i=1; i<=npar; i++){               ijmax=i;
         xp[i] = x[i] + (i==theta ?delti[theta]:0);            }
       }            else if (j <= jmin){
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);                jmin=j;
                 ijmin=i;
       cptj=0;            }
       for(j=1; j<= nlstate; j++){            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
         for(i=1; i<=nlstate; i++){            /*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]);*/
           cptj=cptj+1;            if(j<0){
           for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){              nberr++;
             gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;              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,"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;
                }
                jk= j/stepm;
       for(i=1; i<=npar; i++)           jl= j -jk*stepm;
         xp[i] = x[i] - (i==theta ?delti[theta]:0);          ju= j -(jk+1)*stepm;
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);            if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   if(jl==0){
       cptj=0;              dh[mi][i]=jk;
       for(j=1; j<= nlstate; j++){              bh[mi][i]=0;
         for(i=1;i<=nlstate;i++){            }else{ /* We want a negative bias in order to only have interpolation ie
           cptj=cptj+1;                    * at the price of an extra matrix product in likelihood */
           for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){              dh[mi][i]=jk+1;
               bh[mi][i]=ju;
             gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;            }
           }          }else{
         }            if(jl <= -ju){
       }              dh[mi][i]=jk;
       for(j=1; j<= nlstate*nlstate; j++)              bh[mi][i]=jl;       /* bias is positive if real duration
         for(h=0; h<=nhstepm-1; h++){                                   * is higher than the multiple of stepm and negative otherwise.
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];                                   */
         }            }
      }             else{
                  dh[mi][i]=jk+1;
 /* End theta */              bh[mi][i]=ju;
             }
      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);            if(dh[mi][i]==0){
               dh[mi][i]=1; /* At least one step */
      for(h=0; h<=nhstepm-1; h++)              bh[mi][i]=ju; /* At least one step */
       for(j=1; j<=nlstate*nlstate;j++)              /*  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);*/
         for(theta=1; theta <=npar; theta++)            }
           trgradg[h][j][theta]=gradg[h][theta][j];          } /* end if mle */
              }
       } /* end wave */
      for(i=1;i<=nlstate*nlstate;i++)    }
       for(j=1;j<=nlstate*nlstate;j++)    jmean=sum/k;
         varhe[i][j][(int)age] =0.;    printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);
     fprintf(ficlog,"Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, ijmin, jmax, ijmax, jmean);
      printf("%d|",(int)age);fflush(stdout);   }
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);  
      for(h=0;h<=nhstepm-1;h++){  /*********** Tricode ****************************/
       for(k=0;k<=nhstepm-1;k++){  void tricode(int *Tvar, int **nbcode, int imx)
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);  {
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);   
         for(i=1;i<=nlstate*nlstate;i++)    int Ndum[20],ij=1, k, j, i, maxncov=19;
           for(j=1;j<=nlstate*nlstate;j++)    int cptcode=0;
             varhe[i][j][(int)age] += doldm[i][j]*hf*hf;    cptcoveff=0;
       }   
     }    for (k=0; k<maxncov; k++) Ndum[k]=0;
     /* Computing expectancies */    for (k=1; k<=7; k++) ncodemax[k]=0;
     for(i=1; i<=nlstate;i++)  
       for(j=1; j<=nlstate;j++)    for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){      for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;                                 modality*/
                   ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
 /* 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]);*/        Ndum[ij]++; /*store the modality */
         /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
         }        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
                                          Tvar[j]. If V=sex and male is 0 and
     fprintf(ficreseij,"%3.0f",age );                                         female is 1, then  cptcode=1.*/
     cptj=0;      }
     for(i=1; i<=nlstate;i++)  
       for(j=1; j<=nlstate;j++){      for (i=0; i<=cptcode; i++) {
         cptj++;        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 */
         fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );      }
       }  
     fprintf(ficreseij,"\n");      ij=1;
          for (i=1; i<=ncodemax[j]; i++) {
     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);        for (k=0; k<= maxncov; k++) {
     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);          if (Ndum[k] != 0) {
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);            nbcode[Tvar[j]][ij]=k;
     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);            /* 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; */
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);           
   }            ij++;
   printf("\n");          }
   fprintf(ficlog,"\n");          if (ij > ncodemax[j]) break;
         }  
   free_vector(xp,1,npar);      }
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);    }  
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);  
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);   for (k=0; k< maxncov; k++) Ndum[k]=0;
 }  
    for (i=1; i<=ncovmodel-2; i++) {
 /************ Variance ******************/     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
 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)     ij=Tvar[i];
 {     Ndum[ij]++;
   /* Variance of health expectancies */   }
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/  
   /* double **newm;*/   ij=1;
   double **dnewm,**doldm;   for (i=1; i<= maxncov; i++) {
   double **dnewmp,**doldmp;     if((Ndum[i]!=0) && (i<=ncovcol)){
   int i, j, nhstepm, hstepm, h, nstepm ;       Tvaraff[ij]=i; /*For printing */
   int k, cptcode;       ij++;
   double *xp;     }
   double **gp, **gm;  /* for var eij */   }
   double ***gradg, ***trgradg; /*for var eij */   
   double **gradgp, **trgradgp; /* for var p point j */   cptcoveff=ij-1; /*Number of simple covariates*/
   double *gpp, *gmp; /* for var p point j */  }
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */  
   double ***p3mat;  /*********** Health Expectancies ****************/
   double age,agelim, hf;  
   double ***mobaverage;  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[] )
   int theta;  
   char digit[4];  {
   char digitp[25];    /* Health expectancies, no variances */
     int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
   char fileresprobmorprev[FILENAMELENGTH];    double age, agelim, hf;
     double ***p3mat;
   if(popbased==1){    double eip;
     if(mobilav!=0)  
       strcpy(digitp,"-populbased-mobilav-");    pstamp(ficreseij);
     else strcpy(digitp,"-populbased-nomobil-");    fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
   }    fprintf(ficreseij,"# Age");
   else     for(i=1; i<=nlstate;i++){
     strcpy(digitp,"-stablbased-");      for(j=1; j<=nlstate;j++){
         fprintf(ficreseij," e%1d%1d ",i,j);
   if (mobilav!=0) {      }
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      fprintf(ficreseij," e%1d. ",i);
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){    }
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    fprintf(ficreseij,"\n");
       printf(" Error in movingaverage mobilav=%d\n",mobilav);  
     }   
   }    if(estepm < stepm){
       printf ("Problem %d lower than %d\n",estepm, stepm);
   strcpy(fileresprobmorprev,"prmorprev");     }
   sprintf(digit,"%-d",ij);    else  hstepm=estepm;  
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/    /* We compute the life expectancy from trapezoids spaced every estepm months
   strcat(fileresprobmorprev,digit); /* Tvar to be done */     * This is mainly to measure the difference between two models: for example
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */     * if stepm=24 months pijx are given only every 2 years and by summing them
   strcat(fileresprobmorprev,fileres);     * we are calculating an estimate of the Life Expectancy assuming a linear
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {     * progression in between and thus overestimating or underestimating according
     printf("Problem with resultfile: %s\n", fileresprobmorprev);     * to the curvature of the survival function. If, for the same date, we
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);     * 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
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);     * hypothesis. A more precise result, taking into account a more precise
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);     * curvature will be obtained if estepm is as small as stepm. */
   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(ficresprobmorprev,"# Age cov=%-d",ij);    /* For example we decided to compute the life expectancy with the smallest unit */
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
     fprintf(ficresprobmorprev," p.%-d SE",j);       nhstepm is the number of hstepm from age to agelim
     for(i=1; i<=nlstate;i++)       nstepm is the number of stepm from age to agelin.
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);       Look at hpijx to understand the reason of that which relies in memory size
   }         and note for a fixed period like estepm months */
   fprintf(ficresprobmorprev,"\n");    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   fprintf(ficgp,"\n# Routine varevsij");       survival function given by stepm (the optimization length). Unfortunately it
   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");       means that if the survival funtion is printed only each two years of age and if
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);       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.
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    */
     hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are the stable prevalence in health states i\n");  
   fprintf(ficresvij,"# Age");    agelim=AGESUP;
   for(i=1; i<=nlstate;i++)    /* If stepm=6 months */
     for(j=1; j<=nlstate;j++)      /* Computed by stepm unit matrices, product of hstepm matrices, stored
       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
   fprintf(ficresvij,"\n");     
   /* nhstepm age range expressed in number of stepm */
   xp=vector(1,npar);    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
   dnewm=matrix(1,nlstate,1,npar);    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
   doldm=matrix(1,nlstate,1,nlstate);    /* if (stepm >= YEARM) hstepm=1;*/
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);    for (age=bage; age<=fage; age ++){
   gpp=vector(nlstate+1,nlstate+ndeath);  
   gmp=vector(nlstate+1,nlstate+ndeath);  
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
        
   if(estepm < stepm){      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     printf ("Problem %d lower than %d\n",estepm, stepm);     
   }      printf("%d|",(int)age);fflush(stdout);
   else  hstepm=estepm;         fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
   /* For example we decided to compute the life expectancy with the smallest unit */     
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.   
      nhstepm is the number of hstepm from age to agelim       /* Computing expectancies */
      nstepm is the number of stepm from age to agelin.       for(i=1; i<=nlstate;i++)
      Look at hpijx to understand the reason of that which relies in memory size        for(j=1; j<=nlstate;j++)
      and note for a fixed period like k years */          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
      survival function given by stepm (the optimization length). Unfortunately it           
      means that if the survival funtion is printed every two years of age and if            /*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]);*/
      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.          }
   */     
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */       fprintf(ficreseij,"%3.0f",age );
   agelim = AGESUP;      for(i=1; i<=nlstate;i++){
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */        eip=0;
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */         for(j=1; j<=nlstate;j++){
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */          eip +=eij[i][j][(int)age];
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);        }
     gp=matrix(0,nhstepm,1,nlstate);        fprintf(ficreseij,"%9.4f", eip );
     gm=matrix(0,nhstepm,1,nlstate);      }
       fprintf(ficreseij,"\n");
      
     for(theta=1; theta <=npar; theta++){    }
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    printf("\n");
       }    fprintf(ficlog,"\n");
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);     
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);  }
   
       if (popbased==1) {  void cvevsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
         if(mobilav ==0){  
           for(i=1; i<=nlstate;i++)  {
             prlim[i][i]=probs[(int)age][i][ij];    /* Covariances of health expectancies eij and of total life expectancies according
         }else{ /* mobilav */      to initial status i, ei. .
           for(i=1; i<=nlstate;i++)    */
             prlim[i][i]=mobaverage[(int)age][i][ij];    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
         }    double age, agelim, hf;
       }    double ***p3matp, ***p3matm, ***varhe;
       double **dnewm,**doldm;
       for(j=1; j<= nlstate; j++){    double *xp, *xm;
         for(h=0; h<=nhstepm; h++){    double **gp, **gm;
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)    double ***gradg, ***trgradg;
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];    int theta;
         }  
       }    double eip, vip;
       /* This for computing probability of death (h=1 means  
          computed over hstepm matrices product = hstepm*stepm months)     varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
          as a weighted average of prlim.    xp=vector(1,npar);
       */    xm=vector(1,npar);
       for(j=nlstate+1;j<=nlstate+ndeath;j++){    dnewm=matrix(1,nlstate*nlstate,1,npar);
         for(i=1,gpp[j]=0.; i<= nlstate; i++)    doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
           gpp[j] += prlim[i][i]*p3mat[i][j][1];   
       }        pstamp(ficresstdeij);
       /* end probability of death */    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
     fprintf(ficresstdeij,"# Age");
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */    for(i=1; i<=nlstate;i++){
         xp[i] = x[i] - (i==theta ?delti[theta]:0);      for(j=1; j<=nlstate;j++)
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);          fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      fprintf(ficresstdeij," e%1d. ",i);
      }
       if (popbased==1) {    fprintf(ficresstdeij,"\n");
         if(mobilav ==0){  
           for(i=1; i<=nlstate;i++)    pstamp(ficrescveij);
             prlim[i][i]=probs[(int)age][i][ij];    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
         }else{ /* mobilav */     fprintf(ficrescveij,"# Age");
           for(i=1; i<=nlstate;i++)    for(i=1; i<=nlstate;i++)
             prlim[i][i]=mobaverage[(int)age][i][ij];      for(j=1; j<=nlstate;j++){
         }        cptj= (j-1)*nlstate+i;
       }        for(i2=1; i2<=nlstate;i2++)
           for(j2=1; j2<=nlstate;j2++){
       for(j=1; j<= nlstate; j++){            cptj2= (j2-1)*nlstate+i2;
         for(h=0; h<=nhstepm; h++){            if(cptj2 <= cptj)
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];          }
         }      }
       }    fprintf(ficrescveij,"\n");
       /* This for computing probability of death (h=1 means   
          computed over hstepm matrices product = hstepm*stepm months)     if(estepm < stepm){
          as a weighted average of prlim.      printf ("Problem %d lower than %d\n",estepm, stepm);
       */    }
       for(j=nlstate+1;j<=nlstate+ndeath;j++){    else  hstepm=estepm;  
         for(i=1,gmp[j]=0.; i<= nlstate; i++)    /* We compute the life expectancy from trapezoids spaced every estepm months
          gmp[j] += prlim[i][i]*p3mat[i][j][1];     * This is mainly to measure the difference between two models: for example
       }         * if stepm=24 months pijx are given only every 2 years and by summing them
       /* end probability of death */     * we are calculating an estimate of the Life Expectancy assuming a linear
      * progression in between and thus overestimating or underestimating according
       for(j=1; j<= nlstate; j++) /* vareij */     * to the curvature of the survival function. If, for the same date, we
         for(h=0; h<=nhstepm; h++){     * estimate the model with stepm=1 month, we can keep estepm to 24 months
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];     * to compare the new estimate of Life expectancy with the same linear
         }     * hypothesis. A more precise result, taking into account a more precise
      * curvature will be obtained if estepm is as small as stepm. */
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */  
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];    /* For example we decided to compute the life expectancy with the smallest unit */
       }    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
        nhstepm is the number of hstepm from age to agelim
     } /* End theta */       nstepm is the number of stepm from age to agelin.
        Look at hpijx to understand the reason of that which relies in memory size
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */       and note for a fixed period like estepm months */
     /* We decided (b) to get a life expectancy respecting the most precise curvature of the
     for(h=0; h<=nhstepm; h++) /* veij */       survival function given by stepm (the optimization length). Unfortunately it
       for(j=1; j<=nlstate;j++)       means that if the survival funtion is printed only each two years of age and if
         for(theta=1; theta <=npar; theta++)       you sum them up and add 1 year (area under the trapezoids) you won't get the same
           trgradg[h][j][theta]=gradg[h][theta][j];       results. So we changed our mind and took the option of the best precision.
     */
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
       for(theta=1; theta <=npar; theta++)  
         trgradgp[j][theta]=gradgp[theta][j];    /* If stepm=6 months */
       /* nhstepm age range expressed in number of stepm */
     agelim=AGESUP;
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
     for(i=1;i<=nlstate;i++)    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
       for(j=1;j<=nlstate;j++)    /* if (stepm >= YEARM) hstepm=1;*/
         vareij[i][j][(int)age] =0.;    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
    
     for(h=0;h<=nhstepm;h++){    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       for(k=0;k<=nhstepm;k++){    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);    gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
         for(i=1;i<=nlstate;i++)    gp=matrix(0,nhstepm,1,nlstate*nlstate);
           for(j=1;j<=nlstate;j++)    gm=matrix(0,nhstepm,1,nlstate*nlstate);
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;  
       }    for (age=bage; age<=fage; age ++){
     }  
         /* Computed by stepm unit matrices, product of hstepm matrices, stored
     /* pptj */         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
     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);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     for(j=nlstate+1;j<=nlstate+ndeath;j++)  
       for(i=nlstate+1;i<=nlstate+ndeath;i++)      /* Computing  Variances of health expectancies */
         varppt[j][i]=doldmp[j][i];      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
     /* end ppptj */         decrease memory allocation */
     /*  x centered again */      for(theta=1; theta <=npar; theta++){
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);          for(i=1; i<=npar; i++){
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
            xm[i] = x[i] - (i==theta ?delti[theta]:0);
     if (popbased==1) {        }
       if(mobilav ==0){        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
         for(i=1; i<=nlstate;i++)        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
           prlim[i][i]=probs[(int)age][i][ij];   
       }else{ /* mobilav */         for(j=1; j<= nlstate; j++){
         for(i=1; i<=nlstate;i++)          for(i=1; i<=nlstate; i++){
           prlim[i][i]=mobaverage[(int)age][i][ij];            for(h=0; h<=nhstepm-1; h++){
       }              gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
     }              gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                          }
     /* This for computing probability of death (h=1 means          }
        computed over hstepm (estepm) matrices product = hstepm*stepm months)         }
        as a weighted average of prlim.       
     */        for(ij=1; ij<= nlstate*nlstate; ij++)
     for(j=nlstate+1;j<=nlstate+ndeath;j++){          for(h=0; h<=nhstepm-1; h++){
       for(i=1,gmp[j]=0.;i<= nlstate; i++)             gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
         gmp[j] += prlim[i][i]*p3mat[i][j][1];           }
     }          }/* End theta */
     /* end probability of death */     
      
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);      for(h=0; h<=nhstepm-1; h++)
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){        for(j=1; j<=nlstate*nlstate;j++)
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));          for(theta=1; theta <=npar; theta++)
       for(i=1; i<=nlstate;i++){            trgradg[h][j][theta]=gradg[h][theta][j];
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);     
       }  
     }        for(ij=1;ij<=nlstate*nlstate;ij++)
     fprintf(ficresprobmorprev,"\n");        for(ji=1;ji<=nlstate*nlstate;ji++)
           varhe[ij][ji][(int)age] =0.;
     fprintf(ficresvij,"%.0f ",age );  
     for(i=1; i<=nlstate;i++)       printf("%d|",(int)age);fflush(stdout);
       for(j=1; j<=nlstate;j++){       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);       for(h=0;h<=nhstepm-1;h++){
       }        for(k=0;k<=nhstepm-1;k++){
     fprintf(ficresvij,"\n");          matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
     free_matrix(gp,0,nhstepm,1,nlstate);          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
     free_matrix(gm,0,nhstepm,1,nlstate);          for(ij=1;ij<=nlstate*nlstate;ij++)
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);            for(ji=1;ji<=nlstate*nlstate;ji++)
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        }
   } /* End age */      }
   free_vector(gpp,nlstate+1,nlstate+ndeath);  
   free_vector(gmp,nlstate+1,nlstate+ndeath);      /* Computing expectancies */
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/      for(i=1; i<=nlstate;i++)
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");        for(j=1; j<=nlstate;j++)
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */           
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */            /* 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]);*/
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */  
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));          }
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));  
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));      fprintf(ficresstdeij,"%3.0f",age );
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));      for(i=1; i<=nlstate;i++){
   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);        eip=0.;
   /*  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);        vip=0.;
 */        for(j=1; j<=nlstate;j++){
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */          eip += eij[i][j][(int)age];
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
             vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
   free_vector(xp,1,npar);          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
   free_matrix(doldm,1,nlstate,1,nlstate);        }
   free_matrix(dnewm,1,nlstate,1,npar);        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);      }
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);      fprintf(ficresstdeij,"\n");
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);  
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      fprintf(ficrescveij,"%3.0f",age );
   fclose(ficresprobmorprev);      for(i=1; i<=nlstate;i++)
   fflush(ficgp);        for(j=1; j<=nlstate;j++){
   fflush(fichtm);           cptj= (j-1)*nlstate+i;
 }  /* end varevsij */          for(i2=1; i2<=nlstate;i2++)
             for(j2=1; j2<=nlstate;j2++){
 /************ Variance of prevlim ******************/              cptj2= (j2-1)*nlstate+i2;
 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)              if(cptj2 <= cptj)
 {                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
   /* Variance of prevalence limit */            }
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/        }
   double **newm;      fprintf(ficrescveij,"\n");
   double **dnewm,**doldm;     
   int i, j, nhstepm, hstepm;    }
   int k, cptcode;    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
   double *xp;    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
   double *gp, *gm;    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
   double **gradg, **trgradg;    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
   double age,agelim;    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int theta;    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        printf("\n");
   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");    fprintf(ficlog,"\n");
   fprintf(ficresvpl,"# Age");  
   for(i=1; i<=nlstate;i++)    free_vector(xm,1,npar);
       fprintf(ficresvpl," %1d-%1d",i,i);    free_vector(xp,1,npar);
   fprintf(ficresvpl,"\n");    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
     free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
   xp=vector(1,npar);    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
   dnewm=matrix(1,nlstate,1,npar);  }
   doldm=matrix(1,nlstate,1,nlstate);  
     /************ Variance ******************/
   hstepm=1*YEARM; /* Every year of age */  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[])
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */   {
   agelim = AGESUP;    /* Variance of health expectancies */
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     /* double **newm;*/
     if (stepm >= YEARM) hstepm=1;    double **dnewm,**doldm;
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */    double **dnewmp,**doldmp;
     gradg=matrix(1,npar,1,nlstate);    int i, j, nhstepm, hstepm, h, nstepm ;
     gp=vector(1,nlstate);    int k, cptcode;
     gm=vector(1,nlstate);    double *xp;
     double **gp, **gm;  /* for var eij */
     for(theta=1; theta <=npar; theta++){    double ***gradg, ***trgradg; /*for var eij */
       for(i=1; i<=npar; i++){ /* Computes gradient */    double **gradgp, **trgradgp; /* for var p point j */
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    double *gpp, *gmp; /* for var p point j */
       }    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    double ***p3mat;
       for(i=1;i<=nlstate;i++)    double age,agelim, hf;
         gp[i] = prlim[i][i];    double ***mobaverage;
         int theta;
       for(i=1; i<=npar; i++) /* Computes gradient */    char digit[4];
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    char digitp[25];
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);  
       for(i=1;i<=nlstate;i++)    char fileresprobmorprev[FILENAMELENGTH];
         gm[i] = prlim[i][i];  
     if(popbased==1){
       for(i=1;i<=nlstate;i++)      if(mobilav!=0)
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];        strcpy(digitp,"-populbased-mobilav-");
     } /* End theta */      else strcpy(digitp,"-populbased-nomobil-");
     }
     trgradg =matrix(1,nlstate,1,npar);    else
       strcpy(digitp,"-stablbased-");
     for(j=1; j<=nlstate;j++)  
       for(theta=1; theta <=npar; theta++)    if (mobilav!=0) {
         trgradg[j][theta]=gradg[theta][j];      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
     for(i=1;i<=nlstate;i++)        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
       varpl[i][(int)age] =0.;        printf(" Error in movingaverage mobilav=%d\n",mobilav);
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);      }
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);    }
     for(i=1;i<=nlstate;i++)  
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */    strcpy(fileresprobmorprev,"prmorprev");
     sprintf(digit,"%-d",ij);
     fprintf(ficresvpl,"%.0f ",age );    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
     for(i=1; i<=nlstate;i++)    strcat(fileresprobmorprev,digit); /* Tvar to be done */
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
     fprintf(ficresvpl,"\n");    strcat(fileresprobmorprev,fileres);
     free_vector(gp,1,nlstate);    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
     free_vector(gm,1,nlstate);      printf("Problem with resultfile: %s\n", fileresprobmorprev);
     free_matrix(gradg,1,npar,1,nlstate);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
     free_matrix(trgradg,1,nlstate,1,npar);    }
   } /* End age */    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
    
   free_vector(xp,1,npar);    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   free_matrix(doldm,1,nlstate,1,npar);    pstamp(ficresprobmorprev);
   free_matrix(dnewm,1,nlstate,1,nlstate);    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(ficresprobmorprev,"# Age cov=%-d",ij);
 }    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
       fprintf(ficresprobmorprev," p.%-d SE",j);
 /************ Variance of one-step probabilities  ******************/      for(i=1; i<=nlstate;i++)
 void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax)        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 {    }  
   int i, j=0,  i1, k1, l1, t, tj;    fprintf(ficresprobmorprev,"\n");
   int k2, l2, j1,  z1;    fprintf(ficgp,"\n# Routine varevsij");
   int k=0,l, cptcode;    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   int first=1, first1;    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");
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
   double **dnewm,**doldm;  /*   } */
   double *xp;    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   double *gp, *gm;    pstamp(ficresvij);
   double **gradg, **trgradg;    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
   double **mu;    if(popbased==1)
   double age,agelim, cov[NCOVMAX];      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */    else
   int theta;      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
   char fileresprob[FILENAMELENGTH];    fprintf(ficresvij,"# Age");
   char fileresprobcov[FILENAMELENGTH];    for(i=1; i<=nlstate;i++)
   char fileresprobcor[FILENAMELENGTH];      for(j=1; j<=nlstate;j++)
         fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
   double ***varpij;    fprintf(ficresvij,"\n");
   
   strcpy(fileresprob,"prob");     xp=vector(1,npar);
   strcat(fileresprob,fileres);    dnewm=matrix(1,nlstate,1,npar);
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {    doldm=matrix(1,nlstate,1,nlstate);
     printf("Problem with resultfile: %s\n", fileresprob);    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   }  
   strcpy(fileresprobcov,"probcov");     gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
   strcat(fileresprobcov,fileres);    gpp=vector(nlstate+1,nlstate+ndeath);
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {    gmp=vector(nlstate+1,nlstate+ndeath);
     printf("Problem with resultfile: %s\n", fileresprobcov);    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);   
   }    if(estepm < stepm){
   strcpy(fileresprobcor,"probcor");       printf ("Problem %d lower than %d\n",estepm, stepm);
   strcat(fileresprobcor,fileres);    }
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {    else  hstepm=estepm;  
     printf("Problem with resultfile: %s\n", fileresprobcor);    /* For example we decided to compute the life expectancy with the smallest unit */
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);    /* 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
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);       nstepm is the number of stepm from age to agelin.
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);       Look at hpijx to understand the reason of that which relies in memory size
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);       and note for a fixed period like k years */
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);       survival function given by stepm (the optimization length). Unfortunately it
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);       means that if the survival funtion is printed every two years of age and if
          you sum them up and add 1 year (area under the trapezoids) you won't get the same
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");       results. So we changed our mind and took the option of the best precision.
   fprintf(ficresprob,"# Age");    */
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   fprintf(ficresprobcov,"# Age");    agelim = AGESUP;
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
   fprintf(ficresprobcov,"# Age");      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
       nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   for(i=1; i<=nlstate;i++)      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
     for(j=1; j<=(nlstate+ndeath);j++){      gp=matrix(0,nhstepm,1,nlstate);
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);      gm=matrix(0,nhstepm,1,nlstate);
       fprintf(ficresprobcov," p%1d-%1d ",i,j);  
       fprintf(ficresprobcor," p%1d-%1d ",i,j);  
     }        for(theta=1; theta <=npar; theta++){
  /* fprintf(ficresprob,"\n");        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
   fprintf(ficresprobcov,"\n");          xp[i] = x[i] + (i==theta ?delti[theta]:0);
   fprintf(ficresprobcor,"\n");        }
  */        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
  xp=vector(1,npar);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);  
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));        if (popbased==1) {
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);          if(mobilav ==0){
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);            for(i=1; i<=nlstate;i++)
   first=1;              prlim[i][i]=probs[(int)age][i][ij];
   fprintf(ficgp,"\n# Routine varprob");          }else{ /* mobilav */
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");            for(i=1; i<=nlstate;i++)
   fprintf(fichtm,"\n");              prlim[i][i]=mobaverage[(int)age][i][ij];
           }
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);        }
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\   
   file %s<br>\n",optionfilehtmcov);        for(j=1; j<= nlstate; j++){
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\          for(h=0; h<=nhstepm; h++){
 and drawn. It helps understanding how is the covariance between two incidences.\            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");              gp[h][j] += prlim[i][i]*p3mat[i][j][h];
   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 \        }
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \        /* This for computing probability of death (h=1 means
 standard deviations wide on each axis. <br>\           computed over hstepm matrices product = hstepm*stepm months)
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\           as a weighted average of prlim.
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\        */
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");        for(j=nlstate+1;j<=nlstate+ndeath;j++){
           for(i=1,gpp[j]=0.; i<= nlstate; i++)
   cov[1]=1;            gpp[j] += prlim[i][i]*p3mat[i][j][1];
   tj=cptcoveff;        }    
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}        /* end probability of death */
   j1=0;  
   for(t=1; t<=tj;t++){        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
     for(i1=1; i1<=ncodemax[t];i1++){           xp[i] = x[i] - (i==theta ?delti[theta]:0);
       j1++;        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
       if  (cptcovn>0) {        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         fprintf(ficresprob, "\n#********** Variable ");    
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);        if (popbased==1) {
         fprintf(ficresprob, "**********\n#\n");          if(mobilav ==0){
         fprintf(ficresprobcov, "\n#********** Variable ");             for(i=1; i<=nlstate;i++)
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);              prlim[i][i]=probs[(int)age][i][ij];
         fprintf(ficresprobcov, "**********\n#\n");          }else{ /* mobilav */
                     for(i=1; i<=nlstate;i++)
         fprintf(ficgp, "\n#********** Variable ");               prlim[i][i]=mobaverage[(int)age][i][ij];
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          }
         fprintf(ficgp, "**********\n#\n");        }
           
                 for(j=1; j<= nlstate; j++){
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");           for(h=0; h<=nhstepm; h++){
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   }
         fprintf(ficresprobcor, "\n#********** Variable ");            }
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);        /* This for computing probability of death (h=1 means
         fprintf(ficresprobcor, "**********\n#");               computed over hstepm matrices product = hstepm*stepm months)
       }           as a weighted average of prlim.
               */
       for (age=bage; age<=fage; age ++){         for(j=nlstate+1;j<=nlstate+ndeath;j++){
         cov[2]=age;          for(i=1,gmp[j]=0.; i<= nlstate; i++)
         for (k=1; k<=cptcovn;k++) {           gmp[j] += prlim[i][i]*p3mat[i][j][1];
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];        }    
         }        /* end probability of death */
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];  
         for (k=1; k<=cptcovprod;k++)        for(j=1; j<= nlstate; j++) /* vareij */
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];          for(h=0; h<=nhstepm; h++){
                     gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));          }
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);  
         gp=vector(1,(nlstate)*(nlstate+ndeath));        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
         gm=vector(1,(nlstate)*(nlstate+ndeath));          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
             }
         for(theta=1; theta <=npar; theta++){  
           for(i=1; i<=npar; i++)      } /* End theta */
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);  
                 trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
           pmij(pmmij,cov,ncovmodel,xp,nlstate);  
                 for(h=0; h<=nhstepm; h++) /* veij */
           k=0;        for(j=1; j<=nlstate;j++)
           for(i=1; i<= (nlstate); i++){          for(theta=1; theta <=npar; theta++)
             for(j=1; j<=(nlstate+ndeath);j++){            trgradg[h][j][theta]=gradg[h][theta][j];
               k=k+1;  
               gp[k]=pmmij[i][j];      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
             }        for(theta=1; theta <=npar; theta++)
           }          trgradgp[j][theta]=gradgp[theta][j];
              
           for(i=1; i<=npar; i++)  
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
           for(i=1;i<=nlstate;i++)
           pmij(pmmij,cov,ncovmodel,xp,nlstate);        for(j=1;j<=nlstate;j++)
           k=0;          vareij[i][j][(int)age] =0.;
           for(i=1; i<=(nlstate); i++){  
             for(j=1; j<=(nlstate+ndeath);j++){      for(h=0;h<=nhstepm;h++){
               k=k+1;        for(k=0;k<=nhstepm;k++){
               gm[k]=pmmij[i][j];          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
             }          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
           }          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] += doldm[i][j]*hf*hf;
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];          }
         }      }
    
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)      /* pptj */
           for(theta=1; theta <=npar; theta++)      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
             trgradg[j][theta]=gradg[theta][j];      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
               for(j=nlstate+1;j<=nlstate+ndeath;j++)
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);         for(i=nlstate+1;i<=nlstate+ndeath;i++)
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);          varppt[j][i]=doldmp[j][i];
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));      /* end ppptj */
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));      /*  x centered again */
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
    
         pmij(pmmij,cov,ncovmodel,x,nlstate);      if (popbased==1) {
                 if(mobilav ==0){
         k=0;          for(i=1; i<=nlstate;i++)
         for(i=1; i<=(nlstate); i++){            prlim[i][i]=probs[(int)age][i][ij];
           for(j=1; j<=(nlstate+ndeath);j++){        }else{ /* mobilav */
             k=k+1;          for(i=1; i<=nlstate;i++)
             mu[k][(int) age]=pmmij[i][j];            prlim[i][i]=mobaverage[(int)age][i][ij];
           }        }
         }      }
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)               
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)      /* This for computing probability of death (h=1 means
             varpij[i][j][(int)age] = doldm[i][j];         computed over hstepm (estepm) matrices product = hstepm*stepm months)
          as a weighted average of prlim.
         /*printf("\n%d ",(int)age);      */
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){      for(j=nlstate+1;j<=nlstate+ndeath;j++){
           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));        for(i=1,gmp[j]=0.;i<= nlstate; i++)
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));          gmp[j] += prlim[i][i]*p3mat[i][j][1];
           }*/      }    
       /* end probability of death */
         fprintf(ficresprob,"\n%d ",(int)age);  
         fprintf(ficresprobcov,"\n%d ",(int)age);      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
         fprintf(ficresprobcor,"\n%d ",(int)age);      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
         fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)        for(i=1; i<=nlstate;i++){
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){        }
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);      }
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);      fprintf(ficresprobmorprev,"\n");
         }  
         i=0;      fprintf(ficresvij,"%.0f ",age );
         for (k=1; k<=(nlstate);k++){      for(i=1; i<=nlstate;i++)
           for (l=1; l<=(nlstate+ndeath);l++){         for(j=1; j<=nlstate;j++){
             i=i++;          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);        }
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);      fprintf(ficresvij,"\n");
             for (j=1; j<=i;j++){      free_matrix(gp,0,nhstepm,1,nlstate);
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);      free_matrix(gm,0,nhstepm,1,nlstate);
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
             }      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
           }      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         }/* end of loop for state */    } /* End age */
       } /* end of loop for age */    free_vector(gpp,nlstate+1,nlstate+ndeath);
     free_vector(gmp,nlstate+1,nlstate+ndeath);
       /* Confidence intervalle of pij  */    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
       /*    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
         fprintf(ficgp,"\nset noparametric;unset label");    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");    fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
         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(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
       */    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
     fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
       /* Drawing ellipsoids of confidence of two variables p(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));
       first1=1;    fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
       for (k2=1; k2<=(nlstate);k2++){    /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);
         for (l2=1; l2<=(nlstate+ndeath);l2++){   */
           if(l2==k2) continue;  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
           j=(k2-1)*(nlstate+ndeath)+l2;    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
           for (k1=1; k1<=(nlstate);k1++){  
             for (l1=1; l1<=(nlstate+ndeath);l1++){     free_vector(xp,1,npar);
               if(l1==k1) continue;    free_matrix(doldm,1,nlstate,1,nlstate);
               i=(k1-1)*(nlstate+ndeath)+l1;    free_matrix(dnewm,1,nlstate,1,npar);
               if(i<=j) continue;    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
               for (age=bage; age<=fage; age ++){     free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                 if ((int)age %5==0){    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;    fclose(ficresprobmorprev);
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;    fflush(ficgp);
                   mu1=mu[i][(int) age]/stepm*YEARM ;    fflush(fichtm);
                   mu2=mu[j][(int) age]/stepm*YEARM;  }  /* end varevsij */
                   c12=cv12/sqrt(v1*v2);  
                   /* Computing eigen value of matrix of covariance */  /************ Variance of prevlim ******************/
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  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[])
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  {
                   /* Eigen vectors */    /* Variance of prevalence limit */
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   /*v21=sqrt(1.-v11*v11); *//* error */    double **newm;
                   v21=(lc1-v1)/cv12*v11;    double **dnewm,**doldm;
                   v12=-v21;    int i, j, nhstepm, hstepm;
                   v22=v11;    int k, cptcode;
                   tnalp=v21/v11;    double *xp;
                   if(first1==1){    double *gp, *gm;
                     first1=0;    double **gradg, **trgradg;
                     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);    double age,agelim;
                   }    int theta;
                   fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);   
                   /*printf(fignu*/    pstamp(ficresvpl);
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */    fprintf(ficresvpl,"# Age");
                   if(first==1){    for(i=1; i<=nlstate;i++)
                     first=0;        fprintf(ficresvpl," %1d-%1d",i,i);
                     fprintf(ficgp,"\nset parametric;unset label");    fprintf(ficresvpl,"\n");
                     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");    xp=vector(1,npar);
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\    dnewm=matrix(1,nlstate,1,npar);
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\    doldm=matrix(1,nlstate,1,nlstate);
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\   
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\    hstepm=1*YEARM; /* Every year of age */
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    agelim = AGESUP;
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);      if (stepm >= YEARM) hstepm=1;
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                     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",\      gradg=matrix(1,npar,1,nlstate);
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\      gp=vector(1,nlstate);
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));      gm=vector(1,nlstate);
                   }else{  
                     first=0;      for(theta=1; theta <=npar; theta++){
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);        for(i=1; i<=npar; i++){ /* Computes gradient */
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);        }
                     fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\        for(i=1;i<=nlstate;i++)
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));          gp[i] = prlim[i][i];
                   }/* if first */     
                 } /* age mod 5 */        for(i=1; i<=npar; i++) /* Computes gradient */
               } /* end loop age */          xp[i] = x[i] - (i==theta ?delti[theta]:0);
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
               first=1;        for(i=1;i<=nlstate;i++)
             } /*l12 */          gm[i] = prlim[i][i];
           } /* k12 */  
         } /*l1 */        for(i=1;i<=nlstate;i++)
       }/* k1 */          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
     } /* loop covariates */      } /* End theta */
   }  
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);      trgradg =matrix(1,nlstate,1,npar);
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);  
   free_vector(xp,1,npar);      for(j=1; j<=nlstate;j++)
   fclose(ficresprob);        for(theta=1; theta <=npar; theta++)
   fclose(ficresprobcov);          trgradg[j][theta]=gradg[theta][j];
   fclose(ficresprobcor);  
   fflush(ficgp);      for(i=1;i<=nlstate;i++)
   fflush(fichtmcov);        varpl[i][(int)age] =0.;
 }      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
       matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
       for(i=1;i<=nlstate;i++)
 /******************* Printing html file ***********/        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \  
                   int lastpass, int stepm, int weightopt, char model[],\      fprintf(ficresvpl,"%.0f ",age );
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\      for(i=1; i<=nlstate;i++)
                   int popforecast, int estepm ,\        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   double jprev1, double mprev1,double anprev1, \      fprintf(ficresvpl,"\n");
                   double jprev2, double mprev2,double anprev2){      free_vector(gp,1,nlstate);
   int jj1, k1, i1, cpt;      free_vector(gm,1,nlstate);
       free_matrix(gradg,1,npar,1,nlstate);
    fprintf(fichtm,"<ul><li><h4>Result files (first order: no variance)</h4>\n \      free_matrix(trgradg,1,nlstate,1,npar);
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",    } /* End age */
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));  
    fprintf(fichtm,"\    free_vector(xp,1,npar);
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",    free_matrix(doldm,1,nlstate,1,npar);
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));    free_matrix(dnewm,1,nlstate,1,nlstate);
    fprintf(fichtm,"\  
  - Stable prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",  }
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));  
    fprintf(fichtm,"\  /************ Variance of one-step probabilities  ******************/
  - Life expectancies by age and initial health status (estepm=%2d months): \  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[])
    <a href=\"%s\">%s</a> <br>\n</li>",  {
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));    int i, j=0,  i1, k1, l1, t, tj;
     int k2, l2, j1,  z1;
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");    int k=0,l, cptcode;
     int first=1, first1;
  m=cptcoveff;    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}    double **dnewm,**doldm;
     double *xp;
  jj1=0;    double *gp, *gm;
  for(k1=1; k1<=m;k1++){    double **gradg, **trgradg;
    for(i1=1; i1<=ncodemax[k1];i1++){    double **mu;
      jj1++;    double age,agelim, cov[NCOVMAX];
      if (cptcovn > 0) {    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");    int theta;
        for (cpt=1; cpt<=cptcoveff;cpt++)     char fileresprob[FILENAMELENGTH];
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    char fileresprobcov[FILENAMELENGTH];
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");    char fileresprobcor[FILENAMELENGTH];
      }  
      /* Pij */    double ***varpij;
      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> \  
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);         strcpy(fileresprob,"prob");
      /* Quasi-incidences */    strcat(fileresprob,fileres);
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: %s%d2.png<br> \      printf("Problem with resultfile: %s\n", fileresprob);
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
        /* Stable prevalence in each health state */    }
        for(cpt=1; cpt<nlstate;cpt++){    strcpy(fileresprobcov,"probcov");
          fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br> \    strcat(fileresprobcov,fileres);
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
        }      printf("Problem with resultfile: %s\n", fileresprobcov);
      for(cpt=1; cpt<=nlstate;cpt++) {      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): %s%d%d.png <br> \    }
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);    strcpy(fileresprobcor,"probcor");
      }    strcat(fileresprobcor,fileres);
    } /* end i1 */    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
  }/* End k1 */      printf("Problem with resultfile: %s\n", fileresprobcor);
  fprintf(fichtm,"</ul>");      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
     }
     printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
  fprintf(fichtm,"\    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 \n<br><li><h4> Result files (second order: variances)</h4>\n\    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
     printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));    pstamp(ficresprob);
  fprintf(fichtm,"\    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",    fprintf(ficresprob,"# Age");
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));    pstamp(ficresprobcov);
     fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
  fprintf(fichtm,"\    fprintf(ficresprobcov,"# Age");
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",    pstamp(ficresprobcor);
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
  fprintf(fichtm,"\    fprintf(ficresprobcor,"# Age");
  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"%s\">%s</a><br>\n",  
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));  
  fprintf(fichtm,"\    for(i=1; i<=nlstate;i++)
  - Health expectancies with their variances (no covariance): <a href=\"%s\">%s</a> <br>\n",      for(j=1; j<=(nlstate+ndeath);j++){
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
  fprintf(fichtm,"\        fprintf(ficresprobcov," p%1d-%1d ",i,j);
  - Standard deviation of stable prevalences: <a href=\"%s\">%s</a> <br>\n",\        fprintf(ficresprobcor," p%1d-%1d ",i,j);
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));      }  
    /* fprintf(ficresprob,"\n");
 /*  if(popforecast==1) fprintf(fichtm,"\n */    fprintf(ficresprobcov,"\n");
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */    fprintf(ficresprobcor,"\n");
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */   */
 /*      <br>",fileres,fileres,fileres,fileres); */   xp=vector(1,npar);
 /*  else  */    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 /*    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); */    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
  fflush(fichtm);    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
     first=1;
  m=cptcoveff;    fprintf(ficgp,"\n# Routine varprob");
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
     fprintf(fichtm,"\n");
  jj1=0;  
  for(k1=1; k1<=m;k1++){    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
    for(i1=1; i1<=ncodemax[k1];i1++){    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
      jj1++;    file %s<br>\n",optionfilehtmcov);
      if (cptcovn > 0) {    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");  and drawn. It helps understanding how is the covariance between two incidences.\
        for (cpt=1; cpt<=cptcoveff;cpt++)    They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    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. \
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");  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 \
      for(cpt=1; cpt<=nlstate;cpt++) {  standard deviations wide on each axis. <br>\
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);    To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
      }  
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \    cov[1]=1;
 health expectancies in states (1) and (2): %s%d.png<br>\    tj=cptcoveff;
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
    } /* end i1 */    j1=0;
  }/* End k1 */    for(t=1; t<=tj;t++){
  fprintf(fichtm,"</ul>");      for(i1=1; i1<=ncodemax[t];i1++){
  fflush(fichtm);        j1++;
 }        if  (cptcovn>0) {
           fprintf(ficresprob, "\n#********** Variable ");
 /******************* Gnuplot file **************/          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){          fprintf(ficresprob, "**********\n#\n");
           fprintf(ficresprobcov, "\n#********** Variable ");
   char dirfileres[132],optfileres[132];          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;          fprintf(ficresprobcov, "**********\n#\n");
   int ng;         
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */          fprintf(ficgp, "\n#********** Variable ");
 /*     printf("Problem with file %s",optionfilegnuplot); */          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */          fprintf(ficgp, "**********\n#\n");
 /*   } */         
          
   /*#ifdef windows */          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
   fprintf(ficgp,"cd \"%s\" \n",pathc);          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
     /*#endif */          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
   m=pow(2,cptcoveff);         
           fprintf(ficresprobcor, "\n#********** Variable ");    
   strcpy(dirfileres,optionfilefiname);          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
   strcpy(optfileres,"vpl");          fprintf(ficresprobcor, "**********\n#");    
  /* 1eme*/        }
   for (cpt=1; cpt<= nlstate ; cpt ++) {       
    for (k1=1; k1<= m ; k1 ++) {        for (age=bage; age<=fage; age ++){
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);          cov[2]=age;
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);          for (k=1; k<=cptcovn;k++) {
      fprintf(ficgp,"set xlabel \"Age\" \n\            cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
 set ylabel \"Probability\" \n\          }
 set ter png small\n\          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 set size 0.65,0.65\n\          for (k=1; k<=cptcovprod;k++)
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);            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; i<= nlstate ; i ++) {          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
        else fprintf(ficgp," \%%*lf (\%%*lf)");          gp=vector(1,(nlstate)*(nlstate+ndeath));
      }          gm=vector(1,(nlstate)*(nlstate+ndeath));
      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);     
      for (i=1; i<= nlstate ; i ++) {          for(theta=1; theta <=npar; theta++){
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");            for(i=1; i<=npar; i++)
        else fprintf(ficgp," \%%*lf (\%%*lf)");              xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
      }            
      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);             pmij(pmmij,cov,ncovmodel,xp,nlstate);
      for (i=1; i<= nlstate ; i ++) {           
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");            k=0;
        else fprintf(ficgp," \%%*lf (\%%*lf)");            for(i=1; i<= (nlstate); i++){
      }                for(j=1; j<=(nlstate+ndeath);j++){
      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));                k=k+1;
    }                gp[k]=pmmij[i][j];
   }              }
   /*2 eme*/            }
              
   for (k1=1; k1<= m ; k1 ++) {             for(i=1; i<=npar; i++)
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);     
                 pmij(pmmij,cov,ncovmodel,xp,nlstate);
     for (i=1; i<= nlstate+1 ; i ++) {            k=0;
       k=2*i;            for(i=1; i<=(nlstate); i++){
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);              for(j=1; j<=(nlstate+ndeath);j++){
       for (j=1; j<= nlstate+1 ; j ++) {                k=k+1;
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");                gm[k]=pmmij[i][j];
         else fprintf(ficgp," \%%*lf (\%%*lf)");              }
       }               }
       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)*(nlstate+ndeath); i++)
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);              gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
       for (j=1; j<= nlstate+1 ; j ++) {          }
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");  
         else fprintf(ficgp," \%%*lf (\%%*lf)");          for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
       }               for(theta=1; theta <=npar; theta++)
       fprintf(ficgp,"\" t\"\" w l 0,");              trgradg[j][theta]=gradg[theta][j];
       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 ++) {          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
         else fprintf(ficgp," \%%*lf (\%%*lf)");          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
       }             free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
       else fprintf(ficgp,"\" t\"\" w l 0,");          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
     }  
   }          pmij(pmmij,cov,ncovmodel,x,nlstate);
            
   /*3eme*/          k=0;
             for(i=1; i<=(nlstate); i++){
   for (k1=1; k1<= m ; k1 ++) {             for(j=1; j<=(nlstate+ndeath);j++){
     for (cpt=1; cpt<= nlstate ; cpt ++) {              k=k+1;
       k=2+nlstate*(2*cpt-2);              mu[k][(int) age]=pmmij[i][j];
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);            }
       fprintf(ficgp,"set ter png small\n\          }
 set size 0.65,0.65\n\          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 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(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);              varpij[i][j][(int)age] = doldm[i][j];
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");  
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);          /*printf("\n%d ",(int)age);
         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)*(nlstate+ndeath);i++){
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                     }*/
       */  
       for (i=1; i< nlstate ; i ++) {          fprintf(ficresprob,"\n%d ",(int)age);
         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);          fprintf(ficresprobcov,"\n%d ",(int)age);
                   fprintf(ficresprobcor,"\n%d ",(int)age);
       }   
     }          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
   }            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
             for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
   /* CV preval stable (period) */            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
   for (k1=1; k1<= m ; k1 ++) {             fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
     for (cpt=1; cpt<=nlstate ; cpt ++) {          }
       k=3;          i=0;
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);          for (k=1; k<=(nlstate);k++){
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\            for (l=1; l<=(nlstate+ndeath);l++){
 set ter png small\nset size 0.65,0.65\n\              i=i++;
 unset log y\n\              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                     for (j=1; j<=i;j++){
       for (i=1; i< nlstate ; i ++)                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
         fprintf(ficgp,"+$%d",k+i+1);                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);              }
                   }
       l=3+(nlstate+ndeath)*cpt;          }/* end of loop for state */
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);        } /* end of loop for age */
       for (i=1; i< nlstate ; i ++) {  
         l=3+(nlstate+ndeath)*cpt;        /* Confidence intervalle of pij  */
         fprintf(ficgp,"+$%d",l+i+1);        /*
       }          fprintf(ficgp,"\nset noparametric;unset label");
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);             fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
     }           fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
   }            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);
   /* proba elementaires */          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
   for(i=1,jk=1; i <=nlstate; i++){          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
     for(k=1; k <=(nlstate+ndeath); k++){        */
       if (k != i) {  
         for(j=1; j <=ncovmodel; j++){        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);        first1=1;
           jk++;         for (k2=1; k2<=(nlstate);k2++){
           fprintf(ficgp,"\n");          for (l2=1; l2<=(nlstate+ndeath);l2++){
         }            if(l2==k2) continue;
       }            j=(k2-1)*(nlstate+ndeath)+l2;
     }            for (k1=1; k1<=(nlstate);k1++){
    }              for (l1=1; l1<=(nlstate+ndeath);l1++){
                 if(l1==k1) continue;
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/                i=(k1-1)*(nlstate+ndeath)+l1;
      for(jk=1; jk <=m; jk++) {                if(i<=j) continue;
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);                 for (age=bage; age<=fage; age ++){
        if (ng==2)                  if ((int)age %5==0){
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
        else                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
          fprintf(ficgp,"\nset title \"Probability\"\n");                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);                    mu1=mu[i][(int) age]/stepm*YEARM ;
        i=1;                    mu2=mu[j][(int) age]/stepm*YEARM;
        for(k2=1; k2<=nlstate; k2++) {                    c12=cv12/sqrt(v1*v2);
          k3=i;                    /* Computing eigen value of matrix of covariance */
          for(k=1; k<=(nlstate+ndeath); k++) {                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
            if (k != k2){                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
              if(ng==2)                    /* Eigen vectors */
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
              else                    /*v21=sqrt(1.-v11*v11); *//* error */
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);                    v21=(lc1-v1)/cv12*v11;
              ij=1;                    v12=-v21;
              for(j=3; j <=ncovmodel; j++) {                    v22=v11;
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {                    tnalp=v21/v11;
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);                    if(first1==1){
                  ij++;                      first1=0;
                }                      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);
                else                    }
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-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);
              }                    /*printf(fignu*/
              fprintf(ficgp,")/(1");                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
              for(k1=1; k1 <=nlstate; k1++){                       if(first==1){
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);                      first=0;
                ij=1;                      fprintf(ficgp,"\nset parametric;unset label");
                for(j=3; j <=ncovmodel; j++){                      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);
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                    ij++;   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                  }  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                  else                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                }                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                fprintf(ficgp,")");                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
              }                      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
              i=i+ncovmodel;                      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),\
          } /* end k */                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
        } /* end k2 */                    }else{
      } /* end jk */                      first=0;
    } /* end ng */                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
    fflush(ficgp);                       fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 }  /* end gnuplot */                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                       fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
                               mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 /*************** Moving average **************/                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){                    }/* if first */
                   } /* age mod 5 */
   int i, cpt, cptcod;                } /* end loop age */
   int modcovmax =1;                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   int mobilavrange, mob;                first=1;
   double age;              } /*l12 */
             } /* k12 */
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose           } /*l1 */
                            a covariate has 2 modalities */        }/* k1 */
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */      } /* loop covariates */
     }
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
     if(mobilav==1) mobilavrange=5; /* default */    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
     else mobilavrange=mobilav;    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
     for (age=bage; age<=fage; age++)    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
       for (i=1; i<=nlstate;i++)    free_vector(xp,1,npar);
         for (cptcod=1;cptcod<=modcovmax;cptcod++)    fclose(ficresprob);
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];    fclose(ficresprobcov);
     /* We keep the original values on the extreme ages bage, fage and for     fclose(ficresprobcor);
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2    fflush(ficgp);
        we use a 5 terms etc. until the borders are no more concerned.     fflush(fichtmcov);
     */   }
     for (mob=3;mob <=mobilavrange;mob=mob+2){  
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){  
         for (i=1; i<=nlstate;i++){  /******************* Printing html file ***********/
           for (cptcod=1;cptcod<=modcovmax;cptcod++){  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];                    int lastpass, int stepm, int weightopt, char model[],\
               for (cpt=1;cpt<=(mob-1)/2;cpt++){                    int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];                    int popforecast, int estepm ,\
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];                    double jprev1, double mprev1,double anprev1, \
               }                    double jprev2, double mprev2,double anprev2){
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;    int jj1, k1, i1, cpt;
           }  
         }     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
       }/* end age */     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
     }/* end mob */  </ul>");
   }else return -1;     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
   return 0;   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 }/* End movingaverage */             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
      fprintf(fichtm,"\
    - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 /************** Forecasting ******************/             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 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){     fprintf(fichtm,"\
   /* proj1, year, month, day of starting projection    - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
      agemin, agemax range of age             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
      dateprev1 dateprev2 range of dates during which prevalence is computed     fprintf(fichtm,"\
      anproj2 year of en of projection (same day and month as proj1).   - (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",
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
   int *popage;     fprintf(fichtm,"\
   double agec; /* generic age */   - Population projections by age and states: \
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
   double *popeffectif,*popcount;  
   double ***p3mat;  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
   double ***mobaverage;  
   char fileresf[FILENAMELENGTH];   m=cptcoveff;
    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   agelim=AGESUP;  
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);   jj1=0;
     for(k1=1; k1<=m;k1++){
   strcpy(fileresf,"f");      for(i1=1; i1<=ncodemax[k1];i1++){
   strcat(fileresf,fileres);       jj1++;
   if((ficresf=fopen(fileresf,"w"))==NULL) {       if (cptcovn > 0) {
     printf("Problem with forecast resultfile: %s\n", fileresf);         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);         for (cpt=1; cpt<=cptcoveff;cpt++)
   }           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
   printf("Computing forecasting: result on file '%s' \n", fileresf);         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);       }
        /* Pij */
   if (cptcoveff==0) ncodemax[cptcoveff]=1;       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);    
   if (mobilav!=0) {       /* Quasi-incidences */
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){   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> \
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
       printf(" Error in movingaverage mobilav=%d\n",mobilav);         /* Period (stable) prevalence in each health state */
     }         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> \
   <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
   stepsize=(int) (stepm+YEARM-1)/YEARM;         }
   if (stepm<=12) stepsize=1;       for(cpt=1; cpt<=nlstate;cpt++) {
   if(estepm < stepm){          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> \
     printf ("Problem %d lower than %d\n",estepm, stepm);  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
   }       }
   else  hstepm=estepm;        } /* end i1 */
    }/* End k1 */
   hstepm=hstepm/stepm;    fprintf(fichtm,"</ul>");
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and  
                                fractional in yp1 */  
   anprojmean=yp;   fprintf(fichtm,"\
   yp2=modf((yp1*12),&yp);  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
   mprojmean=yp;   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
   yp1=modf((yp2*30.5),&yp);  
   jprojmean=yp;   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
   if(jprojmean==0) jprojmean=1;           subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
   if(mprojmean==0) jprojmean=1;   fprintf(fichtm,"\
    - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
   i1=cptcoveff;           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
   if (cptcovn < 1){i1=1;}  
      fprintf(fichtm,"\
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);    - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
              subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
   fprintf(ficresf,"#****** Routine prevforecast **\n");   fprintf(fichtm,"\
    - 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): \
 /*            if (h==(int)(YEARM*yearp)){ */     <a href=\"%s\">%s</a> <br>\n</li>",
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){   fprintf(fichtm,"\
       k=k+1;   - (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): \
       fprintf(ficresf,"\n#******");     <a href=\"%s\">%s</a> <br>\n</li>",
       for(j=1;j<=cptcoveff;j++) {             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
         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]]);   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",
       fprintf(ficresf,"******\n");           estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");   fprintf(fichtm,"\
       for(j=1; j<=nlstate+ndeath;j++){    - 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",
         for(i=1; i<=nlstate;i++)                         subdirf2(fileres,"t"),subdirf2(fileres,"t"));
           fprintf(ficresf," p%d%d",i,j);   fprintf(fichtm,"\
         fprintf(ficresf," p.%d",j);   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
       }           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {   
         fprintf(ficresf,"\n");  /*  if(popforecast==1) fprintf(fichtm,"\n */
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);     /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
   /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
         for (agec=fage; agec>=(ageminpar-1); agec--){   /*      <br>",fileres,fileres,fileres,fileres); */
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);   /*  else  */
           nhstepm = nhstepm/hstepm;   /*    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); */
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   fflush(fichtm);
           oldm=oldms;savm=savms;   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);    
            m=cptcoveff;
           for (h=0; h<=nhstepm; h++){   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
             if (h*hstepm/YEARM*stepm ==yearp) {  
               fprintf(ficresf,"\n");   jj1=0;
               for(j=1;j<=cptcoveff;j++)    for(k1=1; k1<=m;k1++){
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);     for(i1=1; i1<=ncodemax[k1];i1++){
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);       jj1++;
             }        if (cptcovn > 0) {
             for(j=1; j<=nlstate+ndeath;j++) {         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
               ppij=0.;         for (cpt=1; cpt<=cptcoveff;cpt++)
               for(i=1; i<=nlstate;i++) {           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                 if (mobilav==1)          fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];       }
                 else {       for(cpt=1; cpt<=nlstate;cpt++) {
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
                 }  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
                 if (h*hstepm/YEARM*stepm== yearp) {  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);       }
                 }       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
               } /* end i */  health expectancies in states (1) and (2): %s%d.png<br>\
               if (h*hstepm/YEARM*stepm==yearp) {  <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                 fprintf(ficresf," %.3f", ppij);     } /* end i1 */
               }   }/* End k1 */
             }/* end j */   fprintf(fichtm,"</ul>");
           } /* end h */   fflush(fichtm);
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  }
         } /* end agec */  
       } /* end yearp */  /******************* Gnuplot file **************/
     } /* end cptcod */  void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   } /* end  cptcov */  
            char dirfileres[132],optfileres[132];
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     int ng;
   fclose(ficresf);  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 }  /*     printf("Problem with file %s",optionfilegnuplot); */
   /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 /************** Forecasting *****not tested NB*************/  /*   } */
 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){  
       /*#ifdef windows */
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;    fprintf(ficgp,"cd \"%s\" \n",pathc);
   int *popage;      /*#endif */
   double calagedatem, agelim, kk1, kk2;    m=pow(2,cptcoveff);
   double *popeffectif,*popcount;  
   double ***p3mat,***tabpop,***tabpopprev;    strcpy(dirfileres,optionfilefiname);
   double ***mobaverage;    strcpy(optfileres,"vpl");
   char filerespop[FILENAMELENGTH];   /* 1eme*/
     for (cpt=1; cpt<= nlstate ; cpt ++) {
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);     for (k1=1; k1<= m ; k1 ++) {
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
   agelim=AGESUP;       fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;       fprintf(ficgp,"set xlabel \"Age\" \n\
     set ylabel \"Probability\" \n\
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);  set ter png small\n\
     set size 0.65,0.65\n\
     plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
   strcpy(filerespop,"pop");   
   strcat(filerespop,fileres);       for (i=1; i<= nlstate ; i ++) {
   if((ficrespop=fopen(filerespop,"w"))==NULL) {         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
     printf("Problem with forecast resultfile: %s\n", filerespop);         else fprintf(ficgp," \%%*lf (\%%*lf)");
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);       }
   }       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);
   printf("Computing forecasting: result on file '%s' \n", filerespop);       for (i=1; i<= nlstate ; i ++) {
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
          else fprintf(ficgp," \%%*lf (\%%*lf)");
   if (cptcoveff==0) ncodemax[cptcoveff]=1;       }
        fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
   if (mobilav!=0) {       for (i=1; i<= nlstate ; i ++) {
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){         else fprintf(ficgp," \%%*lf (\%%*lf)");
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);       }  
       printf(" Error in movingaverage mobilav=%d\n",mobilav);       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));
     }     }
   }    }
     /*2 eme*/
   stepsize=(int) (stepm+YEARM-1)/YEARM;   
   if (stepm<=12) stepsize=1;    for (k1=1; k1<= m ; k1 ++) {
         fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
   agelim=AGESUP;      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
        
   hstepm=1;      for (i=1; i<= nlstate+1 ; i ++) {
   hstepm=hstepm/stepm;         k=2*i;
           fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
   if (popforecast==1) {        for (j=1; j<= nlstate+1 ; j ++) {
     if((ficpop=fopen(popfile,"r"))==NULL) {          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       printf("Problem with population file : %s\n",popfile);exit(0);          else fprintf(ficgp," \%%*lf (\%%*lf)");
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);        }  
     }         if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
     popage=ivector(0,AGESUP);        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
     popeffectif=vector(0,AGESUP);        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
     popcount=vector(0,AGESUP);        for (j=1; j<= nlstate+1 ; j ++) {
               if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
     i=1;             else fprintf(ficgp," \%%*lf (\%%*lf)");
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;        }  
            fprintf(ficgp,"\" t\"\" w l 0,");
     imx=i;        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];        for (j=1; j<= nlstate+1 ; j ++) {
   }          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
           else fprintf(ficgp," \%%*lf (\%%*lf)");
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){        }  
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
       k=k+1;        else fprintf(ficgp,"\" t\"\" w l 0,");
       fprintf(ficrespop,"\n#******");      }
       for(j=1;j<=cptcoveff;j++) {    }
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);   
       }    /*3eme*/
       fprintf(ficrespop,"******\n");   
       fprintf(ficrespop,"# Age");    for (k1=1; k1<= m ; k1 ++) {
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);      for (cpt=1; cpt<= nlstate ; cpt ++) {
       if (popforecast==1)  fprintf(ficrespop," [Population]");        /*       k=2+nlstate*(2*cpt-2); */
               k=2+(nlstate+1)*(cpt-1);
       for (cpt=0; cpt<=0;cpt++) {         fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);           fprintf(ficgp,"set ter png small\n\
           set size 0.65,0.65\n\
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){   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);
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);         /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
           nhstepm = nhstepm/hstepm;           for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                     fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
           oldm=oldms;savm=savms;          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);            fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                  
           for (h=0; h<=nhstepm; h++){        */
             if (h==(int) (calagedatem+YEARM*cpt)) {        for (i=1; i< nlstate ; i ++) {
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);          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);*/
             for(j=1; j<=nlstate+ndeath;j++) {         
               kk1=0.;kk2=0;        }
               for(i=1; i<=nlstate;i++) {                      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                 if (mobilav==1)       }
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];    }
                 else {   
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];    /* CV preval stable (period) */
                 }    for (k1=1; k1<= m ; k1 ++) {
               }      for (cpt=1; cpt<=nlstate ; cpt ++) {
               if (h==(int)(calagedatem+12*cpt)){        k=3;
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
                   /*fprintf(ficrespop," %.3f", kk1);        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/  set ter png small\nset size 0.65,0.65\n\
               }  unset log y\n\
             }  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
             for(i=1; i<=nlstate;i++){       
               kk1=0.;        for (i=1; i< nlstate ; i ++)
                 for(j=1; j<=nlstate;j++){          fprintf(ficgp,"+$%d",k+i+1);
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];         fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
                 }       
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];        l=3+(nlstate+ndeath)*cpt;
             }        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
         for (i=1; i< nlstate ; i ++) {
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)           l=3+(nlstate+ndeath)*cpt;
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);          fprintf(ficgp,"+$%d",l+i+1);
           }        }
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
         }      }
       }    }  
     
   /******/    /* proba elementaires */
     for(i=1,jk=1; i <=nlstate; i++){
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {       for(k=1; k <=(nlstate+ndeath); k++){
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);           if (k != i) {
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){           for(j=1; j <=ncovmodel; j++){
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);             fprintf(ficgp,"p%d=%f ",jk,p[jk]);
           nhstepm = nhstepm/hstepm;             jk++;
                       fprintf(ficgp,"\n");
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          }
           oldm=oldms;savm=savms;        }
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        }
           for (h=0; h<=nhstepm; h++){     }
             if (h==(int) (calagedatem+YEARM*cpt)) {  
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
             }        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);
               kk1=0.;kk2=0;         if (ng==2)
               for(i=1; i<=nlstate;i++) {                         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];             else
               }           fprintf(ficgp,"\nset title \"Probability\"\n");
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                 fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
             }         i=1;
           }         for(k2=1; k2<=nlstate; k2++) {
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);           k3=i;
         }           for(k=1; k<=(nlstate+ndeath); k++) {
       }             if (k != k2){
    }                if(ng==2)
   }                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                 else
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                ij=1;
   if (popforecast==1) {               for(j=3; j <=ncovmodel; j++) {
     free_ivector(popage,0,AGESUP);                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
     free_vector(popeffectif,0,AGESUP);                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
     free_vector(popcount,0,AGESUP);                   ij++;
   }                 }
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                 else
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
   fclose(ficrespop);               }
 } /* End of popforecast */               fprintf(ficgp,")/(1");
                
 int fileappend(FILE *fichier, char *optionfich)               for(k1=1; k1 <=nlstate; k1++){  
 {                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
   if((fichier=fopen(optionfich,"a"))==NULL) {                 ij=1;
     printf("Problem with file: %s\n", optionfich);                 for(j=3; j <=ncovmodel; j++){
     fprintf(ficlog,"Problem with file: %s\n", optionfich);                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
     return (0);                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
   }                     ij++;
   fflush(fichier);                   }
   return (1);                   else
 }                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                  }
                  fprintf(ficgp,")");
 /**************** function prwizard **********************/               }
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 {               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                i=i+ncovmodel;
   /* Wizard to print covariance matrix template */             }
            } /* end k */
   char ca[32], cb[32], cc[32];         } /* end k2 */
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;       } /* end jk */
   int numlinepar;     } /* end ng */
      fflush(ficgp);
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");  }  /* end gnuplot */
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");  
   for(i=1; i <=nlstate; i++){  
     jj=0;  /*************** Moving average **************/
     for(j=1; j <=nlstate+ndeath; j++){  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
       if(j==i) continue;  
       jj++;    int i, cpt, cptcod;
       /*ca[0]= k+'a'-1;ca[1]='\0';*/    int modcovmax =1;
       printf("%1d%1d",i,j);    int mobilavrange, mob;
       fprintf(ficparo,"%1d%1d",i,j);    double age;
       for(k=1; k<=ncovmodel;k++){  
         /*        printf(" %lf",param[i][j][k]); */    modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
         /*        fprintf(ficparo," %lf",param[i][j][k]); */                             a covariate has 2 modalities */
         printf(" 0.");    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
         fprintf(ficparo," 0.");  
       }    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
       printf("\n");      if(mobilav==1) mobilavrange=5; /* default */
       fprintf(ficparo,"\n");      else mobilavrange=mobilav;
     }      for (age=bage; age<=fage; age++)
   }        for (i=1; i<=nlstate;i++)
   printf("# Scales (for hessian or gradient estimation)\n");          for (cptcod=1;cptcod<=modcovmax;cptcod++)
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/       /* We keep the original values on the extreme ages bage, fage and for
   for(i=1; i <=nlstate; i++){         fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
     jj=0;         we use a 5 terms etc. until the borders are no more concerned.
     for(j=1; j <=nlstate+ndeath; j++){      */
       if(j==i) continue;      for (mob=3;mob <=mobilavrange;mob=mob+2){
       jj++;        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
       fprintf(ficparo,"%1d%1d",i,j);          for (i=1; i<=nlstate;i++){
       printf("%1d%1d",i,j);            for (cptcod=1;cptcod<=modcovmax;cptcod++){
       fflush(stdout);              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
       for(k=1; k<=ncovmodel;k++){                for (cpt=1;cpt<=(mob-1)/2;cpt++){
         /*      printf(" %le",delti3[i][j][k]); */                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
         printf(" 0.");                }
         fprintf(ficparo," 0.");              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
       }            }
       numlinepar++;          }
       printf("\n");        }/* end age */
       fprintf(ficparo,"\n");      }/* end mob */
     }    }else return -1;
   }    return 0;
   printf("# Covariance matrix\n");  }/* End movingaverage */
 /* # 121 Var(a12)\n\ */  
 /* # 122 Cov(b12,a12) Var(b12)\n\ */  
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */  /************** Forecasting ******************/
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */  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){
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */    /* proj1, year, month, day of starting projection
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */       agemin, agemax range of age
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */       dateprev1 dateprev2 range of dates during which prevalence is computed
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */       anproj2 year of en of projection (same day and month as proj1).
   fflush(stdout);    */
   fprintf(ficparo,"# Covariance matrix\n");    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
   /* # 121 Var(a12)\n\ */    int *popage;
   /* # 122 Cov(b12,a12) Var(b12)\n\ */    double agec; /* generic age */
   /* #   ...\n\ */    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */    double *popeffectif,*popcount;
       double ***p3mat;
   for(itimes=1;itimes<=2;itimes++){    double ***mobaverage;
     jj=0;    char fileresf[FILENAMELENGTH];
     for(i=1; i <=nlstate; i++){  
       for(j=1; j <=nlstate+ndeath; j++){    agelim=AGESUP;
         if(j==i) continue;    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
         for(k=1; k<=ncovmodel;k++){   
           jj++;    strcpy(fileresf,"f");
           ca[0]= k+'a'-1;ca[1]='\0';    strcat(fileresf,fileres);
           if(itimes==1){    if((ficresf=fopen(fileresf,"w"))==NULL) {
             printf("#%1d%1d%d",i,j,k);      printf("Problem with forecast resultfile: %s\n", fileresf);
             fprintf(ficparo,"#%1d%1d%d",i,j,k);      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
           }else{    }
             printf("%1d%1d%d",i,j,k);    printf("Computing forecasting: result on file '%s' \n", fileresf);
             fprintf(ficparo,"%1d%1d%d",i,j,k);    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
             /*  printf(" %.5le",matcov[i][j]); */  
           }    if (cptcoveff==0) ncodemax[cptcoveff]=1;
           ll=0;  
           for(li=1;li <=nlstate; li++){    if (mobilav!=0) {
             for(lj=1;lj <=nlstate+ndeath; lj++){      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
               if(lj==li) continue;      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
               for(lk=1;lk<=ncovmodel;lk++){        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                 ll++;        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                 if(ll<=jj){      }
                   cb[0]= lk +'a'-1;cb[1]='\0';    }
                   if(ll<jj){  
                     if(itimes==1){    stepsize=(int) (stepm+YEARM-1)/YEARM;
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);    if (stepm<=12) stepsize=1;
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);    if(estepm < stepm){
                     }else{      printf ("Problem %d lower than %d\n",estepm, stepm);
                       printf(" 0.");    }
                       fprintf(ficparo," 0.");    else  hstepm=estepm;  
                     }  
                   }else{    hstepm=hstepm/stepm;
                     if(itimes==1){    yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                       printf(" Var(%s%1d%1d)",ca,i,j);                                 fractional in yp1 */
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);    anprojmean=yp;
                     }else{    yp2=modf((yp1*12),&yp);
                       printf(" 0.");    mprojmean=yp;
                       fprintf(ficparo," 0.");    yp1=modf((yp2*30.5),&yp);
                     }    jprojmean=yp;
                   }    if(jprojmean==0) jprojmean=1;
                 }    if(mprojmean==0) jprojmean=1;
               } /* end lk */  
             } /* end lj */    i1=cptcoveff;
           } /* end li */    if (cptcovn < 1){i1=1;}
           printf("\n");   
           fprintf(ficparo,"\n");    fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
           numlinepar++;   
         } /* end k*/    fprintf(ficresf,"#****** Routine prevforecast **\n");
       } /*end j */  
     } /* end i */  /*            if (h==(int)(YEARM*yearp)){ */
   } /* end itimes */    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
       for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 } /* end of prwizard */        k=k+1;
 /******************* Gompertz Likelihood ******************************/        fprintf(ficresf,"\n#******");
 double gompertz(double x[])        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]]);
   double A,B,L=0.0,sump=0.,num=0.;        }
   int i,n=0; /* n is the size of the sample */        fprintf(ficresf,"******\n");
   for (i=0;i<=imx-1 ; i++) {        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
     sump=sump+weight[i];        for(j=1; j<=nlstate+ndeath;j++){
     sump=sump+1;          for(i=1; i<=nlstate;i++)              
     num=num+1;            fprintf(ficresf," p%d%d",i,j);
   }          fprintf(ficresf," p.%d",j);
          }
          for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
   /* for (i=1; i<=imx; i++)           fprintf(ficresf,"\n");
      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]);*/          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
   
   for (i=0;i<=imx-1 ; i++)          for (agec=fage; agec>=(ageminpar-1); agec--){
     {            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
       if (cens[i]==1 & wav[i]>1)            nhstepm = nhstepm/hstepm;
         A=-x[1]/(x[2])*            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           (exp(x[2]/YEARM*(agecens[i]*12-agegomp*12))-exp(x[2]/YEARM*(ageexmed[i]*12-agegomp*12)));            oldm=oldms;savm=savms;
                   hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
       if (cens[i]==0 & wav[i]>1)         
         A=-x[1]/(x[2])*            for (h=0; h<=nhstepm; h++){
              (exp(x[2]/YEARM*(agedc[i]*12-agegomp*12))-exp(x[2]/YEARM*(ageexmed[i]*12-agegomp*12)))              if (h*hstepm/YEARM*stepm ==yearp) {
           +log(x[1]/YEARM)+x[2]/YEARM*(agedc[i]*12-agegomp*12)+log(YEARM);                      fprintf(ficresf,"\n");
                       for(j=1;j<=cptcoveff;j++)
       if (wav[i]>1 & agecens[i]>15) {                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         L=L+A*weight[i];                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
         /*      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]);*/              }
       }              for(j=1; j<=nlstate+ndeath;j++) {
     }                ppij=0.;
                 for(i=1; i<=nlstate;i++) {
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/                  if (mobilav==1)
                      ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
   return -2*L*num/sump;                  else {
 }                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   }
 /******************* Printing html file ***********/                  if (h*hstepm/YEARM*stepm== yearp) {
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   int lastpass, int stepm, int weightopt, char model[],\                  }
                   int imx,  double p[],double **matcov){                } /* end i */
   int i;                if (h*hstepm/YEARM*stepm==yearp) {
                   fprintf(ficresf," %.3f", ppij);
   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);              }/* end j */
   for (i=1;i<=2;i++)             } /* end h */
     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]));            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");          } /* end agec */
   fprintf(fichtm,"</ul>");        } /* end yearp */
   fflush(fichtm);      } /* end cptcod */
 }    } /* end  cptcov */
          
 /******************* Gnuplot file **************/    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){  
     fclose(ficresf);
   char dirfileres[132],optfileres[132];  }
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;  
   int ng;  /************** Forecasting *****not tested NB*************/
   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){
    
   /*#ifdef windows */    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
   fprintf(ficgp,"cd \"%s\" \n",pathc);    int *popage;
     /*#endif */    double calagedatem, agelim, kk1, kk2;
     double *popeffectif,*popcount;
     double ***p3mat,***tabpop,***tabpopprev;
   strcpy(dirfileres,optionfilefiname);    double ***mobaverage;
   strcpy(optfileres,"vpl");    char filerespop[FILENAMELENGTH];
   fprintf(ficgp,"set out \"graphmort.png\"\n ");   
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");     tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficgp, "set ter png small\n set log y\n");     tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficgp, "set size 0.65,0.65\n");    agelim=AGESUP;
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
    
 }     prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
    
    
     strcpy(filerespop,"pop");
     strcat(filerespop,fileres);
 /***********************************************/    if((ficrespop=fopen(filerespop,"w"))==NULL) {
 /**************** Main Program *****************/      printf("Problem with forecast resultfile: %s\n", filerespop);
 /***********************************************/      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
     }
 int main(int argc, char *argv[])    printf("Computing forecasting: result on file '%s' \n", filerespop);
 {    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);  
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;    if (cptcoveff==0) ncodemax[cptcoveff]=1;
   int jj, ll, li, lj, lk, imk;  
   int numlinepar=0; /* Current linenumber of parameter file */    if (mobilav!=0) {
   int itimes;      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   int NDIM=2;      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   char ca[32], cb[32], cc[32];        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   /*  FILE *fichtm; *//* Html File */      }
   /* FILE *ficgp;*/ /*Gnuplot File */    }
   double agedeb, agefin,hf;  
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;    stepsize=(int) (stepm+YEARM-1)/YEARM;
     if (stepm<=12) stepsize=1;
   double fret;   
   double **xi,tmp,delta;    agelim=AGESUP;
    
   double dum; /* Dummy variable */    hstepm=1;
   double ***p3mat;    hstepm=hstepm/stepm;
   double ***mobaverage;   
   int *indx;    if (popforecast==1) {
   char line[MAXLINE], linepar[MAXLINE];      if((ficpop=fopen(popfile,"r"))==NULL) {
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];        printf("Problem with population file : %s\n",popfile);exit(0);
   char pathr[MAXLINE], pathimach[MAXLINE];         fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
   int firstobs=1, lastobs=10;      }
   int sdeb, sfin; /* Status at beginning and end */      popage=ivector(0,AGESUP);
   int c,  h , cpt,l;      popeffectif=vector(0,AGESUP);
   int ju,jl, mi;      popcount=vector(0,AGESUP);
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;     
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;       i=1;  
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
   int mobilav=0,popforecast=0;     
   int hstepm, nhstepm;      imx=i;
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;    }
   
   double bage, fage, age, agelim, agebase;    for(cptcov=1,k=0;cptcov<=i2;cptcov++){
   double ftolpl=FTOL;     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   double **prlim;        k=k+1;
   double *severity;        fprintf(ficrespop,"\n#******");
   double ***param; /* Matrix of parameters */        for(j=1;j<=cptcoveff;j++) {
   double  *p;          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   double **matcov; /* Matrix of covariance */        }
   double ***delti3; /* Scale */        fprintf(ficrespop,"******\n");
   double *delti; /* Scale */        fprintf(ficrespop,"# Age");
   double ***eij, ***vareij;        for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
   double **varpl; /* Variances of prevalence limits by age */        if (popforecast==1)  fprintf(ficrespop," [Population]");
   double *epj, vepp;       
   double kk1, kk2;        for (cpt=0; cpt<=0;cpt++) {
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   double **ximort;         
   char *alph[]={"a","a","b","c","d","e"}, str[4];          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
   int *dcwave;            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
             nhstepm = nhstepm/hstepm;
   char z[1]="c", occ;           
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];            oldm=oldms;savm=savms;
   char strstart[80], *strt, strtend[80];            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   char *stratrunc;         
   int lstra;            for (h=0; h<=nhstepm; h++){
               if (h==(int) (calagedatem+YEARM*cpt)) {
   long total_usecs;                fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                }
 /*   setlocale (LC_ALL, ""); */              for(j=1; j<=nlstate+ndeath;j++) {
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */                kk1=0.;kk2=0;
 /*   textdomain (PACKAGE); */                for(i=1; i<=nlstate;i++) {              
 /*   setlocale (LC_CTYPE, ""); */                  if (mobilav==1)
 /*   setlocale (LC_MESSAGES, ""); */                    kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   else {
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
   (void) gettimeofday(&start_time,&tzp);                  }
   curr_time=start_time;                }
   tm = *localtime(&start_time.tv_sec);                if (h==(int)(calagedatem+12*cpt)){
   tmg = *gmtime(&start_time.tv_sec);                  tabpop[(int)(agedeb)][j][cptcod]=kk1;
   strcpy(strstart,asctime(&tm));                    /*fprintf(ficrespop," %.3f", kk1);
                       if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 /*  printf("Localtime (at start)=%s",strstart); */                }
 /*  tp.tv_sec = tp.tv_sec +86400; */              }
 /*  tm = *localtime(&start_time.tv_sec); */              for(i=1; i<=nlstate;i++){
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */                kk1=0.;
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */                  for(j=1; j<=nlstate;j++){
 /*   tmg.tm_hour=tmg.tm_hour + 1; */                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
 /*   tp.tv_sec = mktime(&tmg); */                  }
 /*   strt=asctime(&tmg); */                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 /*   printf("Time(after) =%s",strstart);  */              }
 /*  (void) time (&time_value);  
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
 *  tm = *localtime(&time_value);                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 *  strstart=asctime(&tm);            }
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 */          }
         }
   nberr=0; /* Number of errors and warnings */   
   nbwarn=0;    /******/
   getcwd(pathcd, size);  
         for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
   printf("\n%s\n%s",version,fullversion);          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   if(argc <=1){          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
     printf("\nEnter the parameter file name: ");            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
     scanf("%s",pathtot);            nhstepm = nhstepm/hstepm;
   }           
   else{            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     strcpy(pathtot,argv[1]);            oldm=oldms;savm=savms;
   }            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/            for (h=0; h<=nhstepm; h++){
   /*cygwin_split_path(pathtot,path,optionfile);              if (h==(int) (calagedatem+YEARM*cpt)) {
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   /* cutv(path,optionfile,pathtot,'\\');*/              }
               for(j=1; j<=nlstate+ndeath;j++) {
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);                kk1=0.;kk2=0;
  /*   strcpy(pathimach,argv[0]); */                for(i=1; i<=nlstate;i++) {              
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
   printf("pathimach=%s, pathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);                }
   chdir(path);                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
   strcpy(command,"mkdir ");              }
   strcat(command,optionfilefiname);            }
   if((outcmd=system(command)) != 0){            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);          }
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */        }
     /* fclose(ficlog); */     }
 /*     exit(1); */    }
   }   
 /*   if((imk=mkdir(optionfilefiname))<0){ */    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 /*     perror("mkdir"); */  
 /*   } */    if (popforecast==1) {
       free_ivector(popage,0,AGESUP);
   /*-------- arguments in the command line --------*/      free_vector(popeffectif,0,AGESUP);
       free_vector(popcount,0,AGESUP);
   /* Log file */    }
   strcat(filelog, optionfilefiname);    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   strcat(filelog,".log");    /* */    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if((ficlog=fopen(filelog,"w"))==NULL)    {    fclose(ficrespop);
     printf("Problem with logfile %s\n",filelog);  } /* End of popforecast */
     goto end;  
   }  int fileappend(FILE *fichier, char *optionfich)
   fprintf(ficlog,"Log filename:%s\n",filelog);  {
   fprintf(ficlog,"\n%s\n%s",version,fullversion);    if((fichier=fopen(optionfich,"a"))==NULL) {
   fprintf(ficlog,"\nEnter the parameter file name: \n");      printf("Problem with file: %s\n", optionfich);
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\      fprintf(ficlog,"Problem with file: %s\n", optionfich);
  path=%s \n\      return (0);
  optionfile=%s\n\    }
  optionfilext=%s\n\    fflush(fichier);
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);    return (1);
   }
   printf("Local time (at start):%s",strstart);  
   fprintf(ficlog,"Local time (at start): %s",strstart);  
   fflush(ficlog);  /**************** function prwizard **********************/
 /*   (void) gettimeofday(&curr_time,&tzp); */  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */  {
   
   /* */    /* Wizard to print covariance matrix template */
   strcpy(fileres,"r");  
   strcat(fileres, optionfilefiname);    char ca[32], cb[32], cc[32];
   strcat(fileres,".txt");    /* Other files have txt extension */    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
     int numlinepar;
   /*---------arguments file --------*/  
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
   if((ficpar=fopen(optionfile,"r"))==NULL)    {    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     printf("Problem with optionfile %s\n",optionfile);    for(i=1; i <=nlstate; i++){
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);      jj=0;
     fflush(ficlog);      for(j=1; j <=nlstate+ndeath; j++){
     goto end;        if(j==i) continue;
   }        jj++;
         /*ca[0]= k+'a'-1;ca[1]='\0';*/
         printf("%1d%1d",i,j);
         fprintf(ficparo,"%1d%1d",i,j);
   strcpy(filereso,"o");        for(k=1; k<=ncovmodel;k++){
   strcat(filereso,fileres);          /*        printf(" %lf",param[i][j][k]); */
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */          /*        fprintf(ficparo," %lf",param[i][j][k]); */
     printf("Problem with Output resultfile: %s\n", filereso);          printf(" 0.");
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);          fprintf(ficparo," 0.");
     fflush(ficlog);        }
     goto end;        printf("\n");
   }        fprintf(ficparo,"\n");
       }
   /* Reads comments: lines beginning with '#' */    }
   numlinepar=0;    printf("# Scales (for hessian or gradient estimation)\n");
   while((c=getc(ficpar))=='#' && c!= EOF){    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
     ungetc(c,ficpar);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
     fgets(line, MAXLINE, ficpar);    for(i=1; i <=nlstate; i++){
     numlinepar++;      jj=0;
     puts(line);      for(j=1; j <=nlstate+ndeath; j++){
     fputs(line,ficparo);        if(j==i) continue;
     fputs(line,ficlog);        jj++;
   }        fprintf(ficparo,"%1d%1d",i,j);
   ungetc(c,ficpar);        printf("%1d%1d",i,j);
         fflush(stdout);
   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);        for(k=1; k<=ncovmodel;k++){
   numlinepar++;          /*      printf(" %le",delti3[i][j][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," %le",delti3[i][j][k]); */
   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);          printf(" 0.");
   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);          fprintf(ficparo," 0.");
   fflush(ficlog);        }
   while((c=getc(ficpar))=='#' && c!= EOF){        numlinepar++;
     ungetc(c,ficpar);        printf("\n");
     fgets(line, MAXLINE, ficpar);        fprintf(ficparo,"\n");
     numlinepar++;      }
     puts(line);    }
     fputs(line,ficparo);    printf("# Covariance matrix\n");
     fputs(line,ficlog);  /* # 121 Var(a12)\n\ */
   }  /* # 122 Cov(b12,a12) Var(b12)\n\ */
   ungetc(c,ficpar);  /* # 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\ */
   covar=matrix(0,NCOVMAX,1,n);   /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
     fflush(stdout);
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */    fprintf(ficparo,"# Covariance matrix\n");
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */    /* # 121 Var(a12)\n\ */
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/    /* # 122 Cov(b12,a12) Var(b12)\n\ */
     /* #   ...\n\ */
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
   delti=delti3[1][1];   
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/    for(itimes=1;itimes<=2;itimes++){
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */      jj=0;
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);      for(i=1; i <=nlstate; i++){
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);        for(j=1; j <=nlstate+ndeath; j++){
     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);          if(j==i) continue;
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);           for(k=1; k<=ncovmodel;k++){
     fclose (ficparo);            jj++;
     fclose (ficlog);            ca[0]= k+'a'-1;ca[1]='\0';
     exit(0);            if(itimes==1){
   }              printf("#%1d%1d%d",i,j,k);
   else if(mle==-3) {              fprintf(ficparo,"#%1d%1d%d",i,j,k);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);            }else{
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);              printf("%1d%1d%d",i,j,k);
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);              fprintf(ficparo,"%1d%1d%d",i,j,k);
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);              /*  printf(" %.5le",matcov[i][j]); */
     matcov=matrix(1,npar,1,npar);            }
   }            ll=0;
   else{            for(li=1;li <=nlstate; li++){
     /* Read guess parameters */              for(lj=1;lj <=nlstate+ndeath; lj++){
     /* Reads comments: lines beginning with '#' */                if(lj==li) continue;
     while((c=getc(ficpar))=='#' && c!= EOF){                for(lk=1;lk<=ncovmodel;lk++){
       ungetc(c,ficpar);                  ll++;
       fgets(line, MAXLINE, ficpar);                  if(ll<=jj){
       numlinepar++;                    cb[0]= lk +'a'-1;cb[1]='\0';
       puts(line);                    if(ll<jj){
       fputs(line,ficparo);                      if(itimes==1){
       fputs(line,ficlog);                        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);
     ungetc(c,ficpar);                      }else{
                             printf(" 0.");
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);                        fprintf(ficparo," 0.");
     for(i=1; i <=nlstate; i++){                      }
       j=0;                    }else{
       for(jj=1; jj <=nlstate+ndeath; jj++){                      if(itimes==1){
         if(jj==i) continue;                        printf(" Var(%s%1d%1d)",ca,i,j);
         j++;                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
         fscanf(ficpar,"%1d%1d",&i1,&j1);                      }else{
         if ((i1 != i) && (j1 != j)){                        printf(" 0.");
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);                        fprintf(ficparo," 0.");
           exit(1);                      }
         }                    }
         fprintf(ficparo,"%1d%1d",i1,j1);                  }
         if(mle==1)                } /* end lk */
           printf("%1d%1d",i,j);              } /* end lj */
         fprintf(ficlog,"%1d%1d",i,j);            } /* end li */
         for(k=1; k<=ncovmodel;k++){            printf("\n");
           fscanf(ficpar," %lf",&param[i][j][k]);            fprintf(ficparo,"\n");
           if(mle==1){            numlinepar++;
             printf(" %lf",param[i][j][k]);          } /* end k*/
             fprintf(ficlog," %lf",param[i][j][k]);        } /*end j */
           }      } /* end i */
           else    } /* end itimes */
             fprintf(ficlog," %lf",param[i][j][k]);  
           fprintf(ficparo," %lf",param[i][j][k]);  } /* end of prwizard */
         }  /******************* Gompertz Likelihood ******************************/
         fscanf(ficpar,"\n");  double gompertz(double x[])
         numlinepar++;  {
         if(mle==1)    double A,B,L=0.0,sump=0.,num=0.;
           printf("\n");    int i,n=0; /* n is the size of the sample */
         fprintf(ficlog,"\n");  
         fprintf(ficparo,"\n");    for (i=0;i<=imx-1 ; i++) {
       }      sump=sump+weight[i];
     }        /*    sump=sump+1;*/
     fflush(ficlog);      num=num+1;
     }
    
     p=param[1][1];   
         /* for (i=0; i<=imx; i++)
     /* Reads comments: lines beginning with '#' */       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]);*/
     while((c=getc(ficpar))=='#' && c!= EOF){  
       ungetc(c,ficpar);    for (i=1;i<=imx ; i++)
       fgets(line, MAXLINE, ficpar);      {
       numlinepar++;        if (cens[i] == 1 && wav[i]>1)
       puts(line);          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
       fputs(line,ficparo);       
       fputs(line,ficlog);        if (cens[i] == 0 && wav[i]>1)
     }          A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
     ungetc(c,ficpar);               +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
        
     for(i=1; i <=nlstate; i++){        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
       for(j=1; j <=nlstate+ndeath-1; j++){        if (wav[i] > 1 ) { /* ??? */
         fscanf(ficpar,"%1d%1d",&i1,&j1);          L=L+A*weight[i];
         if ((i1-i)*(j1-j)!=0){          /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);        }
           exit(1);      }
         }  
         printf("%1d%1d",i,j);   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
         fprintf(ficparo,"%1d%1d",i1,j1);   
         fprintf(ficlog,"%1d%1d",i1,j1);    return -2*L*num/sump;
         for(k=1; k<=ncovmodel;k++){  }
           fscanf(ficpar,"%le",&delti3[i][j][k]);  
           printf(" %le",delti3[i][j][k]);  /******************* Printing html file ***********/
           fprintf(ficparo," %le",delti3[i][j][k]);  void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
           fprintf(ficlog," %le",delti3[i][j][k]);                    int lastpass, int stepm, int weightopt, char model[],\
         }                    int imx,  double p[],double **matcov,double agemortsup){
         fscanf(ficpar,"\n");    int i,k;
         numlinepar++;  
         printf("\n");    fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
         fprintf(ficparo,"\n");    fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
         fprintf(ficlog,"\n");    for (i=1;i<=2;i++)
       }      fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
     }    fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
     fflush(ficlog);    fprintf(fichtm,"</ul>");
   
     delti=delti3[1][1];  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
   
    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>");
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */  
      for (k=agegomp;k<(agemortsup-2);k++)
     /* Reads comments: lines beginning with '#' */     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]);
     while((c=getc(ficpar))=='#' && c!= EOF){  
       ungetc(c,ficpar);   
       fgets(line, MAXLINE, ficpar);    fflush(fichtm);
       numlinepar++;  }
       puts(line);  
       fputs(line,ficparo);  /******************* Gnuplot file **************/
       fputs(line,ficlog);  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
     }  
     ungetc(c,ficpar);    char dirfileres[132],optfileres[132];
       int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     matcov=matrix(1,npar,1,npar);    int ng;
     for(i=1; i <=npar; i++){  
       fscanf(ficpar,"%s",&str);  
       if(mle==1)    /*#ifdef windows */
         printf("%s",str);    fprintf(ficgp,"cd \"%s\" \n",pathc);
       fprintf(ficlog,"%s",str);      /*#endif */
       fprintf(ficparo,"%s",str);  
       for(j=1; j <=i; j++){  
         fscanf(ficpar," %le",&matcov[i][j]);    strcpy(dirfileres,optionfilefiname);
         if(mle==1){    strcpy(optfileres,"vpl");
           printf(" %.5le",matcov[i][j]);    fprintf(ficgp,"set out \"graphmort.png\"\n ");
         }    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
         fprintf(ficlog," %.5le",matcov[i][j]);    fprintf(ficgp, "set ter png small\n set log y\n");
         fprintf(ficparo," %.5le",matcov[i][j]);    fprintf(ficgp, "set size 0.65,0.65\n");
       }    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
       fscanf(ficpar,"\n");  
       numlinepar++;  }
       if(mle==1)  
         printf("\n");  
       fprintf(ficlog,"\n");  
       fprintf(ficparo,"\n");  
     }  
     for(i=1; i <=npar; i++)  /***********************************************/
       for(j=i+1;j<=npar;j++)  /**************** Main Program *****************/
         matcov[i][j]=matcov[j][i];  /***********************************************/
       
     if(mle==1)  int main(int argc, char *argv[])
       printf("\n");  {
     fprintf(ficlog,"\n");    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
         int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
     fflush(ficlog);    int linei, month, year,iout;
         int jj, ll, li, lj, lk, imk;
     /*-------- Rewriting parameter file ----------*/    int numlinepar=0; /* Current linenumber of parameter file */
     strcpy(rfileres,"r");    /* "Rparameterfile */    int itimes;
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/    int NDIM=2;
     strcat(rfileres,".");    /* */  
     strcat(rfileres,optionfilext);    /* Other files have txt extension */    char ca[32], cb[32], cc[32];
     if((ficres =fopen(rfileres,"w"))==NULL) {    char dummy[]="                         ";
       printf("Problem writing new parameter file: %s\n", fileres);goto end;    /*  FILE *fichtm; *//* Html File */
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;    /* FILE *ficgp;*/ /*Gnuplot File */
     }    struct stat info;
     fprintf(ficres,"#%s\n",version);    double agedeb, agefin,hf;
   }    /* End of mle != -3 */    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
   
   /*-------- data file ----------*/    double fret;
   if((fic=fopen(datafile,"r"))==NULL)    {    double **xi,tmp,delta;
     printf("Problem with datafile: %s\n", datafile);goto end;  
     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;    double dum; /* Dummy variable */
   }    double ***p3mat;
     double ***mobaverage;
   n= lastobs;    int *indx;
   severity = vector(1,maxwav);    char line[MAXLINE], linepar[MAXLINE];
   outcome=imatrix(1,maxwav+1,1,n);    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
   num=lvector(1,n);    char pathr[MAXLINE], pathimach[MAXLINE];
   moisnais=vector(1,n);    char **bp, *tok, *val; /* pathtot */
   annais=vector(1,n);    int firstobs=1, lastobs=10;
   moisdc=vector(1,n);    int sdeb, sfin; /* Status at beginning and end */
   andc=vector(1,n);    int c,  h , cpt,l;
   agedc=vector(1,n);    int ju,jl, mi;
   cod=ivector(1,n);    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
   weight=vector(1,n);    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
   mint=matrix(1,maxwav,1,n);    int mobilav=0,popforecast=0;
   anint=matrix(1,maxwav,1,n);    int hstepm, nhstepm;
   s=imatrix(1,maxwav+1,1,n);    int agemortsup;
   tab=ivector(1,NCOVMAX);    float  sumlpop=0.;
   ncodemax=ivector(1,8);    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;
   i=1;  
   while (fgets(line, MAXLINE, fic) != NULL)    {    double bage, fage, age, agelim, agebase;
     if ((i >= firstobs) && (i <=lastobs)) {    double ftolpl=FTOL;
             double **prlim;
       for (j=maxwav;j>=1;j--){    double *severity;
         cutv(stra, strb,line,' '); s[j][i]=atoi(strb);     double ***param; /* Matrix of parameters */
         strcpy(line,stra);    double  *p;
         cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);    double **matcov; /* Matrix of covariance */
         cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);    double ***delti3; /* Scale */
       }    double *delti; /* Scale */
             double ***eij, ***vareij;
       cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);    double **varpl; /* Variances of prevalence limits by age */
       cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);    double *epj, vepp;
     double kk1, kk2;
       cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
       cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);    double **ximort;
     char *alph[]={"a","a","b","c","d","e"}, str[4];
       cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);    int *dcwave;
       for (j=ncovcol;j>=1;j--){  
         cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);    char z[1]="c", occ;
       }   
       lstra=strlen(stra);    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
       if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */    char  *strt, strtend[80];
         stratrunc = &(stra[lstra-9]);    char *stratrunc;
         num[i]=atol(stratrunc);    int lstra;
       }  
       else    long total_usecs;
         num[i]=atol(stra);   
           /*   setlocale (LC_ALL, ""); */
       /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
         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;}*/  /*   textdomain (PACKAGE); */
   /*   setlocale (LC_CTYPE, ""); */
       i=i+1;  /*   setlocale (LC_MESSAGES, ""); */
     }  
   }    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
   /* printf("ii=%d", ij);    (void) gettimeofday(&start_time,&tzp);
      scanf("%d",i);*/    curr_time=start_time;
   imx=i-1; /* Number of individuals */    tm = *localtime(&start_time.tv_sec);
     tmg = *gmtime(&start_time.tv_sec);
   /* for (i=1; i<=imx; i++){    strcpy(strstart,asctime(&tm));
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;  
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;  /*  printf("Localtime (at start)=%s",strstart); */
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;  /*  tp.tv_sec = tp.tv_sec +86400; */
     }*/  /*  tm = *localtime(&start_time.tv_sec); */
    /*  for (i=1; i<=imx; i++){  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
      if (s[4][i]==9)  s[4][i]=-1;   /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
      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]));}*/  /*   tmg.tm_hour=tmg.tm_hour + 1; */
     /*   tp.tv_sec = mktime(&tmg); */
  for (i=1; i<=imx; i++)  /*   strt=asctime(&tmg); */
    /*   printf("Time(after) =%s",strstart);  */
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;  /*  (void) time (&time_value);
      else weight[i]=1;*/  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
   *  tm = *localtime(&time_value);
   /* Calculation of the number of parameter from char model*/  *  strstart=asctime(&tm);
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
   Tprod=ivector(1,15);   */
   Tvaraff=ivector(1,15);   
   Tvard=imatrix(1,15,1,2);    nberr=0; /* Number of errors and warnings */
   Tage=ivector(1,15);          nbwarn=0;
        getcwd(pathcd, size);
   if (strlen(model) >1){ /* If there is at least 1 covariate */  
     j=0, j1=0, k1=1, k2=1;    printf("\n%s\n%s",version,fullversion);
     j=nbocc(model,'+'); /* j=Number of '+' */    if(argc <=1){
     j1=nbocc(model,'*'); /* j1=Number of '*' */      printf("\nEnter the parameter file name: ");
     cptcovn=j+1;       fgets(pathr,FILENAMELENGTH,stdin);
     cptcovprod=j1; /*Number of products */      i=strlen(pathr);
           if(pathr[i-1]=='\n')
     strcpy(modelsav,model);         pathr[i-1]='\0';
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){     for (tok = pathr; tok != NULL; ){
       printf("Error. Non available option model=%s ",model);        printf("Pathr |%s|\n",pathr);
       fprintf(ficlog,"Error. Non available option model=%s ",model);        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
       goto end;        printf("val= |%s| pathr=%s\n",val,pathr);
     }        strcpy (pathtot, val);
             if(pathr[0] == '\0') break; /* Dirty */
     /* This loop fills the array Tvar from the string 'model'.*/      }
     }
     for(i=(j+1); i>=1;i--){    else{
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */       strcpy(pathtot,argv[1]);
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */    }
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
       /*scanf("%d",i);*/    /*cygwin_split_path(pathtot,path,optionfile);
       if (strchr(strb,'*')) {  /* Model includes a product */      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/    /* cutv(path,optionfile,pathtot,'\\');*/
         if (strcmp(strc,"age")==0) { /* Vn*age */  
           cptcovprod--;    /* Split argv[0], imach program to get pathimach */
           cutv(strb,stre,strd,'V');    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/    split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
           cptcovage++;    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
             Tage[cptcovage]=i;   /*   strcpy(pathimach,argv[0]); */
             /*printf("stre=%s ", stre);*/    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
         }    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
         else if (strcmp(strd,"age")==0) { /* or age*Vn */    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
           cptcovprod--;    chdir(path); /* Can be a relative path */
           cutv(strb,stre,strc,'V');    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
           Tvar[i]=atoi(stre);      printf("Current directory %s!\n",pathcd);
           cptcovage++;    strcpy(command,"mkdir ");
           Tage[cptcovage]=i;    strcat(command,optionfilefiname);
         }    if((outcmd=system(command)) != 0){
         else {  /* Age is not in the model */      printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/      /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
           Tvar[i]=ncovcol+k1;      /* fclose(ficlog); */
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */  /*     exit(1); */
           Tprod[k1]=i;    }
           Tvard[k1][1]=atoi(strc); /* m*/  /*   if((imk=mkdir(optionfilefiname))<0){ */
           Tvard[k1][2]=atoi(stre); /* n */  /*     perror("mkdir"); */
           Tvar[cptcovn+k2]=Tvard[k1][1];  /*   } */
           Tvar[cptcovn+k2+1]=Tvard[k1][2];   
           for (k=1; k<=lastobs;k++)     /*-------- arguments in the command line --------*/
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];  
           k1++;    /* Log file */
           k2=k2+2;    strcat(filelog, optionfilefiname);
         }    strcat(filelog,".log");    /* */
       }    if((ficlog=fopen(filelog,"w"))==NULL)    {
       else { /* no more sum */      printf("Problem with logfile %s\n",filelog);
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/      goto end;
        /*  scanf("%d",i);*/    }
       cutv(strd,strc,strb,'V');    fprintf(ficlog,"Log filename:%s\n",filelog);
       Tvar[i]=atoi(strc);    fprintf(ficlog,"\n%s\n%s",version,fullversion);
       }    fprintf(ficlog,"\nEnter the parameter file name: \n");
       strcpy(modelsav,stra);      fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);   path=%s \n\
         scanf("%d",i);*/   optionfile=%s\n\
     } /* end of loop + */   optionfilext=%s\n\
   } /* end model */   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
     
   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.    printf("Local time (at start):%s",strstart);
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/    fprintf(ficlog,"Local time (at start): %s",strstart);
     fflush(ficlog);
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);  /*   (void) gettimeofday(&curr_time,&tzp); */
   printf("cptcovprod=%d ", cptcovprod);  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);  
     /* */
   scanf("%d ",i);    strcpy(fileres,"r");
   fclose(fic);*/    strcat(fileres, optionfilefiname);
     strcat(fileres,".txt");    /* Other files have txt extension */
     /*  if(mle==1){*/  
   if (weightopt != 1) { /* Maximisation without weights*/    /*---------arguments file --------*/
     for(i=1;i<=n;i++) weight[i]=1.0;  
   }    if((ficpar=fopen(optionfile,"r"))==NULL)    {
     /*-calculation of age at interview from date of interview and age at death -*/      printf("Problem with optionfile %s\n",optionfile);
   agev=matrix(1,maxwav,1,imx);      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
       fflush(ficlog);
   for (i=1; i<=imx; i++) {      goto end;
     for(m=2; (m<= maxwav); m++) {    }
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){  
         anint[m][i]=9999;  
         s[m][i]=-1;  
       }    strcpy(filereso,"o");
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){    strcat(filereso,fileres);
         nberr++;    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
         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("Problem with Output resultfile: %s\n", filereso);
         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,"Problem with Output resultfile: %s\n", filereso);
         s[m][i]=-1;      fflush(ficlog);
       }      goto end;
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){    }
         nberr++;  
         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]);     /* Reads comments: lines beginning with '#' */
         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]);     numlinepar=0;
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */    while((c=getc(ficpar))=='#' && c!= EOF){
       }      ungetc(c,ficpar);
     }      fgets(line, MAXLINE, ficpar);
   }      numlinepar++;
       puts(line);
   for (i=1; i<=imx; i++)  {      fputs(line,ficparo);
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);      fputs(line,ficlog);
     for(m=firstpass; (m<= lastpass); m++){    }
       if(s[m][i] >0){    ungetc(c,ficpar);
         if (s[m][i] >= nlstate+1) {  
           if(agedc[i]>0)    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);
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)    numlinepar++;
               agev[m][i]=agedc[i];    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);
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/    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);
             else {    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 ((int)andc[i]!=9999){    fflush(ficlog);
                 nbwarn++;    while((c=getc(ficpar))=='#' && c!= EOF){
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);      ungetc(c,ficpar);
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);      fgets(line, MAXLINE, ficpar);
                 agev[m][i]=-1;      numlinepar++;
               }      puts(line);
             }      fputs(line,ficparo);
         }      fputs(line,ficlog);
         else if(s[m][i] !=9){ /* Standard case, age in fractional    }
                                  years but with the precision of a    ungetc(c,ficpar);
                                  month */  
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);     
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)    covar=matrix(0,NCOVMAX,1,n);
             agev[m][i]=1;    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
           else if(agev[m][i] <agemin){     if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
             agemin=agev[m][i];  
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
           }    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
           else if(agev[m][i] >agemax){    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
             agemax=agev[m][i];  
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
           }    delti=delti3[1][1];
           /*agev[m][i]=anint[m][i]-annais[i];*/    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
           /*     agev[m][i] = age[i]+2*m;*/    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
         }      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
         else { /* =9 */      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           agev[m][i]=1;      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           s[m][i]=-1;      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
         }      fclose (ficparo);
       }      fclose (ficlog);
       else /*= 0 Unknown */      goto end;
         agev[m][i]=1;      exit(0);
     }    }
         else if(mle==-3) {
   }      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
   for (i=1; i<=imx; i++)  {      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     for(m=firstpass; (m<=lastpass); m++){      fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
       if (s[m][i] > (nlstate+ndeath)) {      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         nberr++;      matcov=matrix(1,npar,1,npar);
         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);         else{
         goto end;      /* Read guess parameters */
       }      /* Reads comments: lines beginning with '#' */
     }      while((c=getc(ficpar))=='#' && c!= EOF){
   }        ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
   /*for (i=1; i<=imx; i++){        numlinepar++;
   for (m=firstpass; (m<lastpass); m++){        puts(line);
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);        fputs(line,ficparo);
 }        fputs(line,ficlog);
       }
 }*/      ungetc(c,ficpar);
      
       param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);      for(i=1; i <=nlstate; i++){
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);         j=0;
         for(jj=1; jj <=nlstate+ndeath; jj++){
   agegomp=(int)agemin;          if(jj==i) continue;
   free_vector(severity,1,maxwav);          j++;
   free_imatrix(outcome,1,maxwav+1,1,n);          fscanf(ficpar,"%1d%1d",&i1,&j1);
   free_vector(moisnais,1,n);          if ((i1 != i) && (j1 != j)){
   free_vector(annais,1,n);            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
   /* free_matrix(mint,1,maxwav,1,n);  It might be a problem of design; if ncovcol and the model are correct\n \
      free_matrix(anint,1,maxwav,1,n);*/  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
   free_vector(moisdc,1,n);            exit(1);
   free_vector(andc,1,n);          }
           fprintf(ficparo,"%1d%1d",i1,j1);
              if(mle==1)
   wav=ivector(1,imx);            printf("%1d%1d",i,j);
   dh=imatrix(1,lastpass-firstpass+1,1,imx);          fprintf(ficlog,"%1d%1d",i,j);
   bh=imatrix(1,lastpass-firstpass+1,1,imx);          for(k=1; k<=ncovmodel;k++){
   mw=imatrix(1,lastpass-firstpass+1,1,imx);            fscanf(ficpar," %lf",&param[i][j][k]);
                if(mle==1){
   /* Concatenates waves */              printf(" %lf",param[i][j][k]);
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);              fprintf(ficlog," %lf",param[i][j][k]);
             }
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */            else
               fprintf(ficlog," %lf",param[i][j][k]);
   Tcode=ivector(1,100);            fprintf(ficparo," %lf",param[i][j][k]);
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);           }
   ncodemax[1]=1;          fscanf(ficpar,"\n");
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);          numlinepar++;
                 if(mle==1)
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of             printf("\n");
                                  the estimations*/          fprintf(ficlog,"\n");
   h=0;          fprintf(ficparo,"\n");
   m=pow(2,cptcoveff);        }
        }  
   for(k=1;k<=cptcoveff; k++){      fflush(ficlog);
     for(i=1; i <=(m/pow(2,k));i++){  
       for(j=1; j <= ncodemax[k]; j++){      p=param[1][1];
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){     
           h++;      /* Reads comments: lines beginning with '#' */
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;      while((c=getc(ficpar))=='#' && c!= EOF){
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/        ungetc(c,ficpar);
         }         fgets(line, MAXLINE, ficpar);
       }        numlinepar++;
     }        puts(line);
   }         fputs(line,ficparo);
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);         fputs(line,ficlog);
      codtab[1][2]=1;codtab[2][2]=2; */      }
   /* for(i=1; i <=m ;i++){       ungetc(c,ficpar);
      for(k=1; k <=cptcovn; k++){  
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);      for(i=1; i <=nlstate; i++){
      }        for(j=1; j <=nlstate+ndeath-1; j++){
      printf("\n");          fscanf(ficpar,"%1d%1d",&i1,&j1);
      }          if ((i1-i)*(j1-j)!=0){
      scanf("%d",i);*/            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                 exit(1);
   /*------------ gnuplot -------------*/          }
   strcpy(optionfilegnuplot,optionfilefiname);          printf("%1d%1d",i,j);
   if(mle==-3)          fprintf(ficparo,"%1d%1d",i1,j1);
     strcat(optionfilegnuplot,"-mort");          fprintf(ficlog,"%1d%1d",i1,j1);
   strcat(optionfilegnuplot,".gp");          for(k=1; k<=ncovmodel;k++){
             fscanf(ficpar,"%le",&delti3[i][j][k]);
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {            printf(" %le",delti3[i][j][k]);
     printf("Problem with file %s",optionfilegnuplot);            fprintf(ficparo," %le",delti3[i][j][k]);
   }            fprintf(ficlog," %le",delti3[i][j][k]);
   else{          }
     fprintf(ficgp,"\n# %s\n", version);           fscanf(ficpar,"\n");
     fprintf(ficgp,"# %s\n", optionfilegnuplot);           numlinepar++;
     fprintf(ficgp,"set missing 'NaNq'\n");          printf("\n");
   }          fprintf(ficparo,"\n");
   /*  fclose(ficgp);*/          fprintf(ficlog,"\n");
   /*--------- index.htm --------*/        }
       }
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */      fflush(ficlog);
   if(mle==-3)  
     strcat(optionfilehtm,"-mort");      delti=delti3[1][1];
   strcat(optionfilehtm,".htm");  
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {  
     printf("Problem with %s \n",optionfilehtm), exit(0);      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
   }   
       /* Reads comments: lines beginning with '#' */
   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);   
   }      matcov=matrix(1,npar,1,npar);
       for(i=1; i <=npar; i++){
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \        fscanf(ficpar,"%s",&str);
 <hr size=\"2\" color=\"#EC5E5E\"> \n\        if(mle==1)
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\          printf("%s",str);
 \n\        fprintf(ficlog,"%s",str);
 <hr  size=\"2\" color=\"#EC5E5E\">\        fprintf(ficparo,"%s",str);
  <ul><li><h4>Parameter files</h4>\n\        for(j=1; j <=i; j++){
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\          fscanf(ficpar," %le",&matcov[i][j]);
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\          if(mle==1){
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\            printf(" %.5le",matcov[i][j]);
  - Date and time at start: %s</ul>\n",\          }
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\          fprintf(ficlog," %.5le",matcov[i][j]);
           fileres,fileres,\          fprintf(ficparo," %.5le",matcov[i][j]);
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);        }
   fflush(fichtm);        fscanf(ficpar,"\n");
         numlinepar++;
   strcpy(pathr,path);        if(mle==1)
   strcat(pathr,optionfilefiname);          printf("\n");
   chdir(optionfilefiname); /* Move to directory named optionfile */        fprintf(ficlog,"\n");
           fprintf(ficparo,"\n");
   /* Calculates basic frequencies. Computes observed prevalence at single age      }
      and prints on file fileres'p'. */      for(i=1; i <=npar; i++)
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);        for(j=i+1;j<=npar;j++)
           matcov[i][j]=matcov[j][i];
   fprintf(fichtm,"\n");     
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\      if(mle==1)
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\        printf("\n");
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\      fprintf(ficlog,"\n");
           imx,agemin,agemax,jmin,jmax,jmean);     
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      fflush(ficlog);
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */     
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      /*-------- Rewriting parameter file ----------*/
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      strcpy(rfileres,"r");    /* "Rparameterfile */
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
           strcat(rfileres,".");    /* */
          strcat(rfileres,optionfilext);    /* Other files have txt extension */
   /* For Powell, parameters are in a vector p[] starting at p[1]      if((ficres =fopen(rfileres,"w"))==NULL) {
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */        printf("Problem writing new parameter file: %s\n", fileres);goto end;
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
       }
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/      fprintf(ficres,"#%s\n",version);
   if (mle==-3){    }    /* End of mle != -3 */
     ximort=matrix(1,NDIM,1,NDIM);  
     cens=ivector(1,n);    /*-------- data file ----------*/
     ageexmed=vector(1,n);    if((fic=fopen(datafile,"r"))==NULL)    {
     agecens=vector(1,n);      printf("Problem while opening datafile: %s\n", datafile);goto end;
     dcwave=ivector(1,n);      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
      }
     for (i=1; i<=imx; i++){  
       dcwave[i]=-1;    n= lastobs;
       for (j=1; j<=lastpass; j++)    severity = vector(1,maxwav);
         if (s[j][i]>nlstate) {    outcome=imatrix(1,maxwav+1,1,n);
           dcwave[i]=j;    num=lvector(1,n);
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/    moisnais=vector(1,n);
           break;    annais=vector(1,n);
         }    moisdc=vector(1,n);
     }    andc=vector(1,n);
     agedc=vector(1,n);
     for (i=1; i<=imx; i++) {    cod=ivector(1,n);
       if (wav[i]>0){    weight=vector(1,n);
         ageexmed[i]=agev[mw[1][i]][i];    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
         j=wav[i];agecens[i]=1.;     mint=matrix(1,maxwav,1,n);
         if (ageexmed[i]>1 & wav[i]>0) agecens[i]=agev[mw[j][i]][i];    anint=matrix(1,maxwav,1,n);
         cens[i]=1;    s=imatrix(1,maxwav+1,1,n);
             tab=ivector(1,NCOVMAX);
         if (ageexmed[i]<1) cens[i]=-1;    ncodemax=ivector(1,8);
         if (agedc[i]< AGESUP & agedc[i]>1 & dcwave[i]>firstpass & dcwave[i]<=lastpass) cens[i]=0 ;  
       }    i=1;
       else cens[i]=-1;    linei=0;
     }    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
           linei=linei+1;
     for (i=1;i<=NDIM;i++) {      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
       for (j=1;j<=NDIM;j++)        if(line[j] == '\t')
         ximort[i][j]=(i == j ? 1.0 : 0.0);          line[j] = ' ';
     }      }
       for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
     p[1]=0.1; p[2]=0.1;        ;
     /*printf("%lf %lf", p[1], p[2]);*/      };
           line[j+1]=0;  /* Trims blanks at end of line */
           if(line[0]=='#'){
   printf("Powell\n");  fprintf(ficlog,"Powell\n");        fprintf(ficlog,"Comment line\n%s\n",line);
   strcpy(filerespow,"pow-mort");         printf("Comment line\n%s\n",line);
   strcat(filerespow,fileres);        continue;
   if((ficrespow=fopen(filerespow,"w"))==NULL) {      }
     printf("Problem with resultfile: %s\n", filerespow);  
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);      for (j=maxwav;j>=1;j--){
   }        cutv(stra, strb,line,' ');
   fprintf(ficrespow,"# Powell\n# iter -2*LL");        errno=0;
   /*  for (i=1;i<=nlstate;i++)        lval=strtol(strb,&endptr,10);
     for(j=1;j<=nlstate+ndeath;j++)        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);        if( strb[0]=='\0' || (*endptr != '\0')){
   */          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(ficrespow,"\n");          exit(1);
         }
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);        s[j][i]=lval;
     fclose(ficrespow);       
             strcpy(line,stra);
     hesscov(matcov, p, NDIM,delti, 1e-4, gompertz);         cutv(stra, strb,line,' ');
         if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     for(i=1; i <=NDIM; i++)        }
       for(j=i+1;j<=NDIM;j++)        else  if(iout=sscanf(strb,"%s.") != 0){
         matcov[i][j]=matcov[j][i];          month=99;
               year=9999;
     printf("\nCovariance matrix\n ");        }else{
     for(i=1; i <=NDIM; i++) {          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);
       for(j=1;j<=NDIM;j++){           exit(1);
         printf("%f ",matcov[i][j]);        }
       }        anint[j][i]= (double) year;
       printf("\n ");        mint[j][i]= (double)month;
     }        strcpy(line,stra);
           } /* ENd Waves */
     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++)       cutv(stra, strb,line,' ');
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */      }
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
             month=99;
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \        year=9999;
                      stepm, weightopt,\      }else{
                      model,imx,p,matcov);        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);
   } /* Endof if mle==-3 */        exit(1);
       }
   else{ /* For mle >=1 */      andc[i]=(double) year;
         moisdc[i]=(double) month;
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */      strcpy(line,stra);
     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);     
     for (k=1; k<=npar;k++)      cutv(stra, strb,line,' ');
       printf(" %d %8.5f",k,p[k]);      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     printf("\n");      }
     globpr=1; /* to print the contributions */      else  if(iout=sscanf(strb,"%s.") != 0){
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */        month=99;
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);        year=9999;
     for (k=1; k<=npar;k++)      }else{
       printf(" %d %8.5f",k,p[k]);        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);
     printf("\n");        exit(1);
     if(mle>=1){ /* Could be 1 or 2 */      }
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);      annais[i]=(double)(year);
     }      moisnais[i]=(double)(month);
           strcpy(line,stra);
     /*--------- 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);      cutv(stra, strb,line,' ');
           errno=0;
           dval=strtod(strb,&endptr);
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      if( strb[0]=='\0' || (*endptr != '\0')){
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        exit(1);
     for(i=1,jk=1; i <=nlstate; i++){      }
       for(k=1; k <=(nlstate+ndeath); k++){      weight[i]=dval;
         if (k != i) {      strcpy(line,stra);
           printf("%d%d ",i,k);     
           fprintf(ficlog,"%d%d ",i,k);      for (j=ncovcol;j>=1;j--){
           fprintf(ficres,"%1d%1d ",i,k);        cutv(stra, strb,line,' ');
           for(j=1; j <=ncovmodel; j++){        errno=0;
             printf("%f ",p[jk]);        lval=strtol(strb,&endptr,10);
             fprintf(ficlog,"%f ",p[jk]);        if( strb[0]=='\0' || (*endptr != '\0')){
             fprintf(ficres,"%f ",p[jk]);          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);
             jk++;           exit(1);
           }        }
           printf("\n");        if(lval <-1 || lval >1){
           fprintf(ficlog,"\n");          printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
           fprintf(ficres,"\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 \
       }   For example, for multinomial values like 1, 2 and 3,\n \
     }   build V1=0 V2=0 for the reference value (1),\n \
     if(mle!=0){          V1=1 V2=0 for (2) \n \
       /* Computing hessian and covariance matrix */   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
       ftolhess=ftol; /* Usually correct */   output of IMaCh is often meaningless.\n \
       hesscov(matcov, p, npar, delti, ftolhess, func);   Exiting.\n",lval,linei, i,line,j);
     }          exit(1);
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");        }
     printf("# Scales (for hessian or gradient estimation)\n");        covar[j][i]=(double)(lval);
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");        strcpy(line,stra);
     for(i=1,jk=1; i <=nlstate; i++){      }
       for(j=1; j <=nlstate+ndeath; j++){      lstra=strlen(stra);
         if (j!=i) {     
           fprintf(ficres,"%1d%1d",i,j);      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
           printf("%1d%1d",i,j);        stratrunc = &(stra[lstra-9]);
           fprintf(ficlog,"%1d%1d",i,j);        num[i]=atol(stratrunc);
           for(k=1; k<=ncovmodel;k++){      }
             printf(" %.5e",delti[jk]);      else
             fprintf(ficlog," %.5e",delti[jk]);        num[i]=atol(stra);
             fprintf(ficres," %.5e",delti[jk]);      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
             jk++;        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");      i=i+1;
           fprintf(ficlog,"\n");    } /* End loop reading  data */
           fprintf(ficres,"\n");    fclose(fic);
         }    /* printf("ii=%d", ij);
       }       scanf("%d",i);*/
     }    imx=i-1; /* Number of individuals */
       
     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 (i=1; i<=imx; i++){
     if(mle>=1)      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
       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 ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
     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");      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
     /* # 121 Var(a12)\n\ */      }*/
     /* # 122 Cov(b12,a12) Var(b12)\n\ */     /*  for (i=1; i<=imx; i++){
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */       if (s[4][i]==9)  s[4][i]=-1;
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\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]));}*/
     /* # 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\ */    /* for (i=1; i<=imx; i++) */
     /* # 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" */     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
            else weight[i]=1;*/
       
     /* Just to have a covariance matrix which will be more understandable    /* Calculation of the number of parameters from char model */
        even is we still don't want to manage dictionary of variables    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
     */    Tprod=ivector(1,15);
     for(itimes=1;itimes<=2;itimes++){    Tvaraff=ivector(1,15);
       jj=0;    Tvard=imatrix(1,15,1,2);
       for(i=1; i <=nlstate; i++){    Tage=ivector(1,15);      
         for(j=1; j <=nlstate+ndeath; j++){     
           if(j==i) continue;    if (strlen(model) >1){ /* If there is at least 1 covariate */
           for(k=1; k<=ncovmodel;k++){      j=0, j1=0, k1=1, k2=1;
             jj++;      j=nbocc(model,'+'); /* j=Number of '+' */
             ca[0]= k+'a'-1;ca[1]='\0';      j1=nbocc(model,'*'); /* j1=Number of '*' */
             if(itimes==1){      cptcovn=j+1;
               if(mle>=1)      cptcovprod=j1; /*Number of products */
                 printf("#%1d%1d%d",i,j,k);     
               fprintf(ficlog,"#%1d%1d%d",i,j,k);      strcpy(modelsav,model);
               fprintf(ficres,"#%1d%1d%d",i,j,k);      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
             }else{        printf("Error. Non available option model=%s ",model);
               if(mle>=1)        fprintf(ficlog,"Error. Non available option model=%s ",model);
                 printf("%1d%1d%d",i,j,k);        goto end;
               fprintf(ficlog,"%1d%1d%d",i,j,k);      }
               fprintf(ficres,"%1d%1d%d",i,j,k);     
             }      /* This loop fills the array Tvar from the string 'model'.*/
             ll=0;  
             for(li=1;li <=nlstate; li++){      for(i=(j+1); i>=1;i--){
               for(lj=1;lj <=nlstate+ndeath; lj++){        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
                 if(lj==li) continue;        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                 for(lk=1;lk<=ncovmodel;lk++){        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   ll++;        /*scanf("%d",i);*/
                   if(ll<=jj){        if (strchr(strb,'*')) {  /* Model includes a product */
                     cb[0]= lk +'a'-1;cb[1]='\0';          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
                     if(ll<jj){          if (strcmp(strc,"age")==0) { /* Vn*age */
                       if(itimes==1){            cptcovprod--;
                         if(mle>=1)            cutv(strb,stre,strd,'V');
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);            cptcovage++;
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);              Tage[cptcovage]=i;
                       }else{              /*printf("stre=%s ", stre);*/
                         if(mle>=1)          }
                           printf(" %.5e",matcov[jj][ll]);           else if (strcmp(strd,"age")==0) { /* or age*Vn */
                         fprintf(ficlog," %.5e",matcov[jj][ll]);             cptcovprod--;
                         fprintf(ficres," %.5e",matcov[jj][ll]);             cutv(strb,stre,strc,'V');
                       }            Tvar[i]=atoi(stre);
                     }else{            cptcovage++;
                       if(itimes==1){            Tage[cptcovage]=i;
                         if(mle>=1)          }
                           printf(" Var(%s%1d%1d)",ca,i,j);          else {  /* Age is not in the model */
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);            Tvar[i]=ncovcol+k1;
                       }else{            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
                         if(mle>=1)            Tprod[k1]=i;
                           printf(" %.5e",matcov[jj][ll]);             Tvard[k1][1]=atoi(strc); /* m*/
                         fprintf(ficlog," %.5e",matcov[jj][ll]);             Tvard[k1][2]=atoi(stre); /* n */
                         fprintf(ficres," %.5e",matcov[jj][ll]);             Tvar[cptcovn+k2]=Tvard[k1][1];
                       }            Tvar[cptcovn+k2+1]=Tvard[k1][2];
                     }            for (k=1; k<=lastobs;k++)
                   }              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
                 } /* end lk */            k1++;
               } /* end lj */            k2=k2+2;
             } /* end li */          }
             if(mle>=1)        }
               printf("\n");        else { /* no more sum */
             fprintf(ficlog,"\n");          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
             fprintf(ficres,"\n");         /*  scanf("%d",i);*/
             numlinepar++;        cutv(strd,strc,strb,'V');
           } /* end k*/        Tvar[i]=atoi(strc);
         } /*end j */        }
       } /* end i */        strcpy(modelsav,stra);  
     } /* end itimes */        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
               scanf("%d",i);*/
     fflush(ficlog);      } /* end of loop + */
     fflush(ficres);    } /* end model */
        
     while((c=getc(ficpar))=='#' && c!= EOF){    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
       ungetc(c,ficpar);      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
       fgets(line, MAXLINE, ficpar);  
       puts(line);    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
       fputs(line,ficparo);    printf("cptcovprod=%d ", cptcovprod);
     }    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
     ungetc(c,ficpar);  
         scanf("%d ",i);*/
     estepm=0;  
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);      /*  if(mle==1){*/
     if (estepm==0 || estepm < stepm) estepm=stepm;    if (weightopt != 1) { /* Maximisation without weights*/
     if (fage <= 2) {      for(i=1;i<=n;i++) weight[i]=1.0;
       bage = ageminpar;    }
       fage = agemaxpar;      /*-calculation of age at interview from date of interview and age at death -*/
     }    agev=matrix(1,maxwav,1,imx);
       
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");    for (i=1; i<=imx; i++) {
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);      for(m=2; (m<= maxwav); m++) {
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);        if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
               anint[m][i]=9999;
     while((c=getc(ficpar))=='#' && c!= EOF){          s[m][i]=-1;
       ungetc(c,ficpar);        }
       fgets(line, MAXLINE, ficpar);        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
       puts(line);          nberr++;
       fputs(line,ficparo);          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);
     }          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);
     ungetc(c,ficpar);          s[m][i]=-1;
             }
     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);        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
     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);          nberr++;
     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("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]);
     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,"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]);
     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);          s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
             }
     while((c=getc(ficpar))=='#' && c!= EOF){      }
       ungetc(c,ficpar);    }
       fgets(line, MAXLINE, ficpar);  
       puts(line);    for (i=1; i<=imx; i++)  {
       fputs(line,ficparo);      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
     }      for(m=firstpass; (m<= lastpass); m++){
     ungetc(c,ficpar);        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
               if (s[m][i] >= nlstate+1) {
                 if(agedc[i]>0)
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;                agev[m][i]=agedc[i];
                 /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
     fscanf(ficpar,"pop_based=%d\n",&popbased);              else {
     fprintf(ficparo,"pop_based=%d\n",popbased);                   if ((int)andc[i]!=9999){
     fprintf(ficres,"pop_based=%d\n",popbased);                     nbwarn++;
                       printf("Warning negative age at death: %ld line:%d\n",num[i],i);
     while((c=getc(ficpar))=='#' && c!= EOF){                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
       ungetc(c,ficpar);                  agev[m][i]=-1;
       fgets(line, MAXLINE, ficpar);                }
       puts(line);              }
       fputs(line,ficparo);          }
     }          else if(s[m][i] !=9){ /* Standard case, age in fractional
     ungetc(c,ficpar);                                   years but with the precision of a month */
                 agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
     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);            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
     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);              agev[m][i]=1;
     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);            else if(agev[m][i] <agemin){
     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);              agemin=agev[m][i];
     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);              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
     /* day and month of proj2 are not used but only year anproj2.*/            }
                 else if(agev[m][i] >agemax){
                   agemax=agev[m][i];
                   /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/            }
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/            /*agev[m][i]=anint[m][i]-annais[i];*/
                 /*     agev[m][i] = age[i]+2*m;*/
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */          }
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);          else { /* =9 */
                 agev[m][i]=1;
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\            s[m][i]=-1;
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\          }
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);        }
               else /*= 0 Unknown */
    /*------------ free_vector  -------------*/          agev[m][i]=1;
    /*  chdir(path); */      }
       
     free_ivector(wav,1,imx);    }
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);    for (i=1; i<=imx; i++)  {
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);      for(m=firstpass; (m<=lastpass); m++){
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);           if (s[m][i] > (nlstate+ndeath)) {
     free_lvector(num,1,n);          nberr++;
     free_vector(agedc,1,n);          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);    
     /*free_matrix(covar,0,NCOVMAX,1,n);*/          fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);    
     /*free_matrix(covar,1,NCOVMAX,1,n);*/          goto end;
     fclose(ficparo);        }
     fclose(ficres);      }
     }
   
     /*--------------- Prevalence limit  (stable prevalence) --------------*/    /*for (i=1; i<=imx; i++){
       for (m=firstpass; (m<lastpass); m++){
     strcpy(filerespl,"pl");       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
     strcat(filerespl,fileres);  }
     if((ficrespl=fopen(filerespl,"w"))==NULL) {  
       printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;  }*/
       fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;  
     }  
     printf("Computing stable prevalence: result on file '%s' \n", filerespl);    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
     fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
     fprintf(ficrespl,"#Stable prevalence \n");  
     fprintf(ficrespl,"#Age ");    agegomp=(int)agemin;
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);    free_vector(severity,1,maxwav);
     fprintf(ficrespl,"\n");    free_imatrix(outcome,1,maxwav+1,1,n);
       free_vector(moisnais,1,n);
     prlim=matrix(1,nlstate,1,nlstate);    free_vector(annais,1,n);
     /* free_matrix(mint,1,maxwav,1,n);
     agebase=ageminpar;       free_matrix(anint,1,maxwav,1,n);*/
     agelim=agemaxpar;    free_vector(moisdc,1,n);
     ftolpl=1.e-10;    free_vector(andc,1,n);
     i1=cptcoveff;  
     if (cptcovn < 1){i1=1;}     
     wav=ivector(1,imx);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){    dh=imatrix(1,lastpass-firstpass+1,1,imx);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){    bh=imatrix(1,lastpass-firstpass+1,1,imx);
         k=k+1;    mw=imatrix(1,lastpass-firstpass+1,1,imx);
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/     
         fprintf(ficrespl,"\n#******");    /* Concatenates waves */
         printf("\n#******");    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
         fprintf(ficlog,"\n#******");  
         for(j=1;j<=cptcoveff;j++) {    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
           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]]);    Tcode=ivector(1,100);
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
         }    ncodemax[1]=1;
         fprintf(ficrespl,"******\n");    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
         printf("******\n");       
         fprintf(ficlog,"******\n");    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
                                            the estimations*/
         for (age=agebase; age<=agelim; age++){    h=0;
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);    m=pow(2,cptcoveff);
           fprintf(ficrespl,"%.0f ",age );   
           for(j=1;j<=cptcoveff;j++)    for(k=1;k<=cptcoveff; k++){
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      for(i=1; i <=(m/pow(2,k));i++){
           for(i=1; i<=nlstate;i++)        for(j=1; j <= ncodemax[k]; j++){
             fprintf(ficrespl," %.5f", prlim[i][i]);          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
           fprintf(ficrespl,"\n");            h++;
         }            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
       }            /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
     }          }
     fclose(ficrespl);        }
       }
     /*------------- h Pij x at various ages ------------*/    }
       /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);       codtab[1][2]=1;codtab[2][2]=2; */
     if((ficrespij=fopen(filerespij,"w"))==NULL) {    /* for(i=1; i <=m ;i++){
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;       for(k=1; k <=cptcovn; k++){
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
     }       }
     printf("Computing pij: result on file '%s' \n", filerespij);       printf("\n");
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);       }
          scanf("%d",i);*/
     stepsize=(int) (stepm+YEARM-1)/YEARM;     
     /*if (stepm<=24) stepsize=2;*/    /*------------ gnuplot -------------*/
     strcpy(optionfilegnuplot,optionfilefiname);
     agelim=AGESUP;    if(mle==-3)
     hstepm=stepsize*YEARM; /* Every year of age */      strcat(optionfilegnuplot,"-mort");
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */     strcat(optionfilegnuplot,".gp");
   
     /* hstepm=1;   aff par mois*/    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
       printf("Problem with file %s",optionfilegnuplot);
     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++){    else{
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      fprintf(ficgp,"\n# %s\n", version);
         k=k+1;      fprintf(ficgp,"# %s\n", optionfilegnuplot);
         fprintf(ficrespij,"\n#****** ");      fprintf(ficgp,"set missing 'NaNq'\n");
         for(j=1;j<=cptcoveff;j++)     }
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);    /*  fclose(ficgp);*/
         fprintf(ficrespij,"******\n");    /*--------- index.htm --------*/
           
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     if(mle==-3)
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */      strcat(optionfilehtm,"-mort");
     strcat(optionfilehtm,".htm");
           /*      nhstepm=nhstepm*YEARM; aff par mois*/    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
       printf("Problem with %s \n",optionfilehtm), exit(0);
           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);      strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");    strcat(optionfilehtmcov,"-cov.htm");
           for(i=1; i<=nlstate;i++)    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
             for(j=1; j<=nlstate+ndeath;j++)      printf("Problem with %s \n",optionfilehtmcov), exit(0);
               fprintf(ficrespij," %1d-%1d",i,j);    }
           fprintf(ficrespij,"\n");    else{
           for (h=0; h<=nhstepm; h++){    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );  <hr size=\"2\" color=\"#EC5E5E\"> \n\
             for(i=1; i<=nlstate;i++)  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
               for(j=1; j<=nlstate+ndeath;j++)            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);    }
             fprintf(ficrespij,"\n");  
           }    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  <hr size=\"2\" color=\"#EC5E5E\"> \n\
           fprintf(ficrespij,"\n");  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
         }  \n\
       }  <hr  size=\"2\" color=\"#EC5E5E\">\
     }   <ul><li><h4>Parameter files</h4>\n\
    - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax);   - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
    - Log file of the run: <a href=\"%s\">%s</a><br>\n\
     fclose(ficrespij);   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
    - Date and time at start: %s</ul>\n",\
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
     for(i=1;i<=AGESUP;i++)            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
       for(j=1;j<=NCOVMAX;j++)            fileres,fileres,\
         for(k=1;k<=NCOVMAX;k++)            filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
           probs[i][j][k]=0.;    fflush(fichtm);
   
     /*---------- Forecasting ------------------*/    strcpy(pathr,path);
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/    strcat(pathr,optionfilefiname);
     if(prevfcast==1){    chdir(optionfilefiname); /* Move to directory named optionfile */
       /*    if(stepm ==1){*/   
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);    /* Calculates basic frequencies. Computes observed prevalence at single age
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/       and prints on file fileres'p'. */
       /*      }  */    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
       /*      else{ */  
       /*        erreur=108; */    fprintf(fichtm,"\n");
       /*        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(fichtm,"<br>Total number of observations=%d <br>\n\
       /*        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); */  Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
       /*      } */  Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
     }            imx,agemin,agemax,jmin,jmax,jmean);
       pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     /*---------- Health expectancies and variances ------------*/      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     strcpy(filerest,"t");      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
     strcat(filerest,fileres);     
     if((ficrest=fopen(filerest,"w"))==NULL) {     
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;    /* For Powell, parameters are in a vector p[] starting at p[1]
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;       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) */
     printf("Computing Total LEs with variances: file '%s' \n", filerest);   
     fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest);     globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
   
     if (mle==-3){
     strcpy(filerese,"e");      ximort=matrix(1,NDIM,1,NDIM);
     strcat(filerese,fileres);      cens=ivector(1,n);
     if((ficreseij=fopen(filerese,"w"))==NULL) {      ageexmed=vector(1,n);
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);      agecens=vector(1,n);
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);      dcwave=ivector(1,n);
     }   
     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);        dcwave[i]=-1;
         for (m=firstpass; m<=lastpass; m++)
     strcpy(fileresv,"v");          if (s[m][i]>nlstate) {
     strcat(fileresv,fileres);            dcwave[i]=m;
     if((ficresvij=fopen(fileresv,"w"))==NULL) {            /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);            break;
       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);      for (i=1; i<=imx; i++) {
         if (wav[i]>0){
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */          ageexmed[i]=agev[mw[1][i]][i];
     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);          j=wav[i];
     /*  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",\          agecens[i]=1.;
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);  
     */          if (ageexmed[i]> 1 && wav[i] > 0){
             agecens[i]=agev[mw[j][i]][i];
     if (mobilav!=0) {            cens[i]= 1;
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          }else if (ageexmed[i]< 1)
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){            cens[i]= -1;
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);          if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
         printf(" Error in movingaverage mobilav=%d\n",mobilav);            cens[i]=0 ;
       }        }
     }        else cens[i]=-1;
       }
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){     
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      for (i=1;i<=NDIM;i++) {
         k=k+1;         for (j=1;j<=NDIM;j++)
         fprintf(ficrest,"\n#****** ");          ximort[i][j]=(i == j ? 1.0 : 0.0);
         for(j=1;j<=cptcoveff;j++)       }
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);     
         fprintf(ficrest,"******\n");      p[1]=0.0268; p[NDIM]=0.083;
       /*printf("%lf %lf", p[1], p[2]);*/
         fprintf(ficreseij,"\n#****** ");     
         for(j=1;j<=cptcoveff;j++)      
           fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      printf("Powell\n");  fprintf(ficlog,"Powell\n");
         fprintf(ficreseij,"******\n");      strcpy(filerespow,"pow-mort");
       strcat(filerespow,fileres);
         fprintf(ficresvij,"\n#****** ");      if((ficrespow=fopen(filerespow,"w"))==NULL) {
         for(j=1;j<=cptcoveff;j++)         printf("Problem with resultfile: %s\n", filerespow);
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
         fprintf(ficresvij,"******\n");      }
       fprintf(ficrespow,"# Powell\n# iter -2*LL");
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      /*  for (i=1;i<=nlstate;i++)
         oldm=oldms;savm=savms;          for(j=1;j<=nlstate+ndeath;j++)
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov);            if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
        */
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      fprintf(ficrespow,"\n");
         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);      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
         if(popbased==1){      fclose(ficrespow);
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav);     
         }      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
   
        for(i=1; i <=NDIM; i++)
         fprintf(ficrest,"#Total LEs with variances: e.. (std) ");        for(j=i+1;j<=NDIM;j++)
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);          matcov[i][j]=matcov[j][i];
         fprintf(ficrest,"\n");     
       printf("\nCovariance matrix\n ");
         epj=vector(1,nlstate+1);      for(i=1; i <=NDIM; i++) {
         for(age=bage; age <=fage ;age++){        for(j=1;j<=NDIM;j++){
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);          printf("%f ",matcov[i][j]);
           if (popbased==1) {        }
             if(mobilav ==0){        printf("\n ");
               for(i=1; i<=nlstate;i++)      }
                 prlim[i][i]=probs[(int)age][i][k];     
             }else{ /* mobilav */       printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
               for(i=1; i<=nlstate;i++)      for (i=1;i<=NDIM;i++)
                 prlim[i][i]=mobaverage[(int)age][i][k];        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);
           fprintf(ficrest," %4.0f",age);      tpop=vector(1,AGESUP);
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){      lsurv[agegomp]=100000;
             for(i=1, epj[j]=0.;i <=nlstate;i++) {     
               epj[j] += prlim[i][i]*eij[i][j][(int)age];      for (k=agegomp;k<=AGESUP;k++) {
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/        agemortsup=k;
             }        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
             epj[nlstate+1] +=epj[j];      }
           }     
       for (k=agegomp;k<agemortsup;k++)
           for(i=1, vepp=0.;i <=nlstate;i++)        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
             for(j=1;j <=nlstate;j++)     
               vepp += vareij[i][j][(int)age];      for (k=agegomp;k<agemortsup;k++){
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));        lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
           for(j=1;j <=nlstate;j++){        sumlpop=sumlpop+lpop[k];
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));      }
           }     
           fprintf(ficrest,"\n");      tpop[agegomp]=sumlpop;
         }      for (k=agegomp;k<(agemortsup-3);k++){
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);        /*  tpop[k+1]=2;*/
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);        tpop[k+1]=tpop[k]-lpop[k];
         free_vector(epj,1,nlstate+1);      }
       }     
     }     
     free_vector(weight,1,n);      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
     free_imatrix(Tvard,1,15,1,2);      for (k=agegomp;k<(agemortsup-2);k++)
     free_imatrix(s,1,maxwav+1,1,n);        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]);
     free_matrix(anint,1,maxwav,1,n);      
     free_matrix(mint,1,maxwav,1,n);     
     free_ivector(cod,1,n);      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     free_ivector(tab,1,NCOVMAX);      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     fclose(ficreseij);     
     fclose(ficresvij);      printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
     fclose(ficrest);                       stepm, weightopt,\
     fclose(ficpar);                       model,imx,p,matcov,agemortsup);
        
     /*------- Variance of stable prevalence------*/         free_vector(lsurv,1,AGESUP);
       free_vector(lpop,1,AGESUP);
     strcpy(fileresvpl,"vpl");      free_vector(tpop,1,AGESUP);
     strcat(fileresvpl,fileres);    } /* Endof if mle==-3 */
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {   
       printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);    else{ /* For mle >=1 */
       exit(0);   
     }      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
     printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);      printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
       for (k=1; k<=npar;k++)
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){        printf(" %d %8.5f",k,p[k]);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      printf("\n");
         k=k+1;      globpr=1; /* to print the contributions */
         fprintf(ficresvpl,"\n#****** ");      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
         for(j=1;j<=cptcoveff;j++)       printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      for (k=1; k<=npar;k++)
         fprintf(ficresvpl,"******\n");        printf(" %d %8.5f",k,p[k]);
             printf("\n");
         varpl=matrix(1,nlstate,(int) bage, (int) fage);      if(mle>=1){ /* Could be 1 or 2 */
         oldm=oldms;savm=savms;        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
         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);     
       }      /*--------- 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);
      
     fclose(ficresvpl);     
       fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     /*---------- End : free ----------------*/      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);      for(i=1,jk=1; i <=nlstate; i++){
         for(k=1; k <=(nlstate+ndeath); k++){
   }  /* mle==-3 arrives here for freeing */          if (k != i) {
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);            printf("%d%d ",i,k);
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);            fprintf(ficlog,"%d%d ",i,k);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);            fprintf(ficres,"%1d%1d ",i,k);
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);            for(j=1; j <=ncovmodel; j++){
                 printf("%lf ",p[jk]);
     free_matrix(covar,0,NCOVMAX,1,n);              fprintf(ficlog,"%lf ",p[jk]);
     free_matrix(matcov,1,npar,1,npar);              fprintf(ficres,"%lf ",p[jk]);
     /*free_vector(delti,1,npar);*/              jk++;
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);             }
     free_matrix(agev,1,maxwav,1,imx);            printf("\n");
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);            fprintf(ficlog,"\n");
             fprintf(ficres,"\n");
     free_ivector(ncodemax,1,8);          }
     free_ivector(Tvar,1,15);        }
     free_ivector(Tprod,1,15);      }
     free_ivector(Tvaraff,1,15);      if(mle!=0){
     free_ivector(Tage,1,15);        /* Computing hessian and covariance matrix */
     free_ivector(Tcode,1,100);        ftolhess=ftol; /* Usually correct */
         hesscov(matcov, p, npar, delti, ftolhess, func);
       }
   fflush(fichtm);      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
   fflush(ficgp);      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++){
   if((nberr >0) || (nbwarn>0)){        for(j=1; j <=nlstate+ndeath; j++){
     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);          if (j!=i) {
     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);            fprintf(ficres,"%1d%1d",i,j);
   }else{            printf("%1d%1d",i,j);
     printf("End of Imach\n");            fprintf(ficlog,"%1d%1d",i,j);
     fprintf(ficlog,"End of Imach\n");            for(k=1; k<=ncovmodel;k++){
   }              printf(" %.5e",delti[jk]);
   printf("See log file on %s\n",filelog);              fprintf(ficlog," %.5e",delti[jk]);
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */              fprintf(ficres," %.5e",delti[jk]);
   (void) gettimeofday(&end_time,&tzp);              jk++;
   tm = *localtime(&end_time.tv_sec);            }
   tmg = *gmtime(&end_time.tv_sec);            printf("\n");
   strcpy(strtend,asctime(&tm));            fprintf(ficlog,"\n");
   printf("Local time at start %s\nLocaltime at end   %s",strstart, strtend);             fprintf(ficres,"\n");
   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(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      if(mle>=1)
   /*  printf("Total time was %d uSec.\n", total_usecs);*/        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(fileappend(fichtm,optionfilehtm)){ */      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");
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);      /* # 121 Var(a12)\n\ */
   fclose(fichtm);      /* # 122 Cov(b12,a12) Var(b12)\n\ */
   fclose(fichtmcov);      /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
   fclose(ficgp);      /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
   fclose(ficlog);      /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
   /*------ End -----------*/      /* # 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\ */
   chdir(path);      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
   strcpy(plotcmd,"\"");     
   strcat(plotcmd,pathimach);     
   strcat(plotcmd,GNUPLOTPROGRAM);      /* Just to have a covariance matrix which will be more understandable
   strcat(plotcmd,"\"");         even is we still don't want to manage dictionary of variables
   strcat(plotcmd," ");      */
   strcat(plotcmd,optionfilegnuplot);      for(itimes=1;itimes<=2;itimes++){
   printf("Starting graphs with: %s",plotcmd);fflush(stdout);        jj=0;
   if((outcmd=system(plotcmd)) != 0){        for(i=1; i <=nlstate; i++){
     printf(" Problem with gnuplot\n");          for(j=1; j <=nlstate+ndeath; j++){
   }            if(j==i) continue;
   printf(" Wait...");            for(k=1; k<=ncovmodel;k++){
   while (z[0] != 'q') {              jj++;
     /* chdir(path); */              ca[0]= k+'a'-1;ca[1]='\0';
     printf("\nType e to edit output files, g to graph again and q for exiting: ");              if(itimes==1){
     scanf("%s",z);                if(mle>=1)
 /*     if (z[0] == 'c') system("./imach"); */                  printf("#%1d%1d%d",i,j,k);
     if (z[0] == 'e') {                fprintf(ficlog,"#%1d%1d%d",i,j,k);
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);                fprintf(ficres,"#%1d%1d%d",i,j,k);
       system(optionfilehtm);              }else{
     }                if(mle>=1)
     else if (z[0] == 'g') system(plotcmd);                  printf("%1d%1d%d",i,j,k);
     else if (z[0] == 'q') exit(0);                fprintf(ficlog,"%1d%1d%d",i,j,k);
   }                fprintf(ficres,"%1d%1d%d",i,j,k);
   end:              }
   while (z[0] != 'q') {              ll=0;
     printf("\nType  q for exiting: ");              for(li=1;li <=nlstate; li++){
     scanf("%s",z);                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.99  
changed lines
  Added in v.1.125


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