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

version 1.108, 2006/01/19 18:05:42 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.108  2006/01/19 18:05:42  lievre    Revision 1.125  2006/04/04 15:20:31  lievre
   Gnuplot problem appeared...    Errors in calculation of health expectancies. Age was not initialized.
   To be fixed    Forecasting file added.
   
   Revision 1.107  2006/01/19 16:20:37  brouard    Revision 1.124  2006/03/22 17:13:53  lievre
   Test existence of gnuplot in imach path    Parameters are printed with %lf instead of %f (more numbers after the comma).
     The log-likelihood is printed in the log file
   Revision 1.106  2006/01/19 13:24:36  brouard  
   Some cleaning and links added in html output    Revision 1.123  2006/03/20 10:52:43  brouard
     * imach.c (Module): <title> changed, corresponds to .htm file
   Revision 1.105  2006/01/05 20:23:19  lievre    name. <head> headers where missing.
   *** empty log message ***  
     * imach.c (Module): Weights can have a decimal point as for
   Revision 1.104  2005/09/30 16:11:43  lievre    English (a comma might work with a correct LC_NUMERIC environment,
   (Module): sump fixed, loop imx fixed, and simplifications.    otherwise the weight is truncated).
   (Module): If the status is missing at the last wave but we know    Modification of warning when the covariates values are not 0 or
   that the person is alive, then we can code his/her status as -2    1.
   (instead of missing=-1 in earlier versions) and his/her    Version 0.98g
   contributions to the likelihood is 1 - Prob of dying from last  
   health status (= 1-p13= p11+p12 in the easiest case of somebody in    Revision 1.122  2006/03/20 09:45:41  brouard
   the healthy state at last known wave). Version is 0.98    (Module): Weights can have a decimal point as for
     English (a comma might work with a correct LC_NUMERIC environment,
   Revision 1.103  2005/09/30 15:54:49  lievre    otherwise the weight is truncated).
   (Module): sump fixed, loop imx fixed, and simplifications.    Modification of warning when the covariates values are not 0 or
     1.
   Revision 1.102  2004/09/15 17:31:30  brouard    Version 0.98g
   Add the possibility to read data file including tab characters.  
     Revision 1.121  2006/03/16 17:45:01  lievre
   Revision 1.101  2004/09/15 10:38:38  brouard    * imach.c (Module): Comments concerning covariates added
   Fix on curr_time  
     * imach.c (Module): refinements in the computation of lli if
   Revision 1.100  2004/07/12 18:29:06  brouard    status=-2 in order to have more reliable computation if stepm is
   Add version for Mac OS X. Just define UNIX in Makefile    not 1 month. Version 0.98f
   
   Revision 1.99  2004/06/05 08:57:40  brouard    Revision 1.120  2006/03/16 15:10:38  lievre
   *** empty log message ***    (Module): refinements in the computation of lli if
     status=-2 in order to have more reliable computation if stepm is
   Revision 1.98  2004/05/16 15:05:56  brouard    not 1 month. Version 0.98f
   New version 0.97 . First attempt to estimate force of mortality  
   directly from the data i.e. without the need of knowing the health    Revision 1.119  2006/03/15 17:42:26  brouard
   state at each age, but using a Gompertz model: log u =a + b*age .    (Module): Bug if status = -2, the loglikelihood was
   This is the basic analysis of mortality and should be done before any    computed as likelihood omitting the logarithm. Version O.98e
   other analysis, in order to test if the mortality estimated from the  
   cross-longitudinal survey is different from the mortality estimated    Revision 1.118  2006/03/14 18:20:07  brouard
   from other sources like vital statistic data.    (Module): varevsij Comments added explaining the second
     table of variances if popbased=1 .
   The same imach parameter file can be used but the option for mle should be -3.    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
     (Module): Function pstamp added
   Agnès, who wrote this part of the code, tried to keep most of the    (Module): Version 0.98d
   former routines in order to include the new code within the former code.  
     Revision 1.117  2006/03/14 17:16:22  brouard
   The output is very simple: only an estimate of the intercept and of    (Module): varevsij Comments added explaining the second
   the slope with 95% confident intervals.    table of variances if popbased=1 .
     (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   Current limitations:    (Module): Function pstamp added
   A) Even if you enter covariates, i.e. with the    (Module): Version 0.98d
   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.  
   B) There is no computation of Life Expectancy nor Life Table.    Revision 1.116  2006/03/06 10:29:27  brouard
     (Module): Variance-covariance wrong links and
   Revision 1.97  2004/02/20 13:25:42  lievre    varian-covariance of ej. is needed (Saito).
   Version 0.96d. Population forecasting command line is (temporarily)  
   suppressed.    Revision 1.115  2006/02/27 12:17:45  brouard
     (Module): One freematrix added in mlikeli! 0.98c
   Revision 1.96  2003/07/15 15:38:55  brouard  
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is    Revision 1.114  2006/02/26 12:57:58  brouard
   rewritten within the same printf. Workaround: many printfs.    (Module): Some improvements in processing parameter
     filename with strsep.
   Revision 1.95  2003/07/08 07:54:34  brouard  
   * imach.c (Repository):    Revision 1.113  2006/02/24 14:20:24  brouard
   (Repository): Using imachwizard code to output a more meaningful covariance    (Module): Memory leaks checks with valgrind and:
   matrix (cov(a12,c31) instead of numbers.    datafile was not closed, some imatrix were not freed and on matrix
     allocation too.
   Revision 1.94  2003/06/27 13:00:02  brouard  
   Just cleaning    Revision 1.112  2006/01/30 09:55:26  brouard
     (Module): Back to gnuplot.exe instead of wgnuplot.exe
   Revision 1.93  2003/06/25 16:33:55  brouard  
   (Module): On windows (cygwin) function asctime_r doesn't    Revision 1.111  2006/01/25 20:38:18  brouard
   exist so I changed back to asctime which exists.    (Module): Lots of cleaning and bugs added (Gompertz)
   (Module): Version 0.96b    (Module): Comments can be added in data file. Missing date values
     can be a simple dot '.'.
   Revision 1.92  2003/06/25 16:30:45  brouard  
   (Module): On windows (cygwin) function asctime_r doesn't    Revision 1.110  2006/01/25 00:51:50  brouard
   exist so I changed back to asctime which exists.    (Module): Lots of cleaning and bugs added (Gompertz)
   
   Revision 1.91  2003/06/25 15:30:29  brouard    Revision 1.109  2006/01/24 19:37:15  brouard
   * imach.c (Repository): Duplicated warning errors corrected.    (Module): Comments (lines starting with a #) are allowed in data.
   (Repository): Elapsed time after each iteration is now output. It  
   helps to forecast when convergence will be reached. Elapsed time    Revision 1.108  2006/01/19 18:05:42  lievre
   is stamped in powell.  We created a new html file for the graphs    Gnuplot problem appeared...
   concerning matrix of covariance. It has extension -cov.htm.    To be fixed
   
   Revision 1.90  2003/06/24 12:34:15  brouard    Revision 1.107  2006/01/19 16:20:37  brouard
   (Module): Some bugs corrected for windows. Also, when    Test existence of gnuplot in imach path
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.106  2006/01/19 13:24:36  brouard
     Some cleaning and links added in html output
   Revision 1.89  2003/06/24 12:30:52  brouard  
   (Module): Some bugs corrected for windows. Also, when    Revision 1.105  2006/01/05 20:23:19  lievre
   mle=-1 a template is output in file "or"mypar.txt with the design    *** empty log message ***
   of the covariance matrix to be input.  
     Revision 1.104  2005/09/30 16:11:43  lievre
   Revision 1.88  2003/06/23 17:54:56  brouard    (Module): sump fixed, loop imx fixed, and simplifications.
   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.    (Module): 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
   Revision 1.87  2003/06/18 12:26:01  brouard    (instead of missing=-1 in earlier versions) and his/her
   Version 0.96    contributions to the likelihood is 1 - Prob of dying from last
     health status (= 1-p13= p11+p12 in the easiest case of somebody in
   Revision 1.86  2003/06/17 20:04:08  brouard    the healthy state at last known wave). Version is 0.98
   (Module): Change position of html and gnuplot routines and added  
   routine fileappend.    Revision 1.103  2005/09/30 15:54:49  lievre
     (Module): sump fixed, loop imx fixed, and simplifications.
   Revision 1.85  2003/06/17 13:12:43  brouard  
   * imach.c (Repository): Check when date of death was earlier that    Revision 1.102  2004/09/15 17:31:30  brouard
   current date of interview. It may happen when the death was just    Add the possibility to read data file including tab characters.
   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.101  2004/09/15 10:38:38  brouard
   assuming that the date of death was just one stepm after the    Fix on curr_time
   interview.  
   (Repository): Because some people have very long ID (first column)    Revision 1.100  2004/07/12 18:29:06  brouard
   we changed int to long in num[] and we added a new lvector for    Add version for Mac OS X. Just define UNIX in Makefile
   memory allocation. But we also truncated to 8 characters (left  
   truncation)    Revision 1.99  2004/06/05 08:57:40  brouard
   (Repository): No more line truncation errors.    *** empty log message ***
   
   Revision 1.84  2003/06/13 21:44:43  brouard    Revision 1.98  2004/05/16 15:05:56  brouard
   * imach.c (Repository): Replace "freqsummary" at a correct    New version 0.97 . First attempt to estimate force of mortality
   place. It differs from routine "prevalence" which may be called    directly from the data i.e. without the need of knowing the health
   many times. Probs is memory consuming and must be used with    state at each age, but using a Gompertz model: log u =a + b*age .
   parcimony.    This is the basic analysis of mortality and should be done before any
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    other analysis, in order to test if the mortality estimated from the
     cross-longitudinal survey is different from the mortality estimated
   Revision 1.83  2003/06/10 13:39:11  lievre    from other sources like vital statistic data.
   *** empty log message ***  
     The same imach parameter file can be used but the option for mle should be -3.
   Revision 1.82  2003/06/05 15:57:20  brouard  
   Add log in  imach.c and  fullversion number is now printed.    Agnès, who wrote this part of the code, tried to keep most of the
     former routines in order to include the new code within the former code.
 */  
 /*    The output is very simple: only an estimate of the intercept and of
    Interpolated Markov Chain    the slope with 95% confident intervals.
   
   Short summary of the programme:    Current limitations:
       A) Even if you enter covariates, i.e. with the
   This program computes Healthy Life Expectancies from    model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    B) There is no computation of Life Expectancy nor Life Table.
   first survey ("cross") where individuals from different ages are  
   interviewed on their health status or degree of disability (in the    Revision 1.97  2004/02/20 13:25:42  lievre
   case of a health survey which is our main interest) -2- at least a    Version 0.96d. Population forecasting command line is (temporarily)
   second wave of interviews ("longitudinal") which measure each change    suppressed.
   (if any) in individual health status.  Health expectancies are  
   computed from the time spent in each health state according to a    Revision 1.96  2003/07/15 15:38:55  brouard
   model. More health states you consider, more time is necessary to reach the    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   Maximum Likelihood of the parameters involved in the model.  The    rewritten within the same printf. Workaround: many printfs.
   simplest model is the multinomial logistic model where pij is the  
   probability to be observed in state j at the second wave    Revision 1.95  2003/07/08 07:54:34  brouard
   conditional to be observed in state i at the first wave. Therefore    * imach.c (Repository):
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    (Repository): Using imachwizard code to output a more meaningful covariance
   'age' is age and 'sex' is a covariate. If you want to have a more    matrix (cov(a12,c31) instead of numbers.
   complex model than "constant and age", you should modify the program  
   where the markup *Covariates have to be included here again* invites    Revision 1.94  2003/06/27 13:00:02  brouard
   you to do it.  More covariates you add, slower the    Just cleaning
   convergence.  
     Revision 1.93  2003/06/25 16:33:55  brouard
   The advantage of this computer programme, compared to a simple    (Module): On windows (cygwin) function asctime_r doesn't
   multinomial logistic model, is clear when the delay between waves is not    exist so I changed back to asctime which exists.
   identical for each individual. Also, if a individual missed an    (Module): Version 0.96b
   intermediate interview, the information is lost, but taken into  
   account using an interpolation or extrapolation.      Revision 1.92  2003/06/25 16:30:45  brouard
     (Module): On windows (cygwin) function asctime_r doesn't
   hPijx is the probability to be observed in state i at age x+h    exist so I changed back to asctime which exists.
   conditional to the observed state i at age x. The delay 'h' can be  
   split into an exact number (nh*stepm) of unobserved intermediate    Revision 1.91  2003/06/25 15:30:29  brouard
   states. This elementary transition (by month, quarter,    * imach.c (Repository): Duplicated warning errors corrected.
   semester or year) is modelled as a multinomial logistic.  The hPx    (Repository): Elapsed time after each iteration is now output. It
   matrix is simply the matrix product of nh*stepm elementary matrices    helps to forecast when convergence will be reached. Elapsed time
   and the contribution of each individual to the likelihood is simply    is stamped in powell.  We created a new html file for the graphs
   hPijx.    concerning matrix of covariance. It has extension -cov.htm.
   
   Also this programme outputs the covariance matrix of the parameters but also    Revision 1.90  2003/06/24 12:34:15  brouard
   of the life expectancies. It also computes the stable prevalence.     (Module): Some bugs corrected for windows. Also, when
       mle=-1 a template is output in file "or"mypar.txt with the design
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    of the covariance matrix to be input.
            Institut national d'études démographiques, Paris.  
   This software have been partly granted by Euro-REVES, a concerted action    Revision 1.89  2003/06/24 12:30:52  brouard
   from the European Union.    (Module): Some bugs corrected for windows. Also, when
   It is copyrighted identically to a GNU software product, ie programme and    mle=-1 a template is output in file "or"mypar.txt with the design
   software can be distributed freely for non commercial use. Latest version    of the covariance matrix to be input.
   can be accessed at http://euroreves.ined.fr/imach .  
     Revision 1.88  2003/06/23 17:54:56  brouard
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    * 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.
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so  
       Revision 1.87  2003/06/18 12:26:01  brouard
   **********************************************************************/    Version 0.96
 /*  
   main    Revision 1.86  2003/06/17 20:04:08  brouard
   read parameterfile    (Module): Change position of html and gnuplot routines and added
   read datafile    routine fileappend.
   concatwav  
   freqsummary    Revision 1.85  2003/06/17 13:12:43  brouard
   if (mle >= 1)    * imach.c (Repository): Check when date of death was earlier that
     mlikeli    current date of interview. It may happen when the death was just
   print results files    prior to the death. In this case, dh was negative and likelihood
   if mle==1     was wrong (infinity). We still send an "Error" but patch by
      computes hessian    assuming that the date of death was just one stepm after the
   read end of parameter file: agemin, agemax, bage, fage, estepm    interview.
       begin-prev-date,...    (Repository): Because some people have very long ID (first column)
   open gnuplot file    we changed int to long in num[] and we added a new lvector for
   open html file    memory allocation. But we also truncated to 8 characters (left
   stable prevalence    truncation)
    for age prevalim()    (Repository): No more line truncation errors.
   h Pij x  
   variance of p varprob    Revision 1.84  2003/06/13 21:44:43  brouard
   forecasting if prevfcast==1 prevforecast call prevalence()    * imach.c (Repository): Replace "freqsummary" at a correct
   health expectancies    place. It differs from routine "prevalence" which may be called
   Variance-covariance of DFLE    many times. Probs is memory consuming and must be used with
   prevalence()    parcimony.
    movingaverage()    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
   varevsij()   
   if popbased==1 varevsij(,popbased)    Revision 1.83  2003/06/10 13:39:11  lievre
   total life expectancies    *** empty log message ***
   Variance of stable prevalence  
  end    Revision 1.82  2003/06/05 15:57:20  brouard
 */    Add log in  imach.c and  fullversion number is now printed.
   
   */
   /*
       Interpolated Markov Chain
 #include <math.h>  
 #include <stdio.h>    Short summary of the programme:
 #include <stdlib.h>   
 #include <string.h>    This program computes Healthy Life Expectancies from
 #include <unistd.h>    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
     first survey ("cross") where individuals from different ages are
 #include <sys/types.h>    interviewed on their health status or degree of disability (in the
 #include <sys/stat.h>    case of a health survey which is our main interest) -2- at least a
 #include <errno.h>    second wave of interviews ("longitudinal") which measure each change
 extern int errno;    (if any) in individual health status.  Health expectancies are
     computed from the time spent in each health state according to a
 /* #include <sys/time.h> */    model. More health states you consider, more time is necessary to reach the
 #include <time.h>    Maximum Likelihood of the parameters involved in the model.  The
 #include "timeval.h"    simplest model is the multinomial logistic model where pij is the
     probability to be observed in state j at the second wave
 /* #include <libintl.h> */    conditional to be observed in state i at the first wave. Therefore
 /* #define _(String) gettext (String) */    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
     'age' is age and 'sex' is a covariate. If you want to have a more
 #define MAXLINE 256    complex model than "constant and age", you should modify the program
     where the markup *Covariates have to be included here again* invites
 #define GNUPLOTPROGRAM "gnuplot"    you to do it.  More covariates you add, slower the
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/    convergence.
 #define FILENAMELENGTH 132  
     The advantage of this computer programme, compared to a simple
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */    multinomial logistic model, is clear when the delay between waves is not
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */    identical for each individual. Also, if a individual missed an
     intermediate interview, the information is lost, but taken into
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */    account using an interpolation or extrapolation.  
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  
     hPijx is the probability to be observed in state i at age x+h
 #define NINTERVMAX 8    conditional to the observed state i at age x. The delay 'h' can be
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */    split into an exact number (nh*stepm) of unobserved intermediate
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */    states. This elementary transition (by month, quarter,
 #define NCOVMAX 8 /* Maximum number of covariates */    semester or year) is modelled as a multinomial logistic.  The hPx
 #define MAXN 20000    matrix is simply the matrix product of nh*stepm elementary matrices
 #define YEARM 12. /* Number of months per year */    and the contribution of each individual to the likelihood is simply
 #define AGESUP 130    hPijx.
 #define AGEBASE 40  
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */    Also this programme outputs the covariance matrix of the parameters but also
 #ifdef UNIX    of the life expectancies. It also computes the period (stable) prevalence.
 #define DIRSEPARATOR '/'   
 #define CHARSEPARATOR "/"    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 #define ODIRSEPARATOR '\\'             Institut national d'études démographiques, Paris.
 #else    This software have been partly granted by Euro-REVES, a concerted action
 #define DIRSEPARATOR '\\'    from the European Union.
 #define CHARSEPARATOR "\\"    It is copyrighted identically to a GNU software product, ie programme and
 #define ODIRSEPARATOR '/'    software can be distributed freely for non commercial use. Latest version
 #endif    can be accessed at http://euroreves.ined.fr/imach .
   
 /* $Id$ */    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 /* $State$ */    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
    
 char version[]="Imach version 0.98a, January 2006, INED-EUROREVES ";    **********************************************************************/
 char fullversion[]="$Revision$ $Date$";   /*
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */    main
 int nvar;    read parameterfile
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;    read datafile
 int npar=NPARMAX;    concatwav
 int nlstate=2; /* Number of live states */    freqsummary
 int ndeath=1; /* Number of dead states */    if (mle >= 1)
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */      mlikeli
 int popbased=0;    print results files
     if mle==1
 int *wav; /* Number of waves for this individuual 0 is possible */       computes hessian
 int maxwav; /* Maxim number of waves */    read end of parameter file: agemin, agemax, bage, fage, estepm
 int jmin, jmax; /* min, max spacing between 2 waves */        begin-prev-date,...
 int gipmx, gsw; /* Global variables on the number of contributions     open gnuplot file
                    to the likelihood and the sum of weights (done by funcone)*/    open html file
 int mle, weightopt;    period (stable) prevalence
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */     for age prevalim()
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */    h Pij x
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between    variance of p varprob
            * wave mi and wave mi+1 is not an exact multiple of stepm. */    forecasting if prevfcast==1 prevforecast call prevalence()
 double jmean; /* Mean space between 2 waves */    health expectancies
 double **oldm, **newm, **savm; /* Working pointers to matrices */    Variance-covariance of DFLE
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */    prevalence()
 FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;     movingaverage()
 FILE *ficlog, *ficrespow;    varevsij()
 int globpr; /* Global variable for printing or not */    if popbased==1 varevsij(,popbased)
 double fretone; /* Only one call to likelihood */    total life expectancies
 long ipmx; /* Number of contributions */    Variance of period (stable) prevalence
 double sw; /* Sum of weights */   end
 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 */  #include <math.h>
 FILE *ficreseij;  #include <stdio.h>
 char filerese[FILENAMELENGTH];  #include <stdlib.h>
 FILE  *ficresvij;  #include <string.h>
 char fileresv[FILENAMELENGTH];  #include <unistd.h>
 FILE  *ficresvpl;  
 char fileresvpl[FILENAMELENGTH];  #include <limits.h>
 char title[MAXLINE];  #include <sys/types.h>
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];  #include <sys/stat.h>
 char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH];  #include <errno.h>
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];   extern int errno;
 char command[FILENAMELENGTH];  
 int  outcmd=0;  /* #include <sys/time.h> */
   #include <time.h>
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  #include "timeval.h"
   
 char filelog[FILENAMELENGTH]; /* Log file */  /* #include <libintl.h> */
 char filerest[FILENAMELENGTH];  /* #define _(String) gettext (String) */
 char fileregp[FILENAMELENGTH];  
 char popfile[FILENAMELENGTH];  #define MAXLINE 256
   
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  #define GNUPLOTPROGRAM "gnuplot"
   /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  #define FILENAMELENGTH 132
 struct timezone tzp;  
 extern int gettimeofday();  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 long time_value;  
 extern long time();  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 char strcurr[80], strfor[80];  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
   
 #define NR_END 1  #define NINTERVMAX 8
 #define FREE_ARG char*  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 #define FTOL 1.0e-10  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
   #define NCOVMAX 8 /* Maximum number of covariates */
 #define NRANSI   #define MAXN 20000
 #define ITMAX 200   #define YEARM 12. /* Number of months per year */
   #define AGESUP 130
 #define TOL 2.0e-4   #define AGEBASE 40
   #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 #define CGOLD 0.3819660   #ifdef UNIX
 #define ZEPS 1.0e-10   #define DIRSEPARATOR '/'
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   #define CHARSEPARATOR "/"
   #define ODIRSEPARATOR '\\'
 #define GOLD 1.618034   #else
 #define GLIMIT 100.0   #define DIRSEPARATOR '\\'
 #define TINY 1.0e-20   #define CHARSEPARATOR "\\"
   #define ODIRSEPARATOR '/'
 static double maxarg1,maxarg2;  #endif
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  /* $Id$ */
     /* $State$ */
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  
 #define rint(a) floor(a+0.5)  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
   char fullversion[]="$Revision$ $Date$";
 static double sqrarg;  char strstart[80];
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 int agegomp= AGEGOMP;  int nvar;
   int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 int imx;   int npar=NPARMAX;
 int stepm=1;  int nlstate=2; /* Number of live states */
 /* Stepm, step in month: minimum step interpolation*/  int ndeath=1; /* Number of dead states */
   int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 int estepm;  int popbased=0;
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  
   int *wav; /* Number of waves for this individuual 0 is possible */
 int m,nb;  int maxwav; /* Maxim number of waves */
 long *num;  int jmin, jmax; /* min, max spacing between 2 waves */
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  int ijmin, ijmax; /* Individuals having jmin and jmax */
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  int gipmx, gsw; /* Global variables on the number of contributions
 double **pmmij, ***probs;                     to the likelihood and the sum of weights (done by funcone)*/
 double *ageexmed,*agecens;  int mle, weightopt;
 double dateintmean=0;  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
   int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 double *weight;  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
 int **s; /* Status */             * wave mi and wave mi+1 is not an exact multiple of stepm. */
 double *agedc, **covar, idx;  double jmean; /* Mean space between 2 waves */
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  double **oldm, **newm, **savm; /* Working pointers to matrices */
 double *lsurv, *lpop, *tpop;  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
   FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  FILE *ficlog, *ficrespow;
 double ftolhess; /* Tolerance for computing hessian */  int globpr; /* Global variable for printing or not */
   double fretone; /* Only one call to likelihood */
 /**************** split *************************/  long ipmx; /* Number of contributions */
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  double sw; /* Sum of weights */
 {  char filerespow[FILENAMELENGTH];
   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
      the name of the file (name), its extension only (ext) and its first part of the name (finame)  FILE *ficresilk;
   */   FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
   char  *ss;                            /* pointer */  FILE *ficresprobmorprev;
   int   l1, l2;                         /* length counters */  FILE *fichtm, *fichtmcov; /* Html File */
   FILE *ficreseij;
   l1 = strlen(path );                   /* length of path */  char filerese[FILENAMELENGTH];
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  FILE *ficresstdeij;
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  char fileresstde[FILENAMELENGTH];
   if ( ss == NULL ) {                   /* no directory, so determine current directory */  FILE *ficrescveij;
     strcpy( name, path );               /* we got the fullname name because no directory */  char filerescve[FILENAMELENGTH];
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  FILE  *ficresvij;
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  char fileresv[FILENAMELENGTH];
     /* get current working directory */  FILE  *ficresvpl;
     /*    extern  char* getcwd ( char *buf , int len);*/  char fileresvpl[FILENAMELENGTH];
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  char title[MAXLINE];
       return( GLOCK_ERROR_GETCWD );  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
     }  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
     /* got dirc from getcwd*/  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
     printf(" DIRC = %s \n",dirc);  char command[FILENAMELENGTH];
   } else {                              /* strip direcotry from path */  int  outcmd=0;
     ss++;                               /* after this, the filename */  
     l2 = strlen( ss );                  /* length of filename */  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  
     strcpy( name, ss );         /* save file name */  char filelog[FILENAMELENGTH]; /* Log file */
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  char filerest[FILENAMELENGTH];
     dirc[l1-l2] = 0;                    /* add zero */  char fileregp[FILENAMELENGTH];
     printf(" DIRC2 = %s \n",dirc);  char popfile[FILENAMELENGTH];
   }  
   /* We add a separator at the end of dirc if not exists */  char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
   l1 = strlen( dirc );                  /* length of directory */  
   if( dirc[l1-1] != DIRSEPARATOR ){  struct timeval start_time, end_time, curr_time, last_time, forecast_time;
     dirc[l1] =  DIRSEPARATOR;  struct timezone tzp;
     dirc[l1+1] = 0;   extern int gettimeofday();
     printf(" DIRC3 = %s \n",dirc);  struct tm tmg, tm, tmf, *gmtime(), *localtime();
   }  long time_value;
   ss = strrchr( name, '.' );            /* find last / */  extern long time();
   if (ss >0){  char strcurr[80], strfor[80];
     ss++;  
     strcpy(ext,ss);                     /* save extension */  char *endptr;
     l1= strlen( name);  long lval;
     l2= strlen(ss)+1;  double dval;
     strncpy( finame, name, l1-l2);  
     finame[l1-l2]= 0;  #define NR_END 1
   }  #define FREE_ARG char*
   #define FTOL 1.0e-10
   return( 0 );                          /* we're done */  
 }  #define NRANSI
   #define ITMAX 200
   
 /******************************************/  #define TOL 2.0e-4
   
 void replace_back_to_slash(char *s, char*t)  #define CGOLD 0.3819660
 {  #define ZEPS 1.0e-10
   int i;  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
   int lg=0;  
   i=0;  #define GOLD 1.618034
   lg=strlen(t);  #define GLIMIT 100.0
   for(i=0; i<= lg; i++) {  #define TINY 1.0e-20
     (s[i] = t[i]);  
     if (t[i]== '\\') s[i]='/';  static double maxarg1,maxarg2;
   }  #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 }  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
    
 int nbocc(char *s, char occ)  #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 {  #define rint(a) floor(a+0.5)
   int i,j=0;  
   int lg=20;  static double sqrarg;
   i=0;  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
   lg=strlen(s);  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
   for(i=0; i<= lg; i++) {  int agegomp= AGEGOMP;
   if  (s[i] == occ ) j++;  
   }  int imx;
   return j;  int stepm=1;
 }  /* Stepm, step in month: minimum step interpolation*/
   
 void cutv(char *u,char *v, char*t, char occ)  int estepm;
 {  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   /* cuts string t into u and v where u ends before first occurence of char 'occ'   
      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')  int m,nb;
      gives u="abcedf" and v="ghi2j" */  long *num;
   int i,lg,j,p=0;  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
   i=0;  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
   for(j=0; j<=strlen(t)-1; j++) {  double **pmmij, ***probs;
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;  double *ageexmed,*agecens;
   }  double dateintmean=0;
   
   lg=strlen(t);  double *weight;
   for(j=0; j<p; j++) {  int **s; /* Status */
     (u[j] = t[j]);  double *agedc, **covar, idx;
   }  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
      u[p]='\0';  double *lsurv, *lpop, *tpop;
   
    for(j=0; j<= lg; j++) {  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
     if (j>=(p+1))(v[j-p-1] = t[j]);  double ftolhess; /* Tolerance for computing hessian */
   }  
 }  /**************** split *************************/
   static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
 /********************** nrerror ********************/  {
     /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 void nrerror(char error_text[])       the name of the file (name), its extension only (ext) and its first part of the name (finame)
 {    */
   fprintf(stderr,"ERREUR ...\n");    char  *ss;                            /* pointer */
   fprintf(stderr,"%s\n",error_text);    int   l1, l2;                         /* length counters */
   exit(EXIT_FAILURE);  
 }    l1 = strlen(path );                   /* length of path */
 /*********************** vector *******************/    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 double *vector(int nl, int nh)    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
 {    if ( ss == NULL ) {                   /* no directory, so determine current directory */
   double *v;      strcpy( name, path );               /* we got the fullname name because no directory */
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
   if (!v) nrerror("allocation failure in vector");        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
   return v-nl+NR_END;      /* get current working directory */
 }      /*    extern  char* getcwd ( char *buf , int len);*/
       if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
 /************************ free vector ******************/        return( GLOCK_ERROR_GETCWD );
 void free_vector(double*v, int nl, int nh)      }
 {      /* got dirc from getcwd*/
   free((FREE_ARG)(v+nl-NR_END));      printf(" DIRC = %s \n",dirc);
 }    } else {                              /* strip direcotry from path */
       ss++;                               /* after this, the filename */
 /************************ivector *******************************/      l2 = strlen( ss );                  /* length of filename */
 int *ivector(long nl,long nh)      if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 {      strcpy( name, ss );         /* save file name */
   int *v;      strncpy( dirc, path, l1 - l2 );     /* now the directory */
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));      dirc[l1-l2] = 0;                    /* add zero */
   if (!v) nrerror("allocation failure in ivector");      printf(" DIRC2 = %s \n",dirc);
   return v-nl+NR_END;    }
 }    /* We add a separator at the end of dirc if not exists */
     l1 = strlen( dirc );                  /* length of directory */
 /******************free ivector **************************/    if( dirc[l1-1] != DIRSEPARATOR ){
 void free_ivector(int *v, long nl, long nh)      dirc[l1] =  DIRSEPARATOR;
 {      dirc[l1+1] = 0;
   free((FREE_ARG)(v+nl-NR_END));      printf(" DIRC3 = %s \n",dirc);
 }    }
     ss = strrchr( name, '.' );            /* find last / */
 /************************lvector *******************************/    if (ss >0){
 long *lvector(long nl,long nh)      ss++;
 {      strcpy(ext,ss);                     /* save extension */
   long *v;      l1= strlen( name);
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));      l2= strlen(ss)+1;
   if (!v) nrerror("allocation failure in ivector");      strncpy( finame, name, l1-l2);
   return v-nl+NR_END;      finame[l1-l2]= 0;
 }    }
   
 /******************free lvector **************************/    return( 0 );                          /* we're done */
 void free_lvector(long *v, long nl, long nh)  }
 {  
   free((FREE_ARG)(v+nl-NR_END));  
 }  /******************************************/
   
 /******************* imatrix *******************************/  void replace_back_to_slash(char *s, char*t)
 int **imatrix(long nrl, long nrh, long ncl, long nch)   {
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */     int i;
 {     int lg=0;
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;     i=0;
   int **m;     lg=strlen(t);
       for(i=0; i<= lg; i++) {
   /* allocate pointers to rows */       (s[i] = t[i]);
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));       if (t[i]== '\\') s[i]='/';
   if (!m) nrerror("allocation failure 1 in matrix()");     }
   m += NR_END;   }
   m -= nrl;   
     int nbocc(char *s, char occ)
     {
   /* allocate rows and set pointers to them */     int i,j=0;
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));     int lg=20;
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");     i=0;
   m[nrl] += NR_END;     lg=strlen(s);
   m[nrl] -= ncl;     for(i=0; i<= lg; i++) {
       if  (s[i] == occ ) j++;
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;     }
       return j;
   /* return pointer to array of pointers to rows */   }
   return m;   
 }   void cutv(char *u,char *v, char*t, char occ)
   {
 /****************** free_imatrix *************************/    /* cuts string t into u and v where u ends before first occurence of char 'occ'
 void free_imatrix(m,nrl,nrh,ncl,nch)       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
       int **m;       gives u="abcedf" and v="ghi2j" */
       long nch,ncl,nrh,nrl;     int i,lg,j,p=0;
      /* free an int matrix allocated by imatrix() */     i=0;
 {     for(j=0; j<=strlen(t)-1; j++) {
   free((FREE_ARG) (m[nrl]+ncl-NR_END));       if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
   free((FREE_ARG) (m+nrl-NR_END));     }
 }   
     lg=strlen(t);
 /******************* matrix *******************************/    for(j=0; j<p; j++) {
 double **matrix(long nrl, long nrh, long ncl, long nch)      (u[j] = t[j]);
 {    }
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;       u[p]='\0';
   double **m;  
      for(j=0; j<= lg; j++) {
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));      if (j>=(p+1))(v[j-p-1] = t[j]);
   if (!m) nrerror("allocation failure 1 in matrix()");    }
   m += NR_END;  }
   m -= nrl;  
   /********************** nrerror ********************/
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  void nrerror(char error_text[])
   m[nrl] += NR_END;  {
   m[nrl] -= ncl;    fprintf(stderr,"ERREUR ...\n");
     fprintf(stderr,"%s\n",error_text);
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    exit(EXIT_FAILURE);
   return m;  }
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])   /*********************** vector *******************/
    */  double *vector(int nl, int nh)
 }  {
     double *v;
 /*************************free matrix ************************/    v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)    if (!v) nrerror("allocation failure in vector");
 {    return v-nl+NR_END;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));  }
   free((FREE_ARG)(m+nrl-NR_END));  
 }  /************************ free vector ******************/
   void free_vector(double*v, int nl, int nh)
 /******************* ma3x *******************************/  {
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)    free((FREE_ARG)(v+nl-NR_END));
 {  }
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;  
   double ***m;  /************************ivector *******************************/
   int *ivector(long nl,long nh)
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  {
   if (!m) nrerror("allocation failure 1 in matrix()");    int *v;
   m += NR_END;    v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
   m -= nrl;    if (!v) nrerror("allocation failure in ivector");
     return v-nl+NR_END;
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  }
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  
   m[nrl] += NR_END;  /******************free ivector **************************/
   m[nrl] -= ncl;  void free_ivector(int *v, long nl, long nh)
   {
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    free((FREE_ARG)(v+nl-NR_END));
   }
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));  
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");  /************************lvector *******************************/
   m[nrl][ncl] += NR_END;  long *lvector(long nl,long nh)
   m[nrl][ncl] -= nll;  {
   for (j=ncl+1; j<=nch; j++)     long *v;
     m[nrl][j]=m[nrl][j-1]+nlay;    v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
       if (!v) nrerror("allocation failure in ivector");
   for (i=nrl+1; i<=nrh; i++) {    return v-nl+NR_END;
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;  }
     for (j=ncl+1; j<=nch; j++)   
       m[i][j]=m[i][j-1]+nlay;  /******************free lvector **************************/
   }  void free_lvector(long *v, long nl, long nh)
   return m;   {
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])    free((FREE_ARG)(v+nl-NR_END));
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)  }
   */  
 }  /******************* imatrix *******************************/
   int **imatrix(long nrl, long nrh, long ncl, long nch)
 /*************************free ma3x ************************/       /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)  {
 {    long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    int **m;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));   
   free((FREE_ARG)(m+nrl-NR_END));    /* allocate pointers to rows */
 }    m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
     if (!m) nrerror("allocation failure 1 in matrix()");
 /*************** function subdirf ***********/    m += NR_END;
 char *subdirf(char fileres[])    m -= nrl;
 {   
   /* Caution optionfilefiname is hidden */   
   strcpy(tmpout,optionfilefiname);    /* allocate rows and set pointers to them */
   strcat(tmpout,"/"); /* Add to the right */    m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
   strcat(tmpout,fileres);    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   return tmpout;    m[nrl] += NR_END;
 }    m[nrl] -= ncl;
    
 /*************** function subdirf2 ***********/    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
 char *subdirf2(char fileres[], char *preop)   
 {    /* return pointer to array of pointers to rows */
       return m;
   /* Caution optionfilefiname is hidden */  }
   strcpy(tmpout,optionfilefiname);  
   strcat(tmpout,"/");  /****************** free_imatrix *************************/
   strcat(tmpout,preop);  void free_imatrix(m,nrl,nrh,ncl,nch)
   strcat(tmpout,fileres);        int **m;
   return tmpout;        long nch,ncl,nrh,nrl;
 }       /* free an int matrix allocated by imatrix() */
   {
 /*************** function subdirf3 ***********/    free((FREE_ARG) (m[nrl]+ncl-NR_END));
 char *subdirf3(char fileres[], char *preop, char *preop2)    free((FREE_ARG) (m+nrl-NR_END));
 {  }
     
   /* Caution optionfilefiname is hidden */  /******************* matrix *******************************/
   strcpy(tmpout,optionfilefiname);  double **matrix(long nrl, long nrh, long ncl, long nch)
   strcat(tmpout,"/");  {
   strcat(tmpout,preop);    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
   strcat(tmpout,preop2);    double **m;
   strcat(tmpout,fileres);  
   return tmpout;    m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 }    if (!m) nrerror("allocation failure 1 in matrix()");
     m += NR_END;
 /***************** f1dim *************************/    m -= nrl;
 extern int ncom;   
 extern double *pcom,*xicom;    m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 extern double (*nrfunc)(double []);     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
      m[nrl] += NR_END;
 double f1dim(double x)     m[nrl] -= ncl;
 {   
   int j;     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   double f;    return m;
   double *xt;     /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
       */
   xt=vector(1,ncom);   }
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];   
   f=(*nrfunc)(xt);   /*************************free matrix ************************/
   free_vector(xt,1,ncom);   void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   return f;   {
 }     free((FREE_ARG)(m[nrl]+ncl-NR_END));
     free((FREE_ARG)(m+nrl-NR_END));
 /*****************brent *************************/  }
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)   
 {   /******************* ma3x *******************************/
   int iter;   double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
   double a,b,d,etemp;  {
   double fu,fv,fw,fx;    long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
   double ftemp;    double ***m;
   double p,q,r,tol1,tol2,u,v,w,x,xm;   
   double e=0.0;     m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
      if (!m) nrerror("allocation failure 1 in matrix()");
   a=(ax < cx ? ax : cx);     m += NR_END;
   b=(ax > cx ? ax : cx);     m -= nrl;
   x=w=v=bx;   
   fw=fv=fx=(*f)(x);     m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   for (iter=1;iter<=ITMAX;iter++) {     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     xm=0.5*(a+b);     m[nrl] += NR_END;
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     m[nrl] -= ncl;
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/  
     printf(".");fflush(stdout);    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
     fprintf(ficlog,".");fflush(ficlog);  
 #ifdef DEBUG    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
     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);    if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
     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);    m[nrl][ncl] += NR_END;
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */    m[nrl][ncl] -= nll;
 #endif    for (j=ncl+1; j<=nch; j++)
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){       m[nrl][j]=m[nrl][j-1]+nlay;
       *xmin=x;    
       return fx;     for (i=nrl+1; i<=nrh; i++) {
     }       m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
     ftemp=fu;      for (j=ncl+1; j<=nch; j++)
     if (fabs(e) > tol1) {         m[i][j]=m[i][j-1]+nlay;
       r=(x-w)*(fx-fv);     }
       q=(x-v)*(fx-fw);     return m;
       p=(x-v)*q-(x-w)*r;     /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
       q=2.0*(q-r);              &(m[i][j][k]) <=> *((*(m+i) + j)+k)
       if (q > 0.0) p = -p;     */
       q=fabs(q);   }
       etemp=e;   
       e=d;   /*************************free ma3x ************************/
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))   void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
         d=CGOLD*(e=(x >= xm ? a-x : b-x));   {
       else {     free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
         d=p/q;     free((FREE_ARG)(m[nrl]+ncl-NR_END));
         u=x+d;     free((FREE_ARG)(m+nrl-NR_END));
         if (u-a < tol2 || b-u < tol2)   }
           d=SIGN(tol1,xm-x);   
       }   /*************** function subdirf ***********/
     } else {   char *subdirf(char fileres[])
       d=CGOLD*(e=(x >= xm ? a-x : b-x));   {
     }     /* Caution optionfilefiname is hidden */
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));     strcpy(tmpout,optionfilefiname);
     fu=(*f)(u);     strcat(tmpout,"/"); /* Add to the right */
     if (fu <= fx) {     strcat(tmpout,fileres);
       if (u >= x) a=x; else b=x;     return tmpout;
       SHFT(v,w,x,u)   }
         SHFT(fv,fw,fx,fu)   
         } else {   /*************** function subdirf2 ***********/
           if (u < x) a=u; else b=u;   char *subdirf2(char fileres[], char *preop)
           if (fu <= fw || w == x) {   {
             v=w;    
             w=u;     /* Caution optionfilefiname is hidden */
             fv=fw;     strcpy(tmpout,optionfilefiname);
             fw=fu;     strcat(tmpout,"/");
           } else if (fu <= fv || v == x || v == w) {     strcat(tmpout,preop);
             v=u;     strcat(tmpout,fileres);
             fv=fu;     return tmpout;
           }   }
         }   
   }   /*************** function subdirf3 ***********/
   nrerror("Too many iterations in brent");   char *subdirf3(char fileres[], char *preop, char *preop2)
   *xmin=x;   {
   return fx;    
 }     /* Caution optionfilefiname is hidden */
     strcpy(tmpout,optionfilefiname);
 /****************** mnbrak ***********************/    strcat(tmpout,"/");
     strcat(tmpout,preop);
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,     strcat(tmpout,preop2);
             double (*func)(double))     strcat(tmpout,fileres);
 {     return tmpout;
   double ulim,u,r,q, dum;  }
   double fu;   
    /***************** f1dim *************************/
   *fa=(*func)(*ax);   extern int ncom;
   *fb=(*func)(*bx);   extern double *pcom,*xicom;
   if (*fb > *fa) {   extern double (*nrfunc)(double []);
     SHFT(dum,*ax,*bx,dum)    
       SHFT(dum,*fb,*fa,dum)   double f1dim(double x)
       }   {
   *cx=(*bx)+GOLD*(*bx-*ax);     int j;
   *fc=(*func)(*cx);     double f;
   while (*fb > *fc) {     double *xt;
     r=(*bx-*ax)*(*fb-*fc);    
     q=(*bx-*cx)*(*fb-*fa);     xt=vector(1,ncom);
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));     f=(*nrfunc)(xt);
     ulim=(*bx)+GLIMIT*(*cx-*bx);     free_vector(xt,1,ncom);
     if ((*bx-u)*(u-*cx) > 0.0) {     return f;
       fu=(*func)(u);   }
     } else if ((*cx-u)*(u-ulim) > 0.0) {   
       fu=(*func)(u);   /*****************brent *************************/
       if (fu < *fc) {   double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))   {
           SHFT(*fb,*fc,fu,(*func)(u))     int iter;
           }     double a,b,d,etemp;
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {     double fu,fv,fw,fx;
       u=ulim;     double ftemp;
       fu=(*func)(u);     double p,q,r,tol1,tol2,u,v,w,x,xm;
     } else {     double e=0.0;
       u=(*cx)+GOLD*(*cx-*bx);    
       fu=(*func)(u);     a=(ax < cx ? ax : cx);
     }     b=(ax > cx ? ax : cx);
     SHFT(*ax,*bx,*cx,u)     x=w=v=bx;
       SHFT(*fa,*fb,*fc,fu)     fw=fv=fx=(*f)(x);
       }     for (iter=1;iter<=ITMAX;iter++) {
 }       xm=0.5*(a+b);
       tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
 /*************** linmin ************************/      /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
       printf(".");fflush(stdout);
 int ncom;       fprintf(ficlog,".");fflush(ficlog);
 double *pcom,*xicom;  #ifdef DEBUG
 double (*nrfunc)(double []);       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);
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 {   #endif
   double brent(double ax, double bx, double cx,       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
                double (*f)(double), double tol, double *xmin);         *xmin=x;
   double f1dim(double x);         return fx;
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,       }
               double *fc, double (*func)(double));       ftemp=fu;
   int j;       if (fabs(e) > tol1) {
   double xx,xmin,bx,ax;         r=(x-w)*(fx-fv);
   double fx,fb,fa;        q=(x-v)*(fx-fw);
          p=(x-v)*q-(x-w)*r;
   ncom=n;         q=2.0*(q-r);
   pcom=vector(1,n);         if (q > 0.0) p = -p;
   xicom=vector(1,n);         q=fabs(q);
   nrfunc=func;         etemp=e;
   for (j=1;j<=n;j++) {         e=d;
     pcom[j]=p[j];         if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
     xicom[j]=xi[j];           d=CGOLD*(e=(x >= xm ? a-x : b-x));
   }         else {
   ax=0.0;           d=p/q;
   xx=1.0;           u=x+d;
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);           if (u-a < tol2 || b-u < tol2)
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);             d=SIGN(tol1,xm-x);
 #ifdef DEBUG        }
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);      } else {
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);        d=CGOLD*(e=(x >= xm ? a-x : b-x));
 #endif      }
   for (j=1;j<=n;j++) {       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
     xi[j] *= xmin;       fu=(*f)(u);
     p[j] += xi[j];       if (fu <= fx) {
   }         if (u >= x) a=x; else b=x;
   free_vector(xicom,1,n);         SHFT(v,w,x,u)
   free_vector(pcom,1,n);           SHFT(fv,fw,fx,fu)
 }           } else {
             if (u < x) a=u; else b=u;
 char *asc_diff_time(long time_sec, char ascdiff[])            if (fu <= fw || w == x) {
 {              v=w;
   long sec_left, days, hours, minutes;              w=u;
   days = (time_sec) / (60*60*24);              fv=fw;
   sec_left = (time_sec) % (60*60*24);              fw=fu;
   hours = (sec_left) / (60*60) ;            } else if (fu <= fv || v == x || v == w) {
   sec_left = (sec_left) %(60*60);              v=u;
   minutes = (sec_left) /60;              fv=fu;
   sec_left = (sec_left) % (60);            }
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);            }
   return ascdiff;    }
 }    nrerror("Too many iterations in brent");
     *xmin=x;
 /*************** powell ************************/    return fx;
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,   }
             double (*func)(double []))   
 {   /****************** mnbrak ***********************/
   void linmin(double p[], double xi[], int n, double *fret,   
               double (*func)(double []));   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
   int i,ibig,j;               double (*func)(double))
   double del,t,*pt,*ptt,*xit;  {
   double fp,fptt;    double ulim,u,r,q, dum;
   double *xits;    double fu;
   int niterf, itmp;   
     *fa=(*func)(*ax);
   pt=vector(1,n);     *fb=(*func)(*bx);
   ptt=vector(1,n);     if (*fb > *fa) {
   xit=vector(1,n);       SHFT(dum,*ax,*bx,dum)
   xits=vector(1,n);         SHFT(dum,*fb,*fa,dum)
   *fret=(*func)(p);         }
   for (j=1;j<=n;j++) pt[j]=p[j];     *cx=(*bx)+GOLD*(*bx-*ax);
   for (*iter=1;;++(*iter)) {     *fc=(*func)(*cx);
     fp=(*fret);     while (*fb > *fc) {
     ibig=0;       r=(*bx-*ax)*(*fb-*fc);
     del=0.0;       q=(*bx-*cx)*(*fb-*fa);
     last_time=curr_time;      u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
     (void) gettimeofday(&curr_time,&tzp);        (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
     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);      ulim=(*bx)+GLIMIT*(*cx-*bx);
     /*    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);      if ((*bx-u)*(u-*cx) > 0.0) {
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);        fu=(*func)(u);
     */      } else if ((*cx-u)*(u-ulim) > 0.0) {
    for (i=1;i<=n;i++) {        fu=(*func)(u);
       printf(" %d %.12f",i, p[i]);        if (fu < *fc) {
       fprintf(ficlog," %d %.12lf",i, p[i]);          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
       fprintf(ficrespow," %.12lf", p[i]);            SHFT(*fb,*fc,fu,(*func)(u))
     }            }
     printf("\n");      } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
     fprintf(ficlog,"\n");        u=ulim;
     fprintf(ficrespow,"\n");fflush(ficrespow);        fu=(*func)(u);
     if(*iter <=3){      } else {
       tm = *localtime(&curr_time.tv_sec);        u=(*cx)+GOLD*(*cx-*bx);
       strcpy(strcurr,asctime(&tm));        fu=(*func)(u);
 /*       asctime_r(&tm,strcurr); */      }
       forecast_time=curr_time;       SHFT(*ax,*bx,*cx,u)
       itmp = strlen(strcurr);        SHFT(*fa,*fb,*fc,fu)
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */        }
         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);  /*************** linmin ************************/
       for(niterf=10;niterf<=30;niterf+=10){  
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);  int ncom;
         tmf = *localtime(&forecast_time.tv_sec);  double *pcom,*xicom;
 /*      asctime_r(&tmf,strfor); */  double (*nrfunc)(double []);
         strcpy(strfor,asctime(&tmf));   
         itmp = strlen(strfor);  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
         if(strfor[itmp-1]=='\n')  {
         strfor[itmp-1]='\0';    double brent(double ax, double bx, double cx,
         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);                 double (*f)(double), double tol, double *xmin);
         fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);    double f1dim(double x);
       }    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
     }                double *fc, double (*func)(double));
     for (i=1;i<=n;i++) {     int j;
       for (j=1;j<=n;j++) xit[j]=xi[j][i];     double xx,xmin,bx,ax;
       fptt=(*fret);     double fx,fb,fa;
 #ifdef DEBUG   
       printf("fret=%lf \n",*fret);    ncom=n;
       fprintf(ficlog,"fret=%lf \n",*fret);    pcom=vector(1,n);
 #endif    xicom=vector(1,n);
       printf("%d",i);fflush(stdout);    nrfunc=func;
       fprintf(ficlog,"%d",i);fflush(ficlog);    for (j=1;j<=n;j++) {
       linmin(p,xit,n,fret,func);       pcom[j]=p[j];
       if (fabs(fptt-(*fret)) > del) {       xicom[j]=xi[j];
         del=fabs(fptt-(*fret));     }
         ibig=i;     ax=0.0;
       }     xx=1.0;
 #ifdef DEBUG    mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
       printf("%d %.12e",i,(*fret));    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
       fprintf(ficlog,"%d %.12e",i,(*fret));  #ifdef DEBUG
       for (j=1;j<=n;j++) {    printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);    fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
         printf(" x(%d)=%.12e",j,xit[j]);  #endif
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);    for (j=1;j<=n;j++) {
       }      xi[j] *= xmin;
       for(j=1;j<=n;j++) {      p[j] += xi[j];
         printf(" p=%.12e",p[j]);    }
         fprintf(ficlog," p=%.12e",p[j]);    free_vector(xicom,1,n);
       }    free_vector(pcom,1,n);
       printf("\n");  }
       fprintf(ficlog,"\n");  
 #endif  char *asc_diff_time(long time_sec, char ascdiff[])
     }   {
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {    long sec_left, days, hours, minutes;
 #ifdef DEBUG    days = (time_sec) / (60*60*24);
       int k[2],l;    sec_left = (time_sec) % (60*60*24);
       k[0]=1;    hours = (sec_left) / (60*60) ;
       k[1]=-1;    sec_left = (sec_left) %(60*60);
       printf("Max: %.12e",(*func)(p));    minutes = (sec_left) /60;
       fprintf(ficlog,"Max: %.12e",(*func)(p));    sec_left = (sec_left) % (60);
       for (j=1;j<=n;j++) {    sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
         printf(" %.12e",p[j]);    return ascdiff;
         fprintf(ficlog," %.12e",p[j]);  }
       }  
       printf("\n");  /*************** powell ************************/
       fprintf(ficlog,"\n");  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
       for(l=0;l<=1;l++) {              double (*func)(double []))
         for (j=1;j<=n;j++) {  {
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];    void linmin(double p[], double xi[], int n, double *fret,
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);                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 i,ibig,j;
         }    double del,t,*pt,*ptt,*xit;
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));    double fp,fptt;
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));    double *xits;
       }    int niterf, itmp;
 #endif  
     pt=vector(1,n);
     ptt=vector(1,n);
       free_vector(xit,1,n);     xit=vector(1,n);
       free_vector(xits,1,n);     xits=vector(1,n);
       free_vector(ptt,1,n);     *fret=(*func)(p);
       free_vector(pt,1,n);     for (j=1;j<=n;j++) pt[j]=p[j];
       return;     for (*iter=1;;++(*iter)) {
     }       fp=(*fret);
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");       ibig=0;
     for (j=1;j<=n;j++) {       del=0.0;
       ptt[j]=2.0*p[j]-pt[j];       last_time=curr_time;
       xit[j]=p[j]-pt[j];       (void) gettimeofday(&curr_time,&tzp);
       pt[j]=p[j];       printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
     }       fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
     fptt=(*func)(ptt);   /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
     if (fptt < fp) {      for (i=1;i<=n;i++) {
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);         printf(" %d %.12f",i, p[i]);
       if (t < 0.0) {         fprintf(ficlog," %d %.12lf",i, p[i]);
         linmin(p,xit,n,fret,func);         fprintf(ficrespow," %.12lf", p[i]);
         for (j=1;j<=n;j++) {       }
           xi[j][ibig]=xi[j][n];       printf("\n");
           xi[j][n]=xit[j];       fprintf(ficlog,"\n");
         }      fprintf(ficrespow,"\n");fflush(ficrespow);
 #ifdef DEBUG      if(*iter <=3){
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        tm = *localtime(&curr_time.tv_sec);
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        strcpy(strcurr,asctime(&tm));
         for(j=1;j<=n;j++){  /*       asctime_r(&tm,strcurr); */
           printf(" %.12e",xit[j]);        forecast_time=curr_time;
           fprintf(ficlog," %.12e",xit[j]);        itmp = strlen(strcurr);
         }        if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
         printf("\n");          strcurr[itmp-1]='\0';
         fprintf(ficlog,"\n");        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
 #endif        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       }        for(niterf=10;niterf<=30;niterf+=10){
     }           forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
   }           tmf = *localtime(&forecast_time.tv_sec);
 }   /*      asctime_r(&tmf,strfor); */
           strcpy(strfor,asctime(&tmf));
 /**** Prevalence limit (stable prevalence)  ****************/          itmp = strlen(strfor);
           if(strfor[itmp-1]=='\n')
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)          strfor[itmp-1]='\0';
 {          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);
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit          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);
      matrix by transitions matrix until convergence is reached */        }
       }
   int i, ii,j,k;      for (i=1;i<=n;i++) {
   double min, max, maxmin, maxmax,sumnew=0.;        for (j=1;j<=n;j++) xit[j]=xi[j][i];
   double **matprod2();        fptt=(*fret);
   double **out, cov[NCOVMAX], **pmij();  #ifdef DEBUG
   double **newm;        printf("fret=%lf \n",*fret);
   double agefin, delaymax=50 ; /* Max number of years to converge */        fprintf(ficlog,"fret=%lf \n",*fret);
   #endif
   for (ii=1;ii<=nlstate+ndeath;ii++)        printf("%d",i);fflush(stdout);
     for (j=1;j<=nlstate+ndeath;j++){        fprintf(ficlog,"%d",i);fflush(ficlog);
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);        linmin(p,xit,n,fret,func);
     }        if (fabs(fptt-(*fret)) > del) {
           del=fabs(fptt-(*fret));
    cov[1]=1.;          ibig=i;
          }
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */  #ifdef DEBUG
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){        printf("%d %.12e",i,(*fret));
     newm=savm;        fprintf(ficlog,"%d %.12e",i,(*fret));
     /* Covariates have to be included here again */        for (j=1;j<=n;j++) {
      cov[2]=agefin;          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
             printf(" x(%d)=%.12e",j,xit[j]);
       for (k=1; k<=cptcovn;k++) {          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
         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]]);*/        for(j=1;j<=n;j++) {
       }          printf(" p=%.12e",p[j]);
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          fprintf(ficlog," p=%.12e",p[j]);
       for (k=1; k<=cptcovprod;k++)        }
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        printf("\n");
         fprintf(ficlog,"\n");
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/  #endif
       /*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]);*/      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);  #ifdef DEBUG
         int k[2],l;
     savm=oldm;        k[0]=1;
     oldm=newm;        k[1]=-1;
     maxmax=0.;        printf("Max: %.12e",(*func)(p));
     for(j=1;j<=nlstate;j++){        fprintf(ficlog,"Max: %.12e",(*func)(p));
       min=1.;        for (j=1;j<=n;j++) {
       max=0.;          printf(" %.12e",p[j]);
       for(i=1; i<=nlstate; i++) {          fprintf(ficlog," %.12e",p[j]);
         sumnew=0;        }
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];        printf("\n");
         prlim[i][j]= newm[i][j]/(1-sumnew);        fprintf(ficlog,"\n");
         max=FMAX(max,prlim[i][j]);        for(l=0;l<=1;l++) {
         min=FMIN(min,prlim[i][j]);          for (j=1;j<=n;j++) {
       }            ptt[j]=p[j]+(p[j]-pt[j])*k[l];
       maxmin=max-min;            printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
       maxmax=FMAX(maxmax,maxmin);            fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
     }          }
     if(maxmax < ftolpl){          printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       return prlim;          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
     }        }
   }  #endif
 }  
   
 /*************** transition probabilities ***************/         free_vector(xit,1,n);
         free_vector(xits,1,n);
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )        free_vector(ptt,1,n);
 {        free_vector(pt,1,n);
   double s1, s2;        return;
   /*double t34;*/      }
   int i,j,j1, nc, ii, jj;      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
       for (j=1;j<=n;j++) {
     for(i=1; i<= nlstate; i++){        ptt[j]=2.0*p[j]-pt[j];
       for(j=1; j<i;j++){        xit[j]=p[j]-pt[j];
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){        pt[j]=p[j];
           /*s2 += param[i][j][nc]*cov[nc];*/      }
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];      fptt=(*func)(ptt);
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */      if (fptt < fp) {
         }        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
         ps[i][j]=s2;        if (t < 0.0) {
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */          linmin(p,xit,n,fret,func);
       }          for (j=1;j<=n;j++) {
       for(j=i+1; j<=nlstate+ndeath;j++){            xi[j][ibig]=xi[j][n];
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){            xi[j][n]=xit[j];
           s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];          }
 /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */  #ifdef DEBUG
         }          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
         ps[i][j]=s2;          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
       }          for(j=1;j<=n;j++){
     }            printf(" %.12e",xit[j]);
     /*ps[3][2]=1;*/            fprintf(ficlog," %.12e",xit[j]);
               }
     for(i=1; i<= nlstate; i++){          printf("\n");
       s1=0;          fprintf(ficlog,"\n");
       for(j=1; j<i; j++)  #endif
         s1+=exp(ps[i][j]);        }
       for(j=i+1; j<=nlstate+ndeath; j++)      }
         s1+=exp(ps[i][j]);    }
       ps[i][i]=1./(s1+1.);  }
       for(j=1; j<i; j++)  
         ps[i][j]= exp(ps[i][j])*ps[i][i];  /**** Prevalence limit (stable or period prevalence)  ****************/
       for(j=i+1; j<=nlstate+ndeath; j++)  
         ps[i][j]= exp(ps[i][j])*ps[i][i];  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */  {
     } /* end i */    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
            matrix by transitions matrix until convergence is reached */
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){  
       for(jj=1; jj<= nlstate+ndeath; jj++){    int i, ii,j,k;
         ps[ii][jj]=0;    double min, max, maxmin, maxmax,sumnew=0.;
         ps[ii][ii]=1;    double **matprod2();
       }    double **out, cov[NCOVMAX], **pmij();
     }    double **newm;
         double agefin, delaymax=50 ; /* Max number of years to converge */
   
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */    for (ii=1;ii<=nlstate+ndeath;ii++)
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */      for (j=1;j<=nlstate+ndeath;j++){
 /*         printf("ddd %lf ",ps[ii][jj]); */        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 /*       } */      }
 /*       printf("\n "); */  
 /*        } */     cov[1]=1.;
 /*        printf("\n ");printf("%lf ",cov[2]); */   
        /*   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
       for(i=1; i<= npar; i++) printf("%f ",x[i]);    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
       goto end;*/      newm=savm;
     return ps;      /* Covariates have to be included here again */
 }       cov[2]=agefin;
    
 /**************** Product of 2 matrices ******************/        for (k=1; k<=cptcovn;k++) {
           cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)          /*      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]]);*/
 {        }
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */        for (k=1; k<=cptcovprod;k++)
   /* in, b, out are matrice of pointers which should have been initialized           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
      before: only the contents of out is modified. The function returns  
      a pointer to pointers identical to out */        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
   long i, j, k;        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
   for(i=nrl; i<= nrh; i++)        /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
     for(k=ncolol; k<=ncoloh; k++)      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
       for(j=ncl,out[i][k]=0.; j<=nch; j++)  
         out[i][k] +=in[i][j]*b[j][k];      savm=oldm;
       oldm=newm;
   return out;      maxmax=0.;
 }      for(j=1;j<=nlstate;j++){
         min=1.;
         max=0.;
 /************* Higher Matrix Product ***************/        for(i=1; i<=nlstate; i++) {
           sumnew=0;
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 {          prlim[i][j]= newm[i][j]/(1-sumnew);
   /* Computes the transition matrix starting at age 'age' over           max=FMAX(max,prlim[i][j]);
      'nhstepm*hstepm*stepm' months (i.e. until          min=FMIN(min,prlim[i][j]);
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying         }
      nhstepm*hstepm matrices.         maxmin=max-min;
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step         maxmax=FMAX(maxmax,maxmin);
      (typically every 2 years instead of every month which is too big       }
      for the memory).      if(maxmax < ftolpl){
      Model is determined by parameters x and covariates have to be         return prlim;
      included manually here.       }
     }
      */  }
   
   int i, j, d, h, k;  /*************** transition probabilities ***************/
   double **out, cov[NCOVMAX];  
   double **newm;  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
   {
   /* Hstepm could be zero and should return the unit matrix */    double s1, s2;
   for (i=1;i<=nlstate+ndeath;i++)    /*double t34;*/
     for (j=1;j<=nlstate+ndeath;j++){    int i,j,j1, nc, ii, jj;
       oldm[i][j]=(i==j ? 1.0 : 0.0);  
       po[i][j][0]=(i==j ? 1.0 : 0.0);      for(i=1; i<= nlstate; i++){
     }        for(j=1; j<i;j++){
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
   for(h=1; h <=nhstepm; h++){            /*s2 += param[i][j][nc]*cov[nc];*/
     for(d=1; d <=hstepm; d++){            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
       newm=savm;  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
       /* Covariates have to be included here again */          }
       cov[1]=1.;          ps[i][j]=s2;
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];        }
       for (k=1; k<=cptcovage;k++)        for(j=i+1; j<=nlstate+ndeath;j++){
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
       for (k=1; k<=cptcovprod;k++)            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
           }
           ps[i][j]=s2;
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/        }
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/      }
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,       /*ps[3][2]=1;*/
                    pmij(pmmij,cov,ncovmodel,x,nlstate));     
       savm=oldm;      for(i=1; i<= nlstate; i++){
       oldm=newm;        s1=0;
     }        for(j=1; j<i; j++)
     for(i=1; i<=nlstate+ndeath; i++)          s1+=exp(ps[i][j]);
       for(j=1;j<=nlstate+ndeath;j++) {        for(j=i+1; j<=nlstate+ndeath; j++)
         po[i][j][h]=newm[i][j];          s1+=exp(ps[i][j]);
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);        ps[i][i]=1./(s1+1.);
          */        for(j=1; j<i; j++)
       }          ps[i][j]= exp(ps[i][j])*ps[i][i];
   } /* end h */        for(j=i+1; j<=nlstate+ndeath; j++)
   return po;          ps[i][j]= exp(ps[i][j])*ps[i][i];
 }        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
       } /* end i */
      
 /*************** log-likelihood *************/      for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 double func( double *x)        for(jj=1; jj<= nlstate+ndeath; jj++){
 {          ps[ii][jj]=0;
   int i, ii, j, k, mi, d, kk;          ps[ii][ii]=1;
   double l, ll[NLSTATEMAX], cov[NCOVMAX];        }
   double **out;      }
   double sw; /* Sum of weights */     
   double lli; /* Individual log likelihood */  
   int s1, s2;  /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
   double bbh, survp;  /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
   long ipmx;  /*         printf("ddd %lf ",ps[ii][jj]); */
   /*extern weight */  /*       } */
   /* We are differentiating ll according to initial status */  /*       printf("\n "); */
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/  /*        } */
   /*for(i=1;i<imx;i++)   /*        printf("\n ");printf("%lf ",cov[2]); */
     printf(" %d\n",s[4][i]);         /*
   */        for(i=1; i<= npar; i++) printf("%f ",x[i]);
   cov[1]=1.;        goto end;*/
       return ps;
   for(k=1; k<=nlstate; k++) ll[k]=0.;  }
   
   if(mle==1){  /**************** Product of 2 matrices ******************/
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];  double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
       for(mi=1; mi<= wav[i]-1; mi++){  {
         for (ii=1;ii<=nlstate+ndeath;ii++)    /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
           for (j=1;j<=nlstate+ndeath;j++){       b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    /* in, b, out are matrice of pointers which should have been initialized
             savm[ii][j]=(ii==j ? 1.0 : 0.0);       before: only the contents of out is modified. The function returns
           }       a pointer to pointers identical to out */
         for(d=0; d<dh[mi][i]; d++){    long i, j, k;
           newm=savm;    for(i=nrl; i<= nrh; i++)
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;      for(k=ncolol; k<=ncoloh; k++)
           for (kk=1; kk<=cptcovage;kk++) {        for(j=ncl,out[i][k]=0.; j<=nch; j++)
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          out[i][k] +=in[i][j]*b[j][k];
           }  
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    return out;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));  }
           savm=oldm;  
           oldm=newm;  
         } /* end mult */  /************* Higher Matrix Product ***************/
         
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */  double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
         /* But now since version 0.9 we anticipate for bias at large stepm.  {
          * If stepm is larger than one month (smallest stepm) and if the exact delay     /* Computes the transition matrix starting at age 'age' over
          * (in months) between two waves is not a multiple of stepm, we rounded to        'nhstepm*hstepm*stepm' months (i.e. until
          * the nearest (and in case of equal distance, to the lowest) interval but now       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
          * we keep into memory the bias bh[mi][i] and also the previous matrix product       nhstepm*hstepm matrices.
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
          * probability in order to take into account the bias as a fraction of the way       (typically every 2 years instead of every month which is too big
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies       for the memory).
          * -stepm/2 to stepm/2 .       Model is determined by parameters x and covariates have to be
          * For stepm=1 the results are the same as for previous versions of Imach.       included manually here.
          * For stepm > 1 the results are less biased than in previous versions.   
          */       */
         s1=s[mw[mi][i]][i];  
         s2=s[mw[mi+1][i]][i];    int i, j, d, h, k;
         bbh=(double)bh[mi][i]/(double)stepm;     double **out, cov[NCOVMAX];
         /* bias bh is positive if real duration    double **newm;
          * is higher than the multiple of stepm and negative otherwise.  
          */    /* Hstepm could be zero and should return the unit matrix */
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/    for (i=1;i<=nlstate+ndeath;i++)
         if( s2 > nlstate){       for (j=1;j<=nlstate+ndeath;j++){
           /* i.e. if s2 is a death state and if the date of death is known         oldm[i][j]=(i==j ? 1.0 : 0.0);
              then the contribution to the likelihood is the probability to         po[i][j][0]=(i==j ? 1.0 : 0.0);
              die between last step unit time and current  step unit time,       }
              which is also equal to probability to die before dh     /* Even if hstepm = 1, at least one multiplication by the unit matrix */
              minus probability to die before dh-stepm .     for(h=1; h <=nhstepm; h++){
              In version up to 0.92 likelihood was computed      for(d=1; d <=hstepm; d++){
         as if date of death was unknown. Death was treated as any other        newm=savm;
         health state: the date of the interview describes the actual state        /* Covariates have to be included here again */
         and not the date of a change in health state. The former idea was        cov[1]=1.;
         to consider that at each interview the state was recorded        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
         (healthy, disable or death) and IMaCh was corrected; but when we        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
         introduced the exact date of death then we should have modified        for (k=1; k<=cptcovage;k++)
         the contribution of an exact death to the likelihood. This new          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         contribution is smaller and very dependent of the step unit        for (k=1; k<=cptcovprod;k++)
         stepm. It is no more the probability to die between last interview          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         and month of death but the probability to survive from last  
         interview up to one month before death multiplied by the  
         probability to die within a month. Thanks to Chris        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
         Jackson for correcting this bug.  Former versions increased        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
         mortality artificially. The bad side is that we add another loop        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
         which slows down the processing. The difference can be up to 10%                     pmij(pmmij,cov,ncovmodel,x,nlstate));
         lower mortality.        savm=oldm;
           */        oldm=newm;
           lli=log(out[s1][s2] - savm[s1][s2]);      }
       for(i=1; i<=nlstate+ndeath; i++)
         for(j=1;j<=nlstate+ndeath;j++) {
         } else if  (s2==-2) {          po[i][j][h]=newm[i][j];
           for (j=1,survp=0. ; j<=nlstate; j++)           /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
             survp += out[s1][j];           */
           lli= survp;        }
         }    } /* end h */
             return po;
         else if  (s2==-4) {  }
           for (j=3,survp=0. ; j<=nlstate; j++)   
             survp += out[s1][j];  
           lli= survp;  /*************** log-likelihood *************/
         }  double func( double *x)
           {
         else if  (s2==-5) {    int i, ii, j, k, mi, d, kk;
           for (j=1,survp=0. ; j<=2; j++)     double l, ll[NLSTATEMAX], cov[NCOVMAX];
             survp += out[s1][j];    double **out;
           lli= survp;    double sw; /* Sum of weights */
         }    double lli; /* Individual log likelihood */
     int s1, s2;
     double bbh, survp;
         else{    long ipmx;
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */    /*extern weight */
           /*  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 */    /* We are differentiating ll according to initial status */
         }     /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/    /*for(i=1;i<imx;i++)
         /*if(lli ==000.0)*/      printf(" %d\n",s[4][i]);
         /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */    */
         ipmx +=1;    cov[1]=1.;
         sw += weight[i];  
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;    for(k=1; k<=nlstate; k++) ll[k]=0.;
       } /* end of wave */  
     } /* end of individual */    if(mle==1){
   }  else if(mle==2){      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];        for(mi=1; mi<= wav[i]-1; mi++){
       for(mi=1; mi<= wav[i]-1; mi++){          for (ii=1;ii<=nlstate+ndeath;ii++)
         for (ii=1;ii<=nlstate+ndeath;ii++)            for (j=1;j<=nlstate+ndeath;j++){
           for (j=1;j<=nlstate+ndeath;j++){              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);              savm[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++){
         for(d=0; d<=dh[mi][i]; d++){            newm=savm;
           newm=savm;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            for (kk=1; kk<=cptcovage;kk++) {
           for (kk=1; kk<=cptcovage;kk++) {              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];            }
           }            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            savm=oldm;
           savm=oldm;            oldm=newm;
           oldm=newm;          } /* end mult */
         } /* end mult */       
                 /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
         s1=s[mw[mi][i]][i];          /* But now since version 0.9 we anticipate for bias at large stepm.
         s2=s[mw[mi+1][i]][i];           * If stepm is larger than one month (smallest stepm) and if the exact delay
         bbh=(double)bh[mi][i]/(double)stepm;            * (in months) between two waves is not a multiple of stepm, we rounded to
         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 */           * the nearest (and in case of equal distance, to the lowest) interval but now
         ipmx +=1;           * we keep into memory the bias bh[mi][i] and also the previous matrix product
         sw += weight[i];           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;           * probability in order to take into account the bias as a fraction of the way
       } /* end of wave */           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
     } /* end of individual */           * -stepm/2 to stepm/2 .
   }  else if(mle==3){  /* exponential inter-extrapolation */           * For stepm=1 the results are the same as for previous versions of Imach.
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){           * For stepm > 1 the results are less biased than in previous versions.
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];           */
       for(mi=1; mi<= wav[i]-1; mi++){          s1=s[mw[mi][i]][i];
         for (ii=1;ii<=nlstate+ndeath;ii++)          s2=s[mw[mi+1][i]][i];
           for (j=1;j<=nlstate+ndeath;j++){          bbh=(double)bh[mi][i]/(double)stepm;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          /* bias bh is positive if real duration
             savm[ii][j]=(ii==j ? 1.0 : 0.0);           * is higher than the multiple of stepm and negative otherwise.
           }           */
         for(d=0; d<dh[mi][i]; d++){          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
           newm=savm;          if( s2 > nlstate){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            /* i.e. if s2 is a death state and if the date of death is known
           for (kk=1; kk<=cptcovage;kk++) {               then the contribution to the likelihood is the probability to
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];               die between last step unit time and current  step unit time,
           }               which is also equal to probability to die before dh
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,               minus probability to die before dh-stepm .
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));               In version up to 0.92 likelihood was computed
           savm=oldm;          as if date of death was unknown. Death was treated as any other
           oldm=newm;          health state: the date of the interview describes the actual state
         } /* end mult */          and not the date of a change in health state. The former idea was
                 to consider that at each interview the state was recorded
         s1=s[mw[mi][i]][i];          (healthy, disable or death) and IMaCh was corrected; but when we
         s2=s[mw[mi+1][i]][i];          introduced the exact date of death then we should have modified
         bbh=(double)bh[mi][i]/(double)stepm;           the contribution of an exact death to the likelihood. This new
         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 */          contribution is smaller and very dependent of the step unit
         ipmx +=1;          stepm. It is no more the probability to die between last interview
         sw += weight[i];          and month of death but the probability to survive from last
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          interview up to one month before death multiplied by the
       } /* end of wave */          probability to die within a month. Thanks to Chris
     } /* end of individual */          Jackson for correcting this bug.  Former versions increased
   }else if (mle==4){  /* ml=4 no inter-extrapolation */          mortality artificially. The bad side is that we add another loop
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          which slows down the processing. The difference can be up to 10%
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          lower mortality.
       for(mi=1; mi<= wav[i]-1; mi++){            */
         for (ii=1;ii<=nlstate+ndeath;ii++)            lli=log(out[s1][s2] - savm[s1][s2]);
           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);          } else if  (s2==-2) {
           }            for (j=1,survp=0. ; j<=nlstate; j++)
         for(d=0; d<dh[mi][i]; d++){              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           newm=savm;            /*survp += out[s1][j]; */
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            lli= log(survp);
           for (kk=1; kk<=cptcovage;kk++) {          }
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];         
           }          else if  (s2==-4) {
                     for (j=3,survp=0. ; j<=nlstate; j++)  
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            lli= log(survp);
           savm=oldm;          }
           oldm=newm;  
         } /* end mult */          else if  (s2==-5) {
                   for (j=1,survp=0. ; j<=2; j++)  
         s1=s[mw[mi][i]][i];              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         s2=s[mw[mi+1][i]][i];            lli= log(survp);
         if( s2 > nlstate){           }
           lli=log(out[s1][s2] - savm[s1][s2]);         
         }else{          else{
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
         }            /*  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 */
         ipmx +=1;          }
         sw += weight[i];          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          /*if(lli ==000.0)*/
 /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */          /*printf("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); */
       } /* end of wave */          ipmx +=1;
     } /* end of individual */          sw += weight[i];
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){        } /* end of wave */
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];      } /* end of individual */
       for(mi=1; mi<= wav[i]-1; mi++){    }  else if(mle==2){
         for (ii=1;ii<=nlstate+ndeath;ii++)      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
           for (j=1;j<=nlstate+ndeath;j++){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);        for(mi=1; mi<= wav[i]-1; mi++){
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          for (ii=1;ii<=nlstate+ndeath;ii++)
           }            for (j=1;j<=nlstate+ndeath;j++){
         for(d=0; d<dh[mi][i]; d++){              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           newm=savm;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            }
           for (kk=1; kk<=cptcovage;kk++) {          for(d=0; d<=dh[mi][i]; d++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];            newm=savm;
           }            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                     for (kk=1; kk<=cptcovage;kk++) {
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            }
           savm=oldm;            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
           oldm=newm;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         } /* end mult */            savm=oldm;
                   oldm=newm;
         s1=s[mw[mi][i]][i];          } /* end mult */
         s2=s[mw[mi+1][i]][i];       
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */          s1=s[mw[mi][i]][i];
         ipmx +=1;          s2=s[mw[mi+1][i]][i];
         sw += weight[i];          bbh=(double)bh[mi][i]/(double)stepm;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          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("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]);*/          ipmx +=1;
       } /* end of wave */          sw += weight[i];
     } /* end of individual */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   } /* End of if */        } /* end of wave */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];      } /* end of individual */
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */    }  else if(mle==3){  /* exponential inter-extrapolation */
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   return -l;        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++)
 /*************** log-likelihood *************/            for (j=1;j<=nlstate+ndeath;j++){
 double funcone( double *x)              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 {              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   /* Same as likeli but slower because of a lot of printf and if */            }
   int i, ii, j, k, mi, d, kk;          for(d=0; d<dh[mi][i]; d++){
   double l, ll[NLSTATEMAX], cov[NCOVMAX];            newm=savm;
   double **out;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   double lli; /* Individual log likelihood */            for (kk=1; kk<=cptcovage;kk++) {
   double llt;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   int s1, s2;            }
   double bbh, survp;            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   /*extern weight */                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   /* We are differentiating ll according to initial status */            savm=oldm;
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/            oldm=newm;
   /*for(i=1;i<imx;i++)           } /* end mult */
     printf(" %d\n",s[4][i]);       
   */          s1=s[mw[mi][i]][i];
   cov[1]=1.;          s2=s[mw[mi+1][i]][i];
           bbh=(double)bh[mi][i]/(double)stepm;
   for(k=1; k<=nlstate; k++) ll[k]=0.;          lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
           ipmx +=1;
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){          sw += weight[i];
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     for(mi=1; mi<= wav[i]-1; mi++){        } /* end of wave */
       for (ii=1;ii<=nlstate+ndeath;ii++)      } /* end of individual */
         for (j=1;j<=nlstate+ndeath;j++){    }else if (mle==4){  /* ml=4 no inter-extrapolation */
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
           savm[ii][j]=(ii==j ? 1.0 : 0.0);        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         }        for(mi=1; mi<= wav[i]-1; mi++){
       for(d=0; d<dh[mi][i]; d++){          for (ii=1;ii<=nlstate+ndeath;ii++)
         newm=savm;            for (j=1;j<=nlstate+ndeath;j++){
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         for (kk=1; kk<=cptcovage;kk++) {              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];            }
         }          for(d=0; d<dh[mi][i]; d++){
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,            newm=savm;
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         savm=oldm;            for (kk=1; kk<=cptcovage;kk++) {
         oldm=newm;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
       } /* end mult */            }
                
       s1=s[mw[mi][i]][i];            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
       s2=s[mw[mi+1][i]][i];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
       bbh=(double)bh[mi][i]/(double)stepm;             savm=oldm;
       /* bias is positive if real duration            oldm=newm;
        * is higher than the multiple of stepm and negative otherwise.          } /* end mult */
        */       
       if( s2 > nlstate && (mle <5) ){  /* Jackson */          s1=s[mw[mi][i]][i];
         lli=log(out[s1][s2] - savm[s1][s2]);          s2=s[mw[mi+1][i]][i];
       } else if (mle==1){          if( s2 > nlstate){
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */            lli=log(out[s1][s2] - savm[s1][s2]);
       } else if(mle==2){          }else{
         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 */            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
       } else if(mle==3){  /* exponential inter-extrapolation */          }
         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 */          ipmx +=1;
       } else if (mle==4){  /* mle=4 no inter-extrapolation */          sw += weight[i];
         lli=log(out[s1][s2]); /* Original formula */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */  /*      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]); */
         lli=log(out[s1][s2]); /* Original formula */        } /* end of wave */
       } /* End of if */      } /* end of individual */
       ipmx +=1;    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
       sw += weight[i];      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 /*       printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */        for(mi=1; mi<= wav[i]-1; mi++){
       if(globpr){          for (ii=1;ii<=nlstate+ndeath;ii++)
         fprintf(ficresilk,"%9d %6d %1d %1d %1d %1d %3d %10.6f %6.4f\            for (j=1;j<=nlstate+ndeath;j++){
  %10.6f %10.6f %10.6f ", \              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],              savm[ii][j]=(ii==j ? 1.0 : 0.0);
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);            }
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){          for(d=0; d<dh[mi][i]; d++){
           llt +=ll[k]*gipmx/gsw;            newm=savm;
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         }            for (kk=1; kk<=cptcovage;kk++) {
         fprintf(ficresilk," %10.6f\n", -llt);              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
       }            }
     } /* end of wave */         
   } /* end of individual */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */            savm=oldm;
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */            oldm=newm;
   if(globpr==0){ /* First time we count the contributions and weights */          } /* end mult */
     gipmx=ipmx;       
     gsw=sw;          s1=s[mw[mi][i]][i];
   }          s2=s[mw[mi+1][i]][i];
   return -l;          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 }          ipmx +=1;
           sw += weight[i];
           ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 /*************** function likelione ***********/          /*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]);*/
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))        } /* end of wave */
 {      } /* end of individual */
   /* This routine should help understanding what is done with     } /* End of if */
      the selection of individuals/waves and    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
      to check the exact contribution to the likelihood.    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
      Plotting could be done.    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
    */    return -l;
   int k;  }
   
   if(*globpri !=0){ /* Just counts and sums, no printings */  /*************** log-likelihood *************/
     strcpy(fileresilk,"ilk");   double funcone( double *x)
     strcat(fileresilk,fileres);  {
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {    /* Same as likeli but slower because of a lot of printf and if */
       printf("Problem with resultfile: %s\n", fileresilk);    int i, ii, j, k, mi, d, kk;
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);    double l, ll[NLSTATEMAX], cov[NCOVMAX];
     }    double **out;
     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");    double lli; /* Individual log likelihood */
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");    double llt;
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */    int s1, s2;
     for(k=1; k<=nlstate; k++)     double bbh, survp;
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);    /*extern weight */
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");    /* We are differentiating ll according to initial status */
   }    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     /*for(i=1;i<imx;i++)
   *fretone=(*funcone)(p);      printf(" %d\n",s[4][i]);
   if(*globpri !=0){    */
     fclose(ficresilk);    cov[1]=1.;
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));  
     fflush(fichtm);     for(k=1; k<=nlstate; k++) ll[k]=0.;
   }   
   return;    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 }      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       for(mi=1; mi<= wav[i]-1; mi++){
         for (ii=1;ii<=nlstate+ndeath;ii++)
 /*********** Maximum Likelihood Estimation ***************/          for (j=1;j<=nlstate+ndeath;j++){
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))            savm[ii][j]=(ii==j ? 1.0 : 0.0);
 {          }
   int i,j, iter;        for(d=0; d<dh[mi][i]; d++){
   double **xi;          newm=savm;
   double fret;          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   double fretone; /* Only one call to likelihood */          for (kk=1; kk<=cptcovage;kk++) {
   /*  char filerespow[FILENAMELENGTH];*/            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   xi=matrix(1,npar,1,npar);          }
   for (i=1;i<=npar;i++)          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
     for (j=1;j<=npar;j++)                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
       xi[i][j]=(i==j ? 1.0 : 0.0);          savm=oldm;
   printf("Powell\n");  fprintf(ficlog,"Powell\n");          oldm=newm;
   strcpy(filerespow,"pow");         } /* end mult */
   strcat(filerespow,fileres);       
   if((ficrespow=fopen(filerespow,"w"))==NULL) {        s1=s[mw[mi][i]][i];
     printf("Problem with resultfile: %s\n", filerespow);        s2=s[mw[mi+1][i]][i];
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);        bbh=(double)bh[mi][i]/(double)stepm;
   }        /* bias is positive if real duration
   fprintf(ficrespow,"# Powell\n# iter -2*LL");         * is higher than the multiple of stepm and negative otherwise.
   for (i=1;i<=nlstate;i++)         */
     for(j=1;j<=nlstate+ndeath;j++)        if( s2 > nlstate && (mle <5) ){  /* Jackson */
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);          lli=log(out[s1][s2] - savm[s1][s2]);
   fprintf(ficrespow,"\n");        } else if  (s2==-2) {
           for (j=1,survp=0. ; j<=nlstate; j++)
   powell(p,xi,npar,ftol,&iter,&fret,func);            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           lli= log(survp);
   fclose(ficrespow);        }else if (mle==1){
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));        } else if(mle==2){
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));          lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
         } else if(mle==3){  /* exponential inter-extrapolation */
 }          lli= (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 */
 /**** Computes Hessian and covariance matrix ***/          lli=log(out[s1][s2]); /* Original formula */
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
 {          lli=log(out[s1][s2]); /* Original formula */
   double  **a,**y,*x,pd;        } /* End of if */
   double **hess;        ipmx +=1;
   int i, j,jk;        sw += weight[i];
   int *indx;        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]); */
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);        if(globpr){
   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
   void lubksb(double **a, int npar, int *indx, double b[]) ;   %11.6f %11.6f %11.6f ", \
   void ludcmp(double **a, int npar, int *indx, double *d) ;                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
   double gompertz(double p[]);                  2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
   hess=matrix(1,npar,1,npar);          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
             llt +=ll[k]*gipmx/gsw;
   printf("\nCalculation of the hessian matrix. Wait...\n");            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");          }
   for (i=1;i<=npar;i++){          fprintf(ficresilk," %10.6f\n", -llt);
     printf("%d",i);fflush(stdout);        }
     fprintf(ficlog,"%d",i);fflush(ficlog);      } /* end of wave */
        } /* end of individual */
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
         /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     /*  printf(" %f ",p[i]);    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/    if(globpr==0){ /* First time we count the contributions and weights */
   }      gipmx=ipmx;
         gsw=sw;
   for (i=1;i<=npar;i++) {    }
     for (j=1;j<=npar;j++)  {    return -l;
       if (j>i) {   }
         printf(".%d%d",i,j);fflush(stdout);  
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);  
         hess[i][j]=hessij(p,delti,i,j,func,npar);  /*************** function likelione ***********/
           void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
         hess[j][i]=hess[i][j];      {
         /*printf(" %lf ",hess[i][j]);*/    /* This routine should help understanding what is done with
       }       the selection of individuals/waves and
     }       to check the exact contribution to the likelihood.
   }       Plotting could be done.
   printf("\n");     */
   fprintf(ficlog,"\n");    int k;
   
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");    if(*globpri !=0){ /* Just counts and sums, no printings */
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");      strcpy(fileresilk,"ilk");
         strcat(fileresilk,fileres);
   a=matrix(1,npar,1,npar);      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
   y=matrix(1,npar,1,npar);        printf("Problem with resultfile: %s\n", fileresilk);
   x=vector(1,npar);        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
   indx=ivector(1,npar);      }
   for (i=1;i<=npar;i++)      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");
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];      fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
   ludcmp(a,npar,indx,&pd);      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
       for(k=1; k<=nlstate; k++)
   for (j=1;j<=npar;j++) {        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
     for (i=1;i<=npar;i++) x[i]=0;      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
     x[j]=1;    }
     lubksb(a,npar,indx,x);  
     for (i=1;i<=npar;i++){     *fretone=(*funcone)(p);
       matcov[i][j]=x[i];    if(*globpri !=0){
     }      fclose(ficresilk);
   }      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
       fflush(fichtm);
   printf("\n#Hessian matrix#\n");    }
   fprintf(ficlog,"\n#Hessian matrix#\n");    return;
   for (i=1;i<=npar;i++) {   }
     for (j=1;j<=npar;j++) {   
       printf("%.3e ",hess[i][j]);  
       fprintf(ficlog,"%.3e ",hess[i][j]);  /*********** Maximum Likelihood Estimation ***************/
     }  
     printf("\n");  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
     fprintf(ficlog,"\n");  {
   }    int i,j, iter;
     double **xi;
   /* Recompute Inverse */    double fret;
   for (i=1;i<=npar;i++)    double fretone; /* Only one call to likelihood */
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];    /*  char filerespow[FILENAMELENGTH];*/
   ludcmp(a,npar,indx,&pd);    xi=matrix(1,npar,1,npar);
     for (i=1;i<=npar;i++)
   /*  printf("\n#Hessian matrix recomputed#\n");      for (j=1;j<=npar;j++)
         xi[i][j]=(i==j ? 1.0 : 0.0);
   for (j=1;j<=npar;j++) {    printf("Powell\n");  fprintf(ficlog,"Powell\n");
     for (i=1;i<=npar;i++) x[i]=0;    strcpy(filerespow,"pow");
     x[j]=1;    strcat(filerespow,fileres);
     lubksb(a,npar,indx,x);    if((ficrespow=fopen(filerespow,"w"))==NULL) {
     for (i=1;i<=npar;i++){       printf("Problem with resultfile: %s\n", filerespow);
       y[i][j]=x[i];      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
       printf("%.3e ",y[i][j]);    }
       fprintf(ficlog,"%.3e ",y[i][j]);    fprintf(ficrespow,"# Powell\n# iter -2*LL");
     }    for (i=1;i<=nlstate;i++)
     printf("\n");      for(j=1;j<=nlstate+ndeath;j++)
     fprintf(ficlog,"\n");        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   }    fprintf(ficrespow,"\n");
   */  
     powell(p,xi,npar,ftol,&iter,&fret,func);
   free_matrix(a,1,npar,1,npar);  
   free_matrix(y,1,npar,1,npar);    free_matrix(xi,1,npar,1,npar);
   free_vector(x,1,npar);    fclose(ficrespow);
   free_ivector(indx,1,npar);    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
   free_matrix(hess,1,npar,1,npar);    fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
     fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
   
 }  }
   
 /*************** hessian matrix ****************/  /**** Computes Hessian and covariance matrix ***/
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 {  {
   int i;    double  **a,**y,*x,pd;
   int l=1, lmax=20;    double **hess;
   double k1,k2;    int i, j,jk;
   double p2[NPARMAX+1];    int *indx;
   double res;  
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;    double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
   double fx;    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
   int k=0,kmax=10;    void lubksb(double **a, int npar, int *indx, double b[]) ;
   double l1;    void ludcmp(double **a, int npar, int *indx, double *d) ;
     double gompertz(double p[]);
   fx=func(x);    hess=matrix(1,npar,1,npar);
   for (i=1;i<=npar;i++) p2[i]=x[i];  
   for(l=0 ; l <=lmax; l++){    printf("\nCalculation of the hessian matrix. Wait...\n");
     l1=pow(10,l);    fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
     delts=delt;    for (i=1;i<=npar;i++){
     for(k=1 ; k <kmax; k=k+1){      printf("%d",i);fflush(stdout);
       delt = delta*(l1*k);      fprintf(ficlog,"%d",i);fflush(ficlog);
       p2[theta]=x[theta] +delt;     
       k1=func(p2)-fx;       hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
       p2[theta]=x[theta]-delt;     
       k2=func(p2)-fx;      /*  printf(" %f ",p[i]);
       /*res= (k1-2.0*fx+k2)/delt/delt; */          printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */    }
          
 #ifdef DEBUG    for (i=1;i<=npar;i++) {
       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);      for (j=1;j<=npar;j++)  {
       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);        if (j>i) {
 #endif          printf(".%d%d",i,j);fflush(stdout);
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){          hess[i][j]=hessij(p,delti,i,j,func,npar);
         k=kmax;         
       }          hess[j][i]=hess[i][j];    
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */          /*printf(" %lf ",hess[i][j]);*/
         k=kmax; l=lmax*10.;        }
       }      }
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){     }
         delts=delt;    printf("\n");
       }    fprintf(ficlog,"\n");
     }  
   }    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
   delti[theta]=delts;    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
   return res;    
       a=matrix(1,npar,1,npar);
 }    y=matrix(1,npar,1,npar);
     x=vector(1,npar);
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)    indx=ivector(1,npar);
 {    for (i=1;i<=npar;i++)
   int i;      for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
   int l=1, l1, lmax=20;    ludcmp(a,npar,indx,&pd);
   double k1,k2,k3,k4,res,fx;  
   double p2[NPARMAX+1];    for (j=1;j<=npar;j++) {
   int k;      for (i=1;i<=npar;i++) x[i]=0;
       x[j]=1;
   fx=func(x);      lubksb(a,npar,indx,x);
   for (k=1; k<=2; k++) {      for (i=1;i<=npar;i++){
     for (i=1;i<=npar;i++) p2[i]=x[i];        matcov[i][j]=x[i];
     p2[thetai]=x[thetai]+delti[thetai]/k;      }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    }
     k1=func(p2)-fx;  
       printf("\n#Hessian matrix#\n");
     p2[thetai]=x[thetai]+delti[thetai]/k;    fprintf(ficlog,"\n#Hessian matrix#\n");
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    for (i=1;i<=npar;i++) {
     k2=func(p2)-fx;      for (j=1;j<=npar;j++) {
           printf("%.3e ",hess[i][j]);
     p2[thetai]=x[thetai]-delti[thetai]/k;        fprintf(ficlog,"%.3e ",hess[i][j]);
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;      }
     k3=func(p2)-fx;      printf("\n");
         fprintf(ficlog,"\n");
     p2[thetai]=x[thetai]-delti[thetai]/k;    }
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;  
     k4=func(p2)-fx;    /* Recompute Inverse */
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */    for (i=1;i<=npar;i++)
 #ifdef DEBUG      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
     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);    ludcmp(a,npar,indx,&pd);
     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    /*  printf("\n#Hessian matrix recomputed#\n");
   }  
   return res;    for (j=1;j<=npar;j++) {
 }      for (i=1;i<=npar;i++) x[i]=0;
       x[j]=1;
 /************** Inverse of matrix **************/      lubksb(a,npar,indx,x);
 void ludcmp(double **a, int n, int *indx, double *d)       for (i=1;i<=npar;i++){
 {         y[i][j]=x[i];
   int i,imax,j,k;         printf("%.3e ",y[i][j]);
   double big,dum,sum,temp;         fprintf(ficlog,"%.3e ",y[i][j]);
   double *vv;       }
        printf("\n");
   vv=vector(1,n);       fprintf(ficlog,"\n");
   *d=1.0;     }
   for (i=1;i<=n;i++) {     */
     big=0.0;   
     for (j=1;j<=n;j++)     free_matrix(a,1,npar,1,npar);
       if ((temp=fabs(a[i][j])) > big) big=temp;     free_matrix(y,1,npar,1,npar);
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");     free_vector(x,1,npar);
     vv[i]=1.0/big;     free_ivector(indx,1,npar);
   }     free_matrix(hess,1,npar,1,npar);
   for (j=1;j<=n;j++) {   
     for (i=1;i<j;i++) {   
       sum=a[i][j];   }
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];   
       a[i][j]=sum;   /*************** hessian matrix ****************/
     }   double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
     big=0.0;   {
     for (i=j;i<=n;i++) {     int i;
       sum=a[i][j];     int l=1, lmax=20;
       for (k=1;k<j;k++)     double k1,k2;
         sum -= a[i][k]*a[k][j];     double p2[NPARMAX+1];
       a[i][j]=sum;     double res;
       if ( (dum=vv[i]*fabs(sum)) >= big) {     double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
         big=dum;     double fx;
         imax=i;     int k=0,kmax=10;
       }     double l1;
     }   
     if (j != imax) {     fx=func(x);
       for (k=1;k<=n;k++) {     for (i=1;i<=npar;i++) p2[i]=x[i];
         dum=a[imax][k];     for(l=0 ; l <=lmax; l++){
         a[imax][k]=a[j][k];       l1=pow(10,l);
         a[j][k]=dum;       delts=delt;
       }       for(k=1 ; k <kmax; k=k+1){
       *d = -(*d);         delt = delta*(l1*k);
       vv[imax]=vv[j];         p2[theta]=x[theta] +delt;
     }         k1=func(p2)-fx;
     indx[j]=imax;         p2[theta]=x[theta]-delt;
     if (a[j][j] == 0.0) a[j][j]=TINY;         k2=func(p2)-fx;
     if (j != n) {         /*res= (k1-2.0*fx+k2)/delt/delt; */
       dum=1.0/(a[j][j]);         res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
       for (i=j+1;i<=n;i++) a[i][j] *= dum;        
     }   #ifdef DEBUG
   }         printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
   free_vector(vv,1,n);  /* Doesn't work */        fprintf(ficlog,"%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
 ;  #endif
 }         /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
         if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 void lubksb(double **a, int n, int *indx, double b[])           k=kmax;
 {         }
   int i,ii=0,ip,j;         else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
   double sum;           k=kmax; l=lmax*10.;
          }
   for (i=1;i<=n;i++) {         else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
     ip=indx[i];           delts=delt;
     sum=b[ip];         }
     b[ip]=b[i];       }
     if (ii)     }
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];     delti[theta]=delts;
     else if (sum) ii=i;     return res;
     b[i]=sum;    
   }   }
   for (i=n;i>=1;i--) {   
     sum=b[i];   double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];   {
     b[i]=sum/a[i][i];     int i;
   }     int l=1, l1, lmax=20;
 }     double k1,k2,k3,k4,res,fx;
     double p2[NPARMAX+1];
 /************ Frequencies ********************/    int k;
 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[])  
 {  /* Some frequencies */    fx=func(x);
       for (k=1; k<=2; k++) {
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;      for (i=1;i<=npar;i++) p2[i]=x[i];
   int first;      p2[thetai]=x[thetai]+delti[thetai]/k;
   double ***freq; /* Frequencies */      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   double *pp, **prop;      k1=func(p2)-fx;
   double pos,posprop, k2, dateintsum=0,k2cpt=0;   
   FILE *ficresp;      p2[thetai]=x[thetai]+delti[thetai]/k;
   char fileresp[FILENAMELENGTH];      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
         k2=func(p2)-fx;
   pp=vector(1,nlstate);   
   prop=matrix(1,nlstate,iagemin,iagemax+3);      p2[thetai]=x[thetai]-delti[thetai]/k;
   strcpy(fileresp,"p");      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   strcat(fileresp,fileres);      k3=func(p2)-fx;
   if((ficresp=fopen(fileresp,"w"))==NULL) {   
     printf("Problem with prevalence resultfile: %s\n", fileresp);      p2[thetai]=x[thetai]-delti[thetai]/k;
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
     exit(0);      k4=func(p2)-fx;
   }      res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);  #ifdef DEBUG
   j1=0;      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);
   j=cptcoveff;  #endif
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    }
     return res;
   first=1;  }
   
   for(k1=1; k1<=j;k1++){  /************** Inverse of matrix **************/
     for(i1=1; i1<=ncodemax[k1];i1++){  void ludcmp(double **a, int n, int *indx, double *d)
       j1++;  {
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    int i,imax,j,k;
         scanf("%d", i);*/    double big,dum,sum,temp;
       for (i=-5; i<=nlstate+ndeath; i++)      double *vv;
         for (jk=-5; jk<=nlstate+ndeath; jk++)     
           for(m=iagemin; m <= iagemax+3; m++)    vv=vector(1,n);
             freq[i][jk][m]=0;    *d=1.0;
     for (i=1;i<=n;i++) {
     for (i=1; i<=nlstate; i++)        big=0.0;
       for(m=iagemin; m <= iagemax+3; m++)      for (j=1;j<=n;j++)
         prop[i][m]=0;        if ((temp=fabs(a[i][j])) > big) big=temp;
             if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
       dateintsum=0;      vv[i]=1.0/big;
       k2cpt=0;    }
       for (i=1; i<=imx; i++) {    for (j=1;j<=n;j++) {
         bool=1;      for (i=1;i<j;i++) {
         if  (cptcovn>0) {        sum=a[i][j];
           for (z1=1; z1<=cptcoveff; z1++)         for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])         a[i][j]=sum;
               bool=0;      }
         }      big=0.0;
         if (bool==1){      for (i=j;i<=n;i++) {
           for(m=firstpass; m<=lastpass; m++){        sum=a[i][j];
             k2=anint[m][i]+(mint[m][i]/12.);        for (k=1;k<j;k++)
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/          sum -= a[i][k]*a[k][j];
               if(agev[m][i]==0) agev[m][i]=iagemax+1;        a[i][j]=sum;
               if(agev[m][i]==1) agev[m][i]=iagemax+2;        if ( (dum=vv[i]*fabs(sum)) >= big) {
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];          big=dum;
               if (m<lastpass) {          imax=i;
                 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];      }
               }      if (j != imax) {
                       for (k=1;k<=n;k++) {
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {          dum=a[imax][k];
                 dateintsum=dateintsum+k2;          a[imax][k]=a[j][k];
                 k2cpt++;          a[j][k]=dum;
               }        }
               /*}*/        *d = -(*d);
           }        vv[imax]=vv[j];
         }      }
       }      indx[j]=imax;
              if (a[j][j] == 0.0) a[j][j]=TINY;
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/      if (j != n) {
 fprintf(ficresp, "#Local time at start: %s", strstart);        dum=1.0/(a[j][j]);
       if  (cptcovn>0) {        for (i=j+1;i<=n;i++) a[i][j] *= dum;
         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#");    free_vector(vv,1,n);  /* Doesn't work */
       }  ;
       for(i=1; i<=nlstate;i++)   }
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);  
       fprintf(ficresp, "\n");  void lubksb(double **a, int n, int *indx, double b[])
         {
       for(i=iagemin; i <= iagemax+3; i++){    int i,ii=0,ip,j;
         if(i==iagemax+3){    double sum;
           fprintf(ficlog,"Total");   
         }else{    for (i=1;i<=n;i++) {
           if(first==1){      ip=indx[i];
             first=0;      sum=b[ip];
             printf("See log file for details...\n");      b[ip]=b[i];
           }      if (ii)
           fprintf(ficlog,"Age %d", i);        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
         }      else if (sum) ii=i;
         for(jk=1; jk <=nlstate ; jk++){      b[i]=sum;
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)    }
             pp[jk] += freq[jk][m][i];     for (i=n;i>=1;i--) {
         }      sum=b[i];
         for(jk=1; jk <=nlstate ; jk++){      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
           for(m=-1, pos=0; m <=0 ; m++)      b[i]=sum/a[i][i];
             pos += freq[jk][m][i];    }
           if(pp[jk]>=1.e-10){  }
             if(first==1){  
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);  void pstamp(FILE *fichier)
             }  {
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
           }else{  }
             if(first==1)  
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);  /************ Frequencies ********************/
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
           }  {  /* Some frequencies */
         }   
     int i, m, jk, k1,i1, j1, bool, z1,z2,j;
         for(jk=1; jk <=nlstate ; jk++){    int first;
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)    double ***freq; /* Frequencies */
             pp[jk] += freq[jk][m][i];    double *pp, **prop;
         }           double pos,posprop, k2, dateintsum=0,k2cpt=0;
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){    char fileresp[FILENAMELENGTH];
           pos += pp[jk];   
           posprop += prop[jk][i];    pp=vector(1,nlstate);
         }    prop=matrix(1,nlstate,iagemin,iagemax+3);
         for(jk=1; jk <=nlstate ; jk++){    strcpy(fileresp,"p");
           if(pos>=1.e-5){    strcat(fileresp,fileres);
             if(first==1)    if((ficresp=fopen(fileresp,"w"))==NULL) {
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);      printf("Problem with prevalence resultfile: %s\n", fileresp);
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
           }else{      exit(0);
             if(first==1)    }
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);    freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);    j1=0;
           }   
           if( i <= iagemax){    j=cptcoveff;
             if(pos>=1.e-5){    if (cptcovn<1) {j=1;ncodemax[1]=1;}
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);  
               /*probs[i][jk][j1]= pp[jk]/pos;*/    first=1;
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/  
             }    for(k1=1; k1<=j;k1++){
             else      for(i1=1; i1<=ncodemax[k1];i1++){
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);        j1++;
           }        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
         }          scanf("%d", i);*/
                 for (i=-5; i<=nlstate+ndeath; i++)  
         for(jk=-1; jk <=nlstate+ndeath; jk++)          for (jk=-5; jk<=nlstate+ndeath; jk++)  
           for(m=-1; m <=nlstate+ndeath; m++)            for(m=iagemin; m <= iagemax+3; m++)
             if(freq[jk][m][i] !=0 ) {              freq[i][jk][m]=0;
             if(first==1)  
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);      for (i=1; i<=nlstate; i++)  
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);        for(m=iagemin; m <= iagemax+3; m++)
             }          prop[i][m]=0;
         if(i <= iagemax)       
           fprintf(ficresp,"\n");        dateintsum=0;
         if(first==1)        k2cpt=0;
           printf("Others in log...\n");        for (i=1; i<=imx; i++) {
         fprintf(ficlog,"\n");          bool=1;
       }          if  (cptcovn>0) {
     }            for (z1=1; z1<=cptcoveff; z1++)
   }              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
   dateintmean=dateintsum/k2cpt;                 bool=0;
            }
   fclose(ficresp);          if (bool==1){
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);            for(m=firstpass; m<=lastpass; m++){
   free_vector(pp,1,nlstate);              k2=anint[m][i]+(mint[m][i]/12.);
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
   /* End of Freq */                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];
 /************ Prevalence ********************/                if (m<lastpass) {
 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)                  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];
   /* 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.                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
   */                  dateintsum=dateintsum+k2;
                    k2cpt++;
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;                }
   double ***freq; /* Frequencies */                /*}*/
   double *pp, **prop;            }
   double pos,posprop;           }
   double  y2; /* in fractional years */        }
   int iagemin, iagemax;         
         /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
   iagemin= (int) agemin;        pstamp(ficresp);
   iagemax= (int) agemax;        if  (cptcovn>0) {
   /*pp=vector(1,nlstate);*/          fprintf(ficresp, "\n#********** Variable ");
   prop=matrix(1,nlstate,iagemin,iagemax+3);           for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/          fprintf(ficresp, "**********\n#");
   j1=0;        }
           for(i=1; i<=nlstate;i++)
   j=cptcoveff;          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}        fprintf(ficresp, "\n");
          
   for(k1=1; k1<=j;k1++){        for(i=iagemin; i <= iagemax+3; i++){
     for(i1=1; i1<=ncodemax[k1];i1++){          if(i==iagemax+3){
       j1++;            fprintf(ficlog,"Total");
                 }else{
       for (i=1; i<=nlstate; i++)              if(first==1){
         for(m=iagemin; m <= iagemax+3; m++)              first=0;
           prop[i][m]=0.0;              printf("See log file for details...\n");
                  }
       for (i=1; i<=imx; i++) { /* Each individual */            fprintf(ficlog,"Age %d", i);
         bool=1;          }
         if  (cptcovn>0) {          for(jk=1; jk <=nlstate ; jk++){
           for (z1=1; z1<=cptcoveff; z1++)             for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])               pp[jk] += freq[jk][m][i];
               bool=0;          }
         }           for(jk=1; jk <=nlstate ; jk++){
         if (bool==1) {             for(m=-1, pos=0; m <=0 ; m++)
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/              pos += freq[jk][m][i];
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */            if(pp[jk]>=1.e-10){
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */              if(first==1){
               if(agev[m][i]==0) agev[m][i]=iagemax+1;              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
               if(agev[m][i]==1) agev[m][i]=iagemax+2;              }
               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);               fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
               if (s[m][i]>0 && s[m][i]<=nlstate) {             }else{
                 /*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]]);*/              if(first==1)
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                 prop[s[m][i]][iagemax+3] += weight[i];               fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
               }             }
             }          }
           } /* end selection of waves */  
         }          for(jk=1; jk <=nlstate ; jk++){
       }            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
       for(i=iagemin; i <= iagemax+3; i++){                pp[jk] += freq[jk][m][i];
                   }      
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {           for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
           posprop += prop[jk][i];             pos += pp[jk];
         }             posprop += prop[jk][i];
           }
         for(jk=1; jk <=nlstate ; jk++){               for(jk=1; jk <=nlstate ; jk++){
           if( i <=  iagemax){             if(pos>=1.e-5){
             if(posprop>=1.e-5){               if(first==1)
               probs[i][jk][j1]= prop[jk][i]/posprop;                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             }               fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
           }             }else{
         }/* end jk */               if(first==1)
       }/* end i */                 printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
     } /* end i1 */              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
   } /* end k1 */            }
               if( i <= iagemax){
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/              if(pos>=1.e-5){
   /*free_vector(pp,1,nlstate);*/                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);                /*probs[i][jk][j1]= pp[jk]/pos;*/
 }  /* End of prevalence */                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
               }
 /************* Waves Concatenation ***************/              else
                 fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 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).          for(jk=-1; jk <=nlstate+ndeath; jk++)
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i            for(m=-1; m <=nlstate+ndeath; m++)
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]              if(freq[jk][m][i] !=0 ) {
      and mw[mi+1][i]. dh depends on stepm.              if(first==1)
      */                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
   int i, mi, m;              }
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;          if(i <= iagemax)
      double sum=0., jmean=0.;*/            fprintf(ficresp,"\n");
   int first;          if(first==1)
   int j, k=0,jk, ju, jl;            printf("Others in log...\n");
   double sum=0.;          fprintf(ficlog,"\n");
   first=0;        }
   jmin=1e+5;      }
   jmax=-1;    }
   jmean=0.;    dateintmean=dateintsum/k2cpt;
   for(i=1; i<=imx; i++){   
     mi=0;    fclose(ficresp);
     m=firstpass;    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
     while(s[m][i] <= nlstate){    free_vector(pp,1,nlstate);
       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
         mw[++mi][i]=m;    /* End of Freq */
       if(m >=lastpass)  }
         break;  
       else  /************ Prevalence ********************/
         m++;  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)
     }/* end while */  {  
     if (s[m][i] > nlstate){    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
       mi++;     /* Death is another wave */       in each health status at the date of interview (if between dateprev1 and dateprev2).
       /* if(mi==0)  never been interviewed correctly before death */       We still use firstpass and lastpass as another selection.
          /* Only death is a correct wave */    */
       mw[mi][i]=m;   
     }    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
     double ***freq; /* Frequencies */
     wav[i]=mi;    double *pp, **prop;
     if(mi==0){    double pos,posprop;
       nbwarn++;    double  y2; /* in fractional years */
       if(first==0){    int iagemin, iagemax;
         printf("Warning! None valid information for:%ld line=%d (skipped) and may be others, see log file\n",num[i],i);  
         first=1;    iagemin= (int) agemin;
       }    iagemax= (int) agemax;
       if(first==1){    /*pp=vector(1,nlstate);*/
         fprintf(ficlog,"Warning! None valid information for:%ld line=%d (skipped)\n",num[i],i);    prop=matrix(1,nlstate,iagemin,iagemax+3);
       }    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
     } /* end mi==0 */    j1=0;
   } /* End individuals */   
     j=cptcoveff;
   for(i=1; i<=imx; i++){    if (cptcovn<1) {j=1;ncodemax[1]=1;}
     for(mi=1; mi<wav[i];mi++){   
       if (stepm <=0)    for(k1=1; k1<=j;k1++){
         dh[mi][i]=1;      for(i1=1; i1<=ncodemax[k1];i1++){
       else{        j1++;
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */       
           if (agedc[i] < 2*AGESUP) {        for (i=1; i<=nlstate; i++)  
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);           for(m=iagemin; m <= iagemax+3; m++)
             if(j==0) j=1;  /* Survives at least one month after exam */            prop[i][m]=0.0;
             else if(j<0){       
               nberr++;        for (i=1; i<=imx; i++) { /* Each individual */
               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]);          bool=1;
               j=1; /* Temporary Dangerous patch */          if  (cptcovn>0) {
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);            for (z1=1; z1<=cptcoveff; z1++)
               fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
               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);                bool=0;
             }          }
             k=k+1;          if (bool==1) {
             if (j >= jmax) jmax=j;            for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
             if (j <= jmin) jmin=j;              y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
             sum=sum+j;              if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/                if(agev[m][i]==0) agev[m][i]=iagemax+1;
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/                if(agev[m][i]==1) agev[m][i]=iagemax+2;
           }                if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m);
         }                if (s[m][i]>0 && s[m][i]<=nlstate) {
         else{                  /*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]]);*/
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));                  prop[s[m][i]][(int)agev[m][i]] += weight[i];
 /*        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]); */                  prop[s[m][i]][iagemax+3] += weight[i];
                 }
           k=k+1;              }
           if (j >= jmax) jmax=j;            } /* end selection of waves */
           else if (j <= jmin)jmin=j;          }
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,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]);*/        for(i=iagemin; i <= iagemax+3; i++){  
           if(j<0){         
             nberr++;          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
             printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);            posprop += prop[jk][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;          for(jk=1; jk <=nlstate ; jk++){    
         }            if( i <=  iagemax){
         jk= j/stepm;              if(posprop>=1.e-5){
         jl= j -jk*stepm;                probs[i][jk][j1]= prop[jk][i]/posprop;
         ju= j -(jk+1)*stepm;              }
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */            }
           if(jl==0){          }/* end jk */
             dh[mi][i]=jk;        }/* end i */
             bh[mi][i]=0;      } /* end i1 */
           }else{ /* We want a negative bias in order to only have interpolation ie    } /* end k1 */
                   * at the price of an extra matrix product in likelihood */   
             dh[mi][i]=jk+1;    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
             bh[mi][i]=ju;    /*free_vector(pp,1,nlstate);*/
           }    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
         }else{  }  /* End of prevalence */
           if(jl <= -ju){  
             dh[mi][i]=jk;  /************* Waves Concatenation ***************/
             bh[mi][i]=jl;       /* bias is positive if real duration  
                                  * is higher than the multiple of stepm and negative otherwise.  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.
           else{       Death is a valid wave (if date is known).
             dh[mi][i]=jk+1;       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
             bh[mi][i]=ju;       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.
           if(dh[mi][i]==0){       */
             dh[mi][i]=1; /* At least one step */  
             bh[mi][i]=ju; /* At least one step */    int i, mi, m;
             /*  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);*/    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
           }       double sum=0., jmean=0.;*/
         } /* end if mle */    int first;
       }    int j, k=0,jk, ju, jl;
     } /* end wave */    double sum=0.;
   }    first=0;
   jmean=sum/k;    jmin=1e+5;
   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);    jmax=-1;
   fprintf(ficlog,"Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);    jmean=0.;
  }    for(i=1; i<=imx; i++){
       mi=0;
 /*********** Tricode ****************************/      m=firstpass;
 void tricode(int *Tvar, int **nbcode, int imx)      while(s[m][i] <= nlstate){
 {        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
             mw[++mi][i]=m;
   int Ndum[20],ij=1, k, j, i, maxncov=19;        if(m >=lastpass)
   int cptcode=0;          break;
   cptcoveff=0;         else
            m++;
   for (k=0; k<maxncov; k++) Ndum[k]=0;      }/* end while */
   for (k=1; k<=7; k++) ncodemax[k]=0;      if (s[m][i] > nlstate){
         mi++;     /* Death is another wave */
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {        /* if(mi==0)  never been interviewed correctly before death */
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum            /* Only death is a correct wave */
                                modality*/         mw[mi][i]=m;
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/      }
       Ndum[ij]++; /*store the modality */  
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/      wav[i]=mi;
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable       if(mi==0){
                                        Tvar[j]. If V=sex and male is 0 and         nbwarn++;
                                        female is 1, then  cptcode=1.*/        if(first==0){
     }          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
           first=1;
     for (i=0; i<=cptcode; i++) {        }
       if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */        if(first==1){
     }          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
         }
     ij=1;       } /* end mi==0 */
     for (i=1; i<=ncodemax[j]; i++) {    } /* End individuals */
       for (k=0; k<= maxncov; k++) {  
         if (Ndum[k] != 0) {    for(i=1; i<=imx; i++){
           nbcode[Tvar[j]][ij]=k;       for(mi=1; mi<wav[i];mi++){
           /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */        if (stepm <=0)
                     dh[mi][i]=1;
           ij++;        else{
         }          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
         if (ij > ncodemax[j]) break;             if (agedc[i] < 2*AGESUP) {
       }                j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
     }               if(j==0) j=1;  /* Survives at least one month after exam */
   }                else if(j<0){
                 nberr++;
  for (k=0; k< maxncov; k++) Ndum[k]=0;                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]);
                 j=1; /* Temporary Dangerous patch */
  for (i=1; i<=ncovmodel-2; i++) {                 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);
    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/                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]);
    ij=Tvar[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);
    Ndum[ij]++;              }
  }              k=k+1;
               if (j >= jmax){
  ij=1;                jmax=j;
  for (i=1; i<= maxncov; i++) {                ijmax=i;
    if((Ndum[i]!=0) && (i<=ncovcol)){              }
      Tvaraff[ij]=i; /*For printing */              if (j <= jmin){
      ij++;                jmin=j;
    }                ijmin=i;
  }              }
                sum=sum+j;
  cptcoveff=ij-1; /*Number of simple covariates*/              /*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);*/
             }
 /*********** Health Expectancies ****************/          }
           else{
 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,char strstart[] )            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
   /*        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]); */
 {  
   /* Health expectancies */            k=k+1;
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;            if (j >= jmax) {
   double age, agelim, hf;              jmax=j;
   double ***p3mat,***varhe;              ijmax=i;
   double **dnewm,**doldm;            }
   double *xp;            else if (j <= jmin){
   double **gp, **gm;              jmin=j;
   double ***gradg, ***trgradg;              ijmin=i;
   int theta;            }
             /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);            /*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]);*/
   xp=vector(1,npar);            if(j<0){
   dnewm=matrix(1,nlstate*nlstate,1,npar);              nberr++;
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);              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]);
   fprintf(ficreseij,"# Local time at start: %s", strstart);            }
   fprintf(ficreseij,"# Health expectancies\n");            sum=sum+j;
   fprintf(ficreseij,"# Age");          }
   for(i=1; i<=nlstate;i++)          jk= j/stepm;
     for(j=1; j<=nlstate;j++)          jl= j -jk*stepm;
       fprintf(ficreseij," %1d-%1d (SE)",i,j);          ju= j -(jk+1)*stepm;
   fprintf(ficreseij,"\n");          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
             if(jl==0){
   if(estepm < stepm){              dh[mi][i]=jk;
     printf ("Problem %d lower than %d\n",estepm, stepm);              bh[mi][i]=0;
   }            }else{ /* We want a negative bias in order to only have interpolation ie
   else  hstepm=estepm;                       * at the price of an extra matrix product in likelihood */
   /* We compute the life expectancy from trapezoids spaced every estepm months              dh[mi][i]=jk+1;
    * This is mainly to measure the difference between two models: for example              bh[mi][i]=ju;
    * 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           }else{
    * progression in between and thus overestimating or underestimating according            if(jl <= -ju){
    * to the curvature of the survival function. If, for the same date, we               dh[mi][i]=jk;
    * estimate the model with stepm=1 month, we can keep estepm to 24 months              bh[mi][i]=jl;       /* bias is positive if real duration
    * to compare the new estimate of Life expectancy with the same linear                                    * is higher than the multiple of stepm and negative otherwise.
    * hypothesis. A more precise result, taking into account a more precise                                   */
    * curvature will be obtained if estepm is as small as stepm. */            }
             else{
   /* For example we decided to compute the life expectancy with the smallest unit */              dh[mi][i]=jk+1;
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.               bh[mi][i]=ju;
      nhstepm is the number of hstepm from age to agelim             }
      nstepm is the number of stepm from age to agelin.             if(dh[mi][i]==0){
      Look at hpijx to understand the reason of that which relies in memory size              dh[mi][i]=1; /* At least one step */
      and note for a fixed period like estepm months */              bh[mi][i]=ju; /* At least one step */
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the              /*  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);*/
      survival function given by stepm (the optimization length). Unfortunately it            }
      means that if the survival funtion is printed only each two years of age and if          } /* end if mle */
      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.      } /* end wave */
   */    }
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     jmean=sum/k;
     printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);
   agelim=AGESUP;    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);
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */   }
     /* nhstepm age range expressed in number of stepm */  
     nstepm=(int) rint((agelim-age)*YEARM/stepm);   /*********** Tricode ****************************/
     /* Typically if 20 years nstepm = 20*12/6=40 stepm */   void tricode(int *Tvar, int **nbcode, int imx)
     /* if (stepm >= YEARM) hstepm=1;*/  {
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */   
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    int Ndum[20],ij=1, k, j, i, maxncov=19;
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);    int cptcode=0;
     gp=matrix(0,nhstepm,1,nlstate*nlstate);    cptcoveff=0;
     gm=matrix(0,nhstepm,1,nlstate*nlstate);   
     for (k=0; k<maxncov; k++) Ndum[k]=0;
     /* Computed by stepm unit matrices, product of hstepm matrices, stored    for (k=1; k<=7; k++) ncodemax[k]=0;
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */  
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);      for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
        for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
                                  modality*/
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */        ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
         Ndum[ij]++; /*store the modality */
     /* Computing  Variances of health expectancies */        /*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
      for(theta=1; theta <=npar; theta++){                                         Tvar[j]. If V=sex and male is 0 and
       for(i=1; i<=npar; i++){                                          female is 1, then  cptcode=1.*/
         xp[i] = x[i] + (i==theta ?delti[theta]:0);      }
       }  
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        for (i=0; i<=cptcode; i++) {
           if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */
       cptj=0;      }
       for(j=1; j<= nlstate; j++){  
         for(i=1; i<=nlstate; i++){      ij=1;
           cptj=cptj+1;      for (i=1; i<=ncodemax[j]; i++) {
           for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){        for (k=0; k<= maxncov; k++) {
             gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;          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; */
       }           
                  ij++;
                }
       for(i=1; i<=npar; i++)           if (ij > ncodemax[j]) break;
         xp[i] = x[i] - (i==theta ?delti[theta]:0);        }  
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        }
           }  
       cptj=0;  
       for(j=1; j<= nlstate; j++){   for (k=0; k< maxncov; k++) Ndum[k]=0;
         for(i=1;i<=nlstate;i++){  
           cptj=cptj+1;   for (i=1; i<=ncovmodel-2; i++) {
           for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
      ij=Tvar[i];
             gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;     Ndum[ij]++;
           }   }
         }  
       }   ij=1;
       for(j=1; j<= nlstate*nlstate; j++)   for (i=1; i<= maxncov; i++) {
         for(h=0; h<=nhstepm-1; h++){     if((Ndum[i]!=0) && (i<=ncovcol)){
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];       Tvaraff[ij]=i; /*For printing */
         }       ij++;
      }      }
       }
 /* End theta */   
    cptcoveff=ij-1; /*Number of simple covariates*/
      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);  }
   
      for(h=0; h<=nhstepm-1; h++)  /*********** Health Expectancies ****************/
       for(j=1; j<=nlstate*nlstate;j++)  
         for(theta=1; theta <=npar; theta++)  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[] )
           trgradg[h][j][theta]=gradg[h][theta][j];  
        {
     /* Health expectancies, no variances */
      for(i=1;i<=nlstate*nlstate;i++)    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
       for(j=1;j<=nlstate*nlstate;j++)    double age, agelim, hf;
         varhe[i][j][(int)age] =0.;    double ***p3mat;
     double eip;
      printf("%d|",(int)age);fflush(stdout);  
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);    pstamp(ficreseij);
      for(h=0;h<=nhstepm-1;h++){    fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
       for(k=0;k<=nhstepm-1;k++){    fprintf(ficreseij,"# Age");
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);    for(i=1; i<=nlstate;i++){
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);      for(j=1; j<=nlstate;j++){
         for(i=1;i<=nlstate*nlstate;i++)        fprintf(ficreseij," e%1d%1d ",i,j);
           for(j=1;j<=nlstate*nlstate;j++)      }
             varhe[i][j][(int)age] += doldm[i][j]*hf*hf;      fprintf(ficreseij," e%1d. ",i);
       }    }
     }    fprintf(ficreseij,"\n");
     /* Computing expectancies */  
     for(i=1; i<=nlstate;i++)   
       for(j=1; j<=nlstate;j++)    if(estepm < stepm){
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){      printf ("Problem %d lower than %d\n",estepm, stepm);
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;    }
               else  hstepm=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]);*/    /* We compute the life expectancy from trapezoids spaced every estepm months
      * 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
      * we are calculating an estimate of the Life Expectancy assuming a linear
     fprintf(ficreseij,"%3.0f",age );     * progression in between and thus overestimating or underestimating according
     cptj=0;     * to the curvature of the survival function. If, for the same date, we
     for(i=1; i<=nlstate;i++)     * estimate the model with stepm=1 month, we can keep estepm to 24 months
       for(j=1; j<=nlstate;j++){     * to compare the new estimate of Life expectancy with the same linear
         cptj++;     * hypothesis. A more precise result, taking into account a more precise
         fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );     * curvature will be obtained if estepm is as small as stepm. */
       }  
     fprintf(ficreseij,"\n");    /* 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.
     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);       nhstepm is the number of hstepm from age to agelim
     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);       nstepm is the number of stepm from age to agelin.
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);       Look at hpijx to understand the reason of that which relies in memory size
     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);       and note for a fixed period like estepm months */
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   }       survival function given by stepm (the optimization length). Unfortunately it
   printf("\n");       means that if the survival funtion is printed only each two years of age and if
   fprintf(ficlog,"\n");       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.
   free_vector(xp,1,npar);    */
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);  
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);    agelim=AGESUP;
 }    /* If stepm=6 months */
       /* Computed by stepm unit matrices, product of hstepm matrices, stored
 /************ Variance ******************/         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 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[])     
 {  /* nhstepm age range expressed in number of stepm */
   /* Variance of health expectancies */    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
   /* double **newm;*/    /* if (stepm >= YEARM) hstepm=1;*/
   double **dnewm,**doldm;    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
   double **dnewmp,**doldmp;    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int i, j, nhstepm, hstepm, h, nstepm ;  
   int k, cptcode;    for (age=bage; age<=fage; age ++){
   double *xp;  
   double **gp, **gm;  /* for var eij */  
   double ***gradg, ***trgradg; /*for var eij */      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
   double **gradgp, **trgradgp; /* for var p point j */     
   double *gpp, *gmp; /* for var p point j */      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */     
   double ***p3mat;      printf("%d|",(int)age);fflush(stdout);
   double age,agelim, hf;      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
   double ***mobaverage;     
   int theta;  
   char digit[4];      /* Computing expectancies */
   char digitp[25];      for(i=1; i<=nlstate;i++)
         for(j=1; j<=nlstate;j++)
   char fileresprobmorprev[FILENAMELENGTH];          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
             eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
   if(popbased==1){           
     if(mobilav!=0)            /*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]);*/
       strcpy(digitp,"-populbased-mobilav-");  
     else strcpy(digitp,"-populbased-nomobil-");          }
   }     
   else       fprintf(ficreseij,"%3.0f",age );
     strcpy(digitp,"-stablbased-");      for(i=1; i<=nlstate;i++){
         eip=0;
   if (mobilav!=0) {        for(j=1; j<=nlstate;j++){
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          eip +=eij[i][j][(int)age];
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);        }
       printf(" Error in movingaverage mobilav=%d\n",mobilav);        fprintf(ficreseij,"%9.4f", eip );
     }      }
   }      fprintf(ficreseij,"\n");
      
   strcpy(fileresprobmorprev,"prmorprev");     }
   sprintf(digit,"%-d",ij);    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/    printf("\n");
   strcat(fileresprobmorprev,digit); /* Tvar to be done */    fprintf(ficlog,"\n");
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */   
   strcat(fileresprobmorprev,fileres);  }
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {  
     printf("Problem with resultfile: %s\n", fileresprobmorprev);  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[] )
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);  
   }  {
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    /* Covariances of health expectancies eij and of total life expectancies according
       to initial status i, ei. .
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    */
   fprintf(ficresprobmorprev, "#Local time at start: %s", strstart);    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
   fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);    double age, agelim, hf;
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);    double ***p3matp, ***p3matm, ***varhe;
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){    double **dnewm,**doldm;
     fprintf(ficresprobmorprev," p.%-d SE",j);    double *xp, *xm;
     for(i=1; i<=nlstate;i++)    double **gp, **gm;
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);    double ***gradg, ***trgradg;
   }      int theta;
   fprintf(ficresprobmorprev,"\n");  
   fprintf(ficgp,"\n# Routine varevsij");    double eip, vip;
   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/  
   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");    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);    xp=vector(1,npar);
 /*   } */    xm=vector(1,npar);
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    dnewm=matrix(1,nlstate*nlstate,1,npar);
  fprintf(ficresvij, "#Local time at start: %s", strstart);    doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
   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");    pstamp(ficresstdeij);
   for(i=1; i<=nlstate;i++)    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
     for(j=1; j<=nlstate;j++)    fprintf(ficresstdeij,"# Age");
       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);    for(i=1; i<=nlstate;i++){
   fprintf(ficresvij,"\n");      for(j=1; j<=nlstate;j++)
         fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
   xp=vector(1,npar);      fprintf(ficresstdeij," e%1d. ",i);
   dnewm=matrix(1,nlstate,1,npar);    }
   doldm=matrix(1,nlstate,1,nlstate);    fprintf(ficresstdeij,"\n");
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);  
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    pstamp(ficrescveij);
     fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);    fprintf(ficrescveij,"# Age");
   gpp=vector(nlstate+1,nlstate+ndeath);    for(i=1; i<=nlstate;i++)
   gmp=vector(nlstate+1,nlstate+ndeath);      for(j=1; j<=nlstate;j++){
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/        cptj= (j-1)*nlstate+i;
           for(i2=1; i2<=nlstate;i2++)
   if(estepm < stepm){          for(j2=1; j2<=nlstate;j2++){
     printf ("Problem %d lower than %d\n",estepm, stepm);            cptj2= (j2-1)*nlstate+i2;
   }            if(cptj2 <= cptj)
   else  hstepm=estepm;                 fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
   /* 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     fprintf(ficrescveij,"\n");
      nstepm is the number of stepm from age to agelin.    
      Look at hpijx to understand the reason of that which relies in memory size    if(estepm < stepm){
      and note for a fixed period like k years */      printf ("Problem %d lower than %d\n",estepm, stepm);
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    }
      survival function given by stepm (the optimization length). Unfortunately it    else  hstepm=estepm;  
      means that if the survival funtion is printed every two years of age and if    /* We compute the life expectancy from trapezoids spaced every estepm months
      you sum them up and add 1 year (area under the trapezoids) you won't get the same      * This is mainly to measure the difference between two models: for example
      results. So we changed our mind and took the option of the best precision.     * 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
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */      * progression in between and thus overestimating or underestimating according
   agelim = AGESUP;     * to the curvature of the survival function. If, for the same date, we
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */     * estimate the model with stepm=1 month, we can keep estepm to 24 months
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */      * to compare the new estimate of Life expectancy with the same linear
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */     * hypothesis. A more precise result, taking into account a more precise
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);     * curvature will be obtained if estepm is as small as stepm. */
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);  
     gp=matrix(0,nhstepm,1,nlstate);    /* For example we decided to compute the life expectancy with the smallest unit */
     gm=matrix(0,nhstepm,1,nlstate);    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
        nhstepm is the number of hstepm from age to agelim
        nstepm is the number of stepm from age to agelin.
     for(theta=1; theta <=npar; theta++){       Look at hpijx to understand the reason of that which relies in memory size
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/       and note for a fixed period like estepm months */
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
       }       survival function given by stepm (the optimization length). Unfortunately it
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);         means that if the survival funtion is printed only each two years of age and if
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);       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.
       if (popbased==1) {    */
         if(mobilav ==0){    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
           for(i=1; i<=nlstate;i++)  
             prlim[i][i]=probs[(int)age][i][ij];    /* If stepm=6 months */
         }else{ /* mobilav */     /* nhstepm age range expressed in number of stepm */
           for(i=1; i<=nlstate;i++)    agelim=AGESUP;
             prlim[i][i]=mobaverage[(int)age][i][ij];    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
         }    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
       }    /* if (stepm >= YEARM) hstepm=1;*/
       nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       for(j=1; j<= nlstate; j++){   
         for(h=0; h<=nhstepm; h++){    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];    gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
         }    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
       }    gp=matrix(0,nhstepm,1,nlstate*nlstate);
       /* This for computing probability of death (h=1 means    gm=matrix(0,nhstepm,1,nlstate*nlstate);
          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++){      /* Computed by stepm unit matrices, product of hstepm matrices, stored
         for(i=1,gpp[j]=0.; i<= nlstate; i++)         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
           gpp[j] += prlim[i][i]*p3mat[i][j][1];   
       }          hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       /* end probability of death */  
       /* Computing  Variances of health expectancies */
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
         xp[i] = x[i] - (i==theta ?delti[theta]:0);         decrease memory allocation */
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        for(theta=1; theta <=npar; theta++){
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);        for(i=1; i<=npar; i++){
            xp[i] = x[i] + (i==theta ?delti[theta]:0);
       if (popbased==1) {          xm[i] = x[i] - (i==theta ?delti[theta]:0);
         if(mobilav ==0){        }
           for(i=1; i<=nlstate;i++)        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
             prlim[i][i]=probs[(int)age][i][ij];        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
         }else{ /* mobilav */    
           for(i=1; i<=nlstate;i++)        for(j=1; j<= nlstate; j++){
             prlim[i][i]=mobaverage[(int)age][i][ij];          for(i=1; i<=nlstate; i++){
         }            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.;
       for(j=1; j<= nlstate; j++){            }
         for(h=0; h<=nhstepm; h++){          }
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)        }
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];       
         }        for(ij=1; ij<= nlstate*nlstate; ij++)
       }          for(h=0; h<=nhstepm-1; h++){
       /* This for computing probability of death (h=1 means            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
          computed over hstepm matrices product = hstepm*stepm months)           }
          as a weighted average of prlim.      }/* End theta */
       */     
       for(j=nlstate+1;j<=nlstate+ndeath;j++){     
         for(i=1,gmp[j]=0.; i<= nlstate; i++)      for(h=0; h<=nhstepm-1; h++)
          gmp[j] += prlim[i][i]*p3mat[i][j][1];        for(j=1; j<=nlstate*nlstate;j++)
       }              for(theta=1; theta <=npar; theta++)
       /* end probability of death */            trgradg[h][j][theta]=gradg[h][theta][j];
      
       for(j=1; j<= nlstate; j++) /* vareij */  
         for(h=0; h<=nhstepm; h++){       for(ij=1;ij<=nlstate*nlstate;ij++)
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];        for(ji=1;ji<=nlstate*nlstate;ji++)
         }          varhe[ij][ji][(int)age] =0.;
   
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */       printf("%d|",(int)age);fflush(stdout);
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
       }       for(h=0;h<=nhstepm-1;h++){
         for(k=0;k<=nhstepm-1;k++){
     } /* End theta */          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]);
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */          for(ij=1;ij<=nlstate*nlstate;ij++)
             for(ji=1;ji<=nlstate*nlstate;ji++)
     for(h=0; h<=nhstepm; h++) /* veij */              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
       for(j=1; j<=nlstate;j++)        }
         for(theta=1; theta <=npar; theta++)      }
           trgradg[h][j][theta]=gradg[h][theta][j];  
       /* Computing expectancies */
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
       for(theta=1; theta <=npar; theta++)      for(i=1; i<=nlstate;i++)
         trgradgp[j][theta]=gradgp[theta][j];        for(j=1; j<=nlstate;j++)
             for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
             eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */           
     for(i=1;i<=nlstate;i++)            /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
       for(j=1;j<=nlstate;j++)  
         vareij[i][j][(int)age] =0.;          }
   
     for(h=0;h<=nhstepm;h++){      fprintf(ficresstdeij,"%3.0f",age );
       for(k=0;k<=nhstepm;k++){      for(i=1; i<=nlstate;i++){
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);        eip=0.;
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);        vip=0.;
         for(i=1;i<=nlstate;i++)        for(j=1; j<=nlstate;j++){
           for(j=1;j<=nlstate;j++)          eip += eij[i][j][(int)age];
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;          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];
     }          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
           }
     /* pptj */        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
     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);      fprintf(ficresstdeij,"\n");
     for(j=nlstate+1;j<=nlstate+ndeath;j++)  
       for(i=nlstate+1;i<=nlstate+ndeath;i++)      fprintf(ficrescveij,"%3.0f",age );
         varppt[j][i]=doldmp[j][i];      for(i=1; i<=nlstate;i++)
     /* end ppptj */        for(j=1; j<=nlstate;j++){
     /*  x centered again */          cptj= (j-1)*nlstate+i;
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);            for(i2=1; i2<=nlstate;i2++)
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);            for(j2=1; j2<=nlstate;j2++){
                cptj2= (j2-1)*nlstate+i2;
     if (popbased==1) {              if(cptj2 <= cptj)
       if(mobilav ==0){                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
         for(i=1; i<=nlstate;i++)            }
           prlim[i][i]=probs[(int)age][i][ij];        }
       }else{ /* mobilav */       fprintf(ficrescveij,"\n");
         for(i=1; i<=nlstate;i++)     
           prlim[i][i]=mobaverage[(int)age][i][ij];    }
       }    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
     }    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                  free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
     /* This for computing probability of death (h=1 means    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
        computed over hstepm (estepm) matrices product = hstepm*stepm months)     free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        as a weighted average of prlim.    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     */    printf("\n");
     for(j=nlstate+1;j<=nlstate+ndeath;j++){    fprintf(ficlog,"\n");
       for(i=1,gmp[j]=0.;i<= nlstate; i++)   
         gmp[j] += prlim[i][i]*p3mat[i][j][1];     free_vector(xm,1,npar);
     }        free_vector(xp,1,npar);
     /* end probability of death */    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
     free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
     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;i++){  /************ Variance ******************/
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);  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[])
       }  {
     }     /* Variance of health expectancies */
     fprintf(ficresprobmorprev,"\n");    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
     /* double **newm;*/
     fprintf(ficresvij,"%.0f ",age );    double **dnewm,**doldm;
     for(i=1; i<=nlstate;i++)    double **dnewmp,**doldmp;
       for(j=1; j<=nlstate;j++){    int i, j, nhstepm, hstepm, h, nstepm ;
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);    int k, cptcode;
       }    double *xp;
     fprintf(ficresvij,"\n");    double **gp, **gm;  /* for var eij */
     free_matrix(gp,0,nhstepm,1,nlstate);    double ***gradg, ***trgradg; /*for var eij */
     free_matrix(gm,0,nhstepm,1,nlstate);    double **gradgp, **trgradgp; /* for var p point j */
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);    double *gpp, *gmp; /* for var p point j */
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    double ***p3mat;
   } /* End age */    double age,agelim, hf;
   free_vector(gpp,nlstate+1,nlstate+ndeath);    double ***mobaverage;
   free_vector(gmp,nlstate+1,nlstate+ndeath);    int theta;
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);    char digit[4];
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/    char digitp[25];
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");  
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */    char fileresprobmorprev[FILENAMELENGTH];
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");  
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */    if(popbased==1){
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */      if(mobilav!=0)
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */        strcpy(digitp,"-populbased-mobilav-");
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));      else strcpy(digitp,"-populbased-nomobil-");
   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));    else
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));      strcpy(digitp,"-stablbased-");
   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);  
   /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);    if (mobilav!=0) {
 */      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
         printf(" Error in movingaverage mobilav=%d\n",mobilav);
   free_vector(xp,1,npar);      }
   free_matrix(doldm,1,nlstate,1,nlstate);    }
   free_matrix(dnewm,1,nlstate,1,npar);  
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    strcpy(fileresprobmorprev,"prmorprev");
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);    sprintf(digit,"%-d",ij);
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    strcat(fileresprobmorprev,digit); /* Tvar to be done */
   fclose(ficresprobmorprev);    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
   fflush(ficgp);    strcat(fileresprobmorprev,fileres);
   fflush(fichtm);     if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 }  /* end varevsij */      printf("Problem with resultfile: %s\n", fileresprobmorprev);
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 /************ Variance of prevlim ******************/    }
 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[])    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 {   
   /* Variance of prevalence limit */    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/    pstamp(ficresprobmorprev);
   double **newm;    fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);
   double **dnewm,**doldm;    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
   int i, j, nhstepm, hstepm;    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   int k, cptcode;      fprintf(ficresprobmorprev," p.%-d SE",j);
   double *xp;      for(i=1; i<=nlstate;i++)
   double *gp, *gm;        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
   double **gradg, **trgradg;    }  
   double age,agelim;    fprintf(ficresprobmorprev,"\n");
   int theta;    fprintf(ficgp,"\n# Routine varevsij");
   fprintf(ficresvpl, "#Local time at start: %s", strstart);     /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");    fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");
   fprintf(ficresvpl,"# Age");    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
   for(i=1; i<=nlstate;i++)  /*   } */
       fprintf(ficresvpl," %1d-%1d",i,i);    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   fprintf(ficresvpl,"\n");    pstamp(ficresvij);
     fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
   xp=vector(1,npar);    if(popbased==1)
   dnewm=matrix(1,nlstate,1,npar);      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
   doldm=matrix(1,nlstate,1,nlstate);    else
         fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
   hstepm=1*YEARM; /* Every year of age */    fprintf(ficresvij,"# Age");
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */     for(i=1; i<=nlstate;i++)
   agelim = AGESUP;      for(j=1; j<=nlstate;j++)
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     fprintf(ficresvij,"\n");
     if (stepm >= YEARM) hstepm=1;  
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */    xp=vector(1,npar);
     gradg=matrix(1,npar,1,nlstate);    dnewm=matrix(1,nlstate,1,npar);
     gp=vector(1,nlstate);    doldm=matrix(1,nlstate,1,nlstate);
     gm=vector(1,nlstate);    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
     doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
     for(theta=1; theta <=npar; theta++){  
       for(i=1; i<=npar; i++){ /* Computes gradient */    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    gpp=vector(nlstate+1,nlstate+ndeath);
       }    gmp=vector(nlstate+1,nlstate+ndeath);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
       for(i=1;i<=nlstate;i++)   
         gp[i] = prlim[i][i];    if(estepm < stepm){
           printf ("Problem %d lower than %d\n",estepm, stepm);
       for(i=1; i<=npar; i++) /* Computes gradient */    }
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    else  hstepm=estepm;  
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    /* For example we decided to compute the life expectancy with the smallest unit */
       for(i=1;i<=nlstate;i++)    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
         gm[i] = prlim[i][i];       nhstepm is the number of hstepm from age to agelim
        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
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];       and note for a fixed period like k years */
     } /* End theta */    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
        survival function given by stepm (the optimization length). Unfortunately it
     trgradg =matrix(1,nlstate,1,npar);       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
     for(j=1; j<=nlstate;j++)       results. So we changed our mind and took the option of the best precision.
       for(theta=1; theta <=npar; theta++)    */
         trgradg[j][theta]=gradg[theta][j];    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
     agelim = AGESUP;
     for(i=1;i<=nlstate;i++)    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
       varpl[i][(int)age] =0.;      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     for(i=1;i<=nlstate;i++)      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */      gp=matrix(0,nhstepm,1,nlstate);
       gm=matrix(0,nhstepm,1,nlstate);
     fprintf(ficresvpl,"%.0f ",age );  
     for(i=1; i<=nlstate;i++)  
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));      for(theta=1; theta <=npar; theta++){
     fprintf(ficresvpl,"\n");        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
     free_vector(gp,1,nlstate);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
     free_vector(gm,1,nlstate);        }
     free_matrix(gradg,1,npar,1,nlstate);        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
     free_matrix(trgradg,1,nlstate,1,npar);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   } /* End age */  
         if (popbased==1) {
   free_vector(xp,1,npar);          if(mobilav ==0){
   free_matrix(doldm,1,nlstate,1,npar);            for(i=1; i<=nlstate;i++)
   free_matrix(dnewm,1,nlstate,1,nlstate);              prlim[i][i]=probs[(int)age][i][ij];
           }else{ /* mobilav */
 }            for(i=1; i<=nlstate;i++)
               prlim[i][i]=mobaverage[(int)age][i][ij];
 /************ Variance of one-step probabilities  ******************/          }
 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[])        }
 {   
   int i, j=0,  i1, k1, l1, t, tj;        for(j=1; j<= nlstate; j++){
   int k2, l2, j1,  z1;          for(h=0; h<=nhstepm; h++){
   int k=0,l, cptcode;            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
   int first=1, first1;              gp[h][j] += prlim[i][i]*p3mat[i][j][h];
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;          }
   double **dnewm,**doldm;        }
   double *xp;        /* This for computing probability of death (h=1 means
   double *gp, *gm;           computed over hstepm matrices product = hstepm*stepm months)
   double **gradg, **trgradg;           as a weighted average of prlim.
   double **mu;        */
   double age,agelim, cov[NCOVMAX];        for(j=nlstate+1;j<=nlstate+ndeath;j++){
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */          for(i=1,gpp[j]=0.; i<= nlstate; i++)
   int theta;            gpp[j] += prlim[i][i]*p3mat[i][j][1];
   char fileresprob[FILENAMELENGTH];        }    
   char fileresprobcov[FILENAMELENGTH];        /* end probability of death */
   char fileresprobcor[FILENAMELENGTH];  
         for(i=1; i<=npar; i++) /* Computes gradient x - delta */
   double ***varpij;          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
   strcpy(fileresprob,"prob");         prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   strcat(fileresprob,fileres);   
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {        if (popbased==1) {
     printf("Problem with resultfile: %s\n", fileresprob);          if(mobilav ==0){
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);            for(i=1; i<=nlstate;i++)
   }              prlim[i][i]=probs[(int)age][i][ij];
   strcpy(fileresprobcov,"probcov");           }else{ /* mobilav */
   strcat(fileresprobcov,fileres);            for(i=1; i<=nlstate;i++)
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {              prlim[i][i]=mobaverage[(int)age][i][ij];
     printf("Problem with resultfile: %s\n", fileresprobcov);          }
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);        }
   }  
   strcpy(fileresprobcor,"probcor");         for(j=1; j<= nlstate; j++){
   strcat(fileresprobcor,fileres);          for(h=0; h<=nhstepm; h++){
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
     printf("Problem with resultfile: %s\n", fileresprobcor);              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);          }
   }        }
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);        /* This for computing probability of death (h=1 means
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);           computed over hstepm matrices product = hstepm*stepm months)
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);           as a weighted average of prlim.
   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);        for(j=nlstate+1;j<=nlstate+ndeath;j++){
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);          for(i=1,gmp[j]=0.; i<= nlstate; i++)
   fprintf(ficresprob, "#Local time at start: %s", strstart);           gmp[j] += prlim[i][i]*p3mat[i][j][1];
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");        }    
   fprintf(ficresprob,"# Age");        /* end probability of death */
   fprintf(ficresprobcov, "#Local time at start: %s", strstart);  
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");        for(j=1; j<= nlstate; j++) /* vareij */
   fprintf(ficresprobcov,"# Age");          for(h=0; h<=nhstepm; h++){
   fprintf(ficresprobcor, "#Local time at start: %s", strstart);            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");          }
   fprintf(ficresprobcov,"# Age");  
         for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
           gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
   for(i=1; i<=nlstate;i++)        }
     for(j=1; j<=(nlstate+ndeath);j++){  
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);      } /* End theta */
       fprintf(ficresprobcov," p%1d-%1d ",i,j);  
       fprintf(ficresprobcor," p%1d-%1d ",i,j);      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
     }    
  /* fprintf(ficresprob,"\n");      for(h=0; h<=nhstepm; h++) /* veij */
   fprintf(ficresprobcov,"\n");        for(j=1; j<=nlstate;j++)
   fprintf(ficresprobcor,"\n");          for(theta=1; theta <=npar; theta++)
  */            trgradg[h][j][theta]=gradg[h][theta][j];
  xp=vector(1,npar);  
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));        for(theta=1; theta <=npar; theta++)
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);          trgradgp[j][theta]=gradgp[theta][j];
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);   
   first=1;  
   fprintf(ficgp,"\n# Routine varprob");      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
   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");        for(j=1;j<=nlstate;j++)
           vareij[i][j][(int)age] =0.;
   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\      for(h=0;h<=nhstepm;h++){
   file %s<br>\n",optionfilehtmcov);        for(k=0;k<=nhstepm;k++){
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 and drawn. It helps understanding how is the covariance between two incidences.\          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");          for(i=1;i<=nlstate;i++)
   fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \            for(j=1;j<=nlstate;j++)
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \              vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \        }
 standard deviations wide on each axis. <br>\      }
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\   
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\      /* pptj */
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");      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);
   cov[1]=1;      for(j=nlstate+1;j<=nlstate+ndeath;j++)
   tj=cptcoveff;        for(i=nlstate+1;i<=nlstate+ndeath;i++)
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}          varppt[j][i]=doldmp[j][i];
   j1=0;      /* end ppptj */
   for(t=1; t<=tj;t++){      /*  x centered again */
     for(i1=1; i1<=ncodemax[t];i1++){       hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
       j1++;      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
       if  (cptcovn>0) {   
         fprintf(ficresprob, "\n#********** Variable ");       if (popbased==1) {
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);        if(mobilav ==0){
         fprintf(ficresprob, "**********\n#\n");          for(i=1; i<=nlstate;i++)
         fprintf(ficresprobcov, "\n#********** Variable ");             prlim[i][i]=probs[(int)age][i][ij];
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);        }else{ /* mobilav */
         fprintf(ficresprobcov, "**********\n#\n");          for(i=1; i<=nlstate;i++)
                     prlim[i][i]=mobaverage[(int)age][i][ij];
         fprintf(ficgp, "\n#********** Variable ");         }
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      }
         fprintf(ficgp, "**********\n#\n");               
               /* This for computing probability of death (h=1 means
                  computed over hstepm (estepm) matrices product = hstepm*stepm months)
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");          as a weighted average of prlim.
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      */
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                 for(i=1,gmp[j]=0.;i<= nlstate; i++)
         fprintf(ficresprobcor, "\n#********** Variable ");              gmp[j] += prlim[i][i]*p3mat[i][j][1];
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      }    
         fprintf(ficresprobcor, "**********\n#");          /* end probability of death */
       }  
             fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
       for (age=bage; age<=fage; age ++){       for(j=nlstate+1; j<=(nlstate+ndeath);j++){
         cov[2]=age;        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
         for (k=1; k<=cptcovn;k++) {        for(i=1; i<=nlstate;i++){
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
         }        }
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];      }
         for (k=1; k<=cptcovprod;k++)      fprintf(ficresprobmorprev,"\n");
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];  
               fprintf(ficresvij,"%.0f ",age );
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));      for(i=1; i<=nlstate;i++)
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);        for(j=1; j<=nlstate;j++){
         gp=vector(1,(nlstate)*(nlstate+ndeath));          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
         gm=vector(1,(nlstate)*(nlstate+ndeath));        }
           fprintf(ficresvij,"\n");
         for(theta=1; theta <=npar; theta++){      free_matrix(gp,0,nhstepm,1,nlstate);
           for(i=1; i<=npar; i++)      free_matrix(gm,0,nhstepm,1,nlstate);
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                 free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
           pmij(pmmij,cov,ncovmodel,xp,nlstate);      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
               } /* End age */
           k=0;    free_vector(gpp,nlstate+1,nlstate+ndeath);
           for(i=1; i<= (nlstate); i++){    free_vector(gmp,nlstate+1,nlstate+ndeath);
             for(j=1; j<=(nlstate+ndeath);j++){    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
               k=k+1;    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
               gp[k]=pmmij[i][j];    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
             }    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
           }    fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
             /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
           for(i=1; i<=npar; i++)  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);  /*   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));
           pmij(pmmij,cov,ncovmodel,xp,nlstate);    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
           k=0;    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
           for(i=1; i<=(nlstate); i++){    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
             for(j=1; j<=(nlstate+ndeath);j++){    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);
               k=k+1;    /*  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);
               gm[k]=pmmij[i][j];  */
             }  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
           }    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
        
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)     free_vector(xp,1,npar);
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];      free_matrix(doldm,1,nlstate,1,nlstate);
         }    free_matrix(dnewm,1,nlstate,1,npar);
     free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
           for(theta=1; theta <=npar; theta++)    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
             trgradg[j][theta]=gradg[theta][j];    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
             fclose(ficresprobmorprev);
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);     fflush(ficgp);
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);    fflush(fichtm);
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));  }  /* end varevsij */
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));  
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);  /************ Variance of prevlim ******************/
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);  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[])
   {
         pmij(pmmij,cov,ncovmodel,x,nlstate);    /* Variance of prevalence limit */
             /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
         k=0;    double **newm;
         for(i=1; i<=(nlstate); i++){    double **dnewm,**doldm;
           for(j=1; j<=(nlstate+ndeath);j++){    int i, j, nhstepm, hstepm;
             k=k+1;    int k, cptcode;
             mu[k][(int) age]=pmmij[i][j];    double *xp;
           }    double *gp, *gm;
         }    double **gradg, **trgradg;
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)    double age,agelim;
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)    int theta;
             varpij[i][j][(int)age] = doldm[i][j];   
     pstamp(ficresvpl);
         /*printf("\n%d ",(int)age);    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){    fprintf(ficresvpl,"# Age");
           printf("%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(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));        fprintf(ficresvpl," %1d-%1d",i,i);
           }*/    fprintf(ficresvpl,"\n");
   
         fprintf(ficresprob,"\n%d ",(int)age);    xp=vector(1,npar);
         fprintf(ficresprobcov,"\n%d ",(int)age);    dnewm=matrix(1,nlstate,1,npar);
         fprintf(ficresprobcor,"\n%d ",(int)age);    doldm=matrix(1,nlstate,1,nlstate);
    
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)    hstepm=1*YEARM; /* Every year of age */
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){    agelim = AGESUP;
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
         }      if (stepm >= YEARM) hstepm=1;
         i=0;      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
         for (k=1; k<=(nlstate);k++){      gradg=matrix(1,npar,1,nlstate);
           for (l=1; l<=(nlstate+ndeath);l++){       gp=vector(1,nlstate);
             i=i++;      gm=vector(1,nlstate);
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);  
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);      for(theta=1; theta <=npar; theta++){
             for (j=1; j<=i;j++){        for(i=1; i<=npar; i++){ /* Computes gradient */
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));        }
             }        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
           }        for(i=1;i<=nlstate;i++)
         }/* end of loop for state */          gp[i] = prlim[i][i];
       } /* end of loop for age */     
         for(i=1; i<=npar; i++) /* Computes gradient */
       /* Confidence intervalle of pij  */          xp[i] = x[i] - (i==theta ?delti[theta]:0);
       /*        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         fprintf(ficgp,"\nset noparametric;unset label");        for(i=1;i<=nlstate;i++)
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");          gm[i] = prlim[i][i];
         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);        for(i=1;i<=nlstate;i++)
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);      } /* End theta */
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);  
       */      trgradg =matrix(1,nlstate,1,npar);
   
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/      for(j=1; j<=nlstate;j++)
       first1=1;        for(theta=1; theta <=npar; theta++)
       for (k2=1; k2<=(nlstate);k2++){          trgradg[j][theta]=gradg[theta][j];
         for (l2=1; l2<=(nlstate+ndeath);l2++){   
           if(l2==k2) continue;      for(i=1;i<=nlstate;i++)
           j=(k2-1)*(nlstate+ndeath)+l2;        varpl[i][(int)age] =0.;
           for (k1=1; k1<=(nlstate);k1++){      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
             for (l1=1; l1<=(nlstate+ndeath);l1++){       matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
               if(l1==k1) continue;      for(i=1;i<=nlstate;i++)
               i=(k1-1)*(nlstate+ndeath)+l1;        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
               if(i<=j) continue;  
               for (age=bage; age<=fage; age ++){       fprintf(ficresvpl,"%.0f ",age );
                 if ((int)age %5==0){      for(i=1; i<=nlstate;i++)
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;      fprintf(ficresvpl,"\n");
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;      free_vector(gp,1,nlstate);
                   mu1=mu[i][(int) age]/stepm*YEARM ;      free_vector(gm,1,nlstate);
                   mu2=mu[j][(int) age]/stepm*YEARM;      free_matrix(gradg,1,npar,1,nlstate);
                   c12=cv12/sqrt(v1*v2);      free_matrix(trgradg,1,nlstate,1,npar);
                   /* Computing eigen value of matrix of covariance */    } /* End age */
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;    free_vector(xp,1,npar);
                   /* Eigen vectors */    free_matrix(doldm,1,nlstate,1,npar);
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));    free_matrix(dnewm,1,nlstate,1,nlstate);
                   /*v21=sqrt(1.-v11*v11); *//* error */  
                   v21=(lc1-v1)/cv12*v11;  }
                   v12=-v21;  
                   v22=v11;  /************ Variance of one-step probabilities  ******************/
                   tnalp=v21/v11;  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[])
                   if(first1==1){  {
                     first1=0;    int i, j=0,  i1, k1, l1, t, tj;
                     printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);    int k2, l2, j1,  z1;
                   }    int k=0,l, cptcode;
                   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);    int first=1, first1;
                   /*printf(fignu*/    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */    double **dnewm,**doldm;
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */    double *xp;
                   if(first==1){    double *gp, *gm;
                     first=0;    double **gradg, **trgradg;
                     fprintf(ficgp,"\nset parametric;unset label");    double **mu;
                     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);    double age,agelim, cov[NCOVMAX];
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\    int theta;
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\    char fileresprob[FILENAMELENGTH];
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\    char fileresprobcov[FILENAMELENGTH];
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\    char fileresprobcor[FILENAMELENGTH];
                             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);    double ***varpij;
                     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);    strcpy(fileresprob,"prob");
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);    strcat(fileresprob,fileres);
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                     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",\      printf("Problem with resultfile: %s\n", fileresprob);
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    }
                   }else{    strcpy(fileresprobcov,"probcov");
                     first=0;    strcat(fileresprobcov,fileres);
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);      printf("Problem with resultfile: %s\n", fileresprobcov);
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                     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),\    strcpy(fileresprobcor,"probcor");
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    strcat(fileresprobcor,fileres);
                   }/* if first */    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                 } /* age mod 5 */      printf("Problem with resultfile: %s\n", fileresprobcor);
               } /* end loop age */      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    }
               first=1;    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
             } /*l12 */    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
           } /* k12 */    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
         } /*l1 */    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
       }/* k1 */    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
     } /* loop covariates */    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   }    pstamp(ficresprob);
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);    fprintf(ficresprob,"# Age");
   free_vector(xp,1,npar);    pstamp(ficresprobcov);
   fclose(ficresprob);    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
   fclose(ficresprobcov);    fprintf(ficresprobcov,"# Age");
   fclose(ficresprobcor);    pstamp(ficresprobcor);
   fflush(ficgp);    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
   fflush(fichtmcov);    fprintf(ficresprobcor,"# Age");
 }  
   
     for(i=1; i<=nlstate;i++)
 /******************* Printing html file ***********/      for(j=1; j<=(nlstate+ndeath);j++){
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   int lastpass, int stepm, int weightopt, char model[],\        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   int popforecast, int estepm ,\      }  
                   double jprev1, double mprev1,double anprev1, \   /* fprintf(ficresprob,"\n");
                   double jprev2, double mprev2,double anprev2){    fprintf(ficresprobcov,"\n");
   int jj1, k1, i1, cpt;    fprintf(ficresprobcor,"\n");
    */
    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \   xp=vector(1,npar);
    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 </ul>");    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));    first=1;
    fprintf(fichtm,"\    fprintf(ficgp,"\n# Routine varprob");
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));    fprintf(fichtm,"\n");
    fprintf(fichtm,"\  
  - Stable prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
    fprintf(fichtm,"\    file %s<br>\n",optionfilehtmcov);
  - Life expectancies by age and initial health status (estepm=%2d months): \    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
    <a href=\"%s\">%s</a> <br>\n</li>",  and drawn. It helps understanding how is the covariance between two incidences.\
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
     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<ul><li><b>Graphs</b></li><p>");  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 \
  m=cptcoveff;  standard deviations wide on each axis. <br>\
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
    and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
  jj1=0;  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
  for(k1=1; k1<=m;k1++){  
    for(i1=1; i1<=ncodemax[k1];i1++){    cov[1]=1;
      jj1++;    tj=cptcoveff;
      if (cptcovn > 0) {    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");    j1=0;
        for (cpt=1; cpt<=cptcoveff;cpt++)     for(t=1; t<=tj;t++){
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);      for(i1=1; i1<=ncodemax[t];i1++){
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");        j1++;
      }        if  (cptcovn>0) {
      /* Pij */          fprintf(ficresprob, "\n#********** Variable ");
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: %s%d1.png<br> \          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);               fprintf(ficresprob, "**********\n#\n");
      /* Quasi-incidences */          fprintf(ficresprobcov, "\n#********** Variable ");
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: %s%d2.png<br> \          fprintf(ficresprobcov, "**********\n#\n");
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);          
        /* Stable prevalence in each health state */          fprintf(ficgp, "\n#********** Variable ");
        for(cpt=1; cpt<nlstate;cpt++){          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
          fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br> \          fprintf(ficgp, "**********\n#\n");
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);         
        }         
      for(cpt=1; cpt<=nlstate;cpt++) {          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): %s%d%d.png <br> \          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
      }         
    } /* end i1 */          fprintf(ficresprobcor, "\n#********** Variable ");    
  }/* End k1 */          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
  fprintf(fichtm,"</ul>");          fprintf(ficresprobcor, "**********\n#");    
         }
        
  fprintf(fichtm,"\        for (age=bage; age<=fage; age ++){
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\          cov[2]=age;
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);          for (k=1; k<=cptcovn;k++) {
             cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",          }
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
  fprintf(fichtm,"\          for (k=1; k<=cptcovprod;k++)
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",            cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));         
           gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
  fprintf(fichtm,"\          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",          gp=vector(1,(nlstate)*(nlstate+ndeath));
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));          gm=vector(1,(nlstate)*(nlstate+ndeath));
  fprintf(fichtm,"\     
  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"%s\">%s</a><br>\n",          for(theta=1; theta <=npar; theta++){
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));            for(i=1; i<=npar; i++)
  fprintf(fichtm,"\              xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
  - Health expectancies with their variances (no covariance): <a href=\"%s\">%s</a> <br>\n",           
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));            pmij(pmmij,cov,ncovmodel,xp,nlstate);
  fprintf(fichtm,"\           
  - Standard deviation of stable prevalences: <a href=\"%s\">%s</a> <br>\n",\            k=0;
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));            for(i=1; i<= (nlstate); i++){
               for(j=1; j<=(nlstate+ndeath);j++){
 /*  if(popforecast==1) fprintf(fichtm,"\n */                k=k+1;
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */                gp[k]=pmmij[i][j];
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */              }
 /*      <br>",fileres,fileres,fileres,fileres); */            }
 /*  else  */           
 /*    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); */            for(i=1; i<=npar; i++)
  fflush(fichtm);              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");     
             pmij(pmmij,cov,ncovmodel,xp,nlstate);
  m=cptcoveff;            k=0;
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}            for(i=1; i<=(nlstate); i++){
               for(j=1; j<=(nlstate+ndeath);j++){
  jj1=0;                k=k+1;
  for(k1=1; k1<=m;k1++){                gm[k]=pmmij[i][j];
    for(i1=1; i1<=ncodemax[k1];i1++){              }
      jj1++;            }
      if (cptcovn > 0) {       
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
        for (cpt=1; cpt<=cptcoveff;cpt++)               gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);          }
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");  
      }          for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
      for(cpt=1; cpt<=nlstate;cpt++) {            for(theta=1; theta <=npar; theta++)
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \              trgradg[j][theta]=gradg[theta][j];
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\         
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);            matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
      }          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 health expectancies in states (1) and (2): %s%d.png<br>\          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
    } /* end i1 */          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
  }/* End k1 */  
  fprintf(fichtm,"</ul>");          pmij(pmmij,cov,ncovmodel,x,nlstate);
  fflush(fichtm);         
 }          k=0;
           for(i=1; i<=(nlstate); i++){
 /******************* Gnuplot file **************/            for(j=1; j<=(nlstate+ndeath);j++){
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){              k=k+1;
               mu[k][(int) age]=pmmij[i][j];
   char dirfileres[132],optfileres[132];            }
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;          }
   int ng;          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */            for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 /*     printf("Problem with file %s",optionfilegnuplot); */              varpij[i][j][(int)age] = doldm[i][j];
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */  
 /*   } */          /*printf("\n%d ",(int)age);
             for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
   /*#ifdef windows */            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
   fprintf(ficgp,"cd \"%s\" \n",pathc);            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
     /*#endif */            }*/
   m=pow(2,cptcoveff);  
           fprintf(ficresprob,"\n%d ",(int)age);
   strcpy(dirfileres,optionfilefiname);          fprintf(ficresprobcov,"\n%d ",(int)age);
   strcpy(optfileres,"vpl");          fprintf(ficresprobcor,"\n%d ",(int)age);
  /* 1eme*/  
   for (cpt=1; cpt<= nlstate ; cpt ++) {          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
    for (k1=1; k1<= m ; k1 ++) {            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
      fprintf(ficgp,"set xlabel \"Age\" \n\            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 set ylabel \"Probability\" \n\          }
 set ter png small\n\          i=0;
 set size 0.65,0.65\n\          for (k=1; k<=(nlstate);k++){
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);            for (l=1; l<=(nlstate+ndeath);l++){
               i=i++;
      for (i=1; i<= nlstate ; i ++) {              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
        else fprintf(ficgp," \%%*lf (\%%*lf)");              for (j=1; j<=i;j++){
      }                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
      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);                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
      for (i=1; i<= nlstate ; i ++) {              }
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");            }
        else fprintf(ficgp," \%%*lf (\%%*lf)");          }/* end of loop for state */
      }         } /* end of loop for age */
      fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);   
      for (i=1; i<= nlstate ; i ++) {        /* Confidence intervalle of pij  */
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");        /*
        else fprintf(ficgp," \%%*lf (\%%*lf)");          fprintf(ficgp,"\nset noparametric;unset label");
      }            fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
      fprintf(ficgp,"\" t\"\" w l 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));          fprintf(ficgp,"\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);
   /*2 eme*/          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
             fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
   for (k1=1; k1<= m ; k1 ++) {         */
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);  
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
             first1=1;
     for (i=1; i<= nlstate+1 ; i ++) {        for (k2=1; k2<=(nlstate);k2++){
       k=2*i;          for (l2=1; l2<=(nlstate+ndeath);l2++){
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);            if(l2==k2) continue;
       for (j=1; j<= nlstate+1 ; j ++) {            j=(k2-1)*(nlstate+ndeath)+l2;
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");            for (k1=1; k1<=(nlstate);k1++){
         else fprintf(ficgp," \%%*lf (\%%*lf)");              for (l1=1; l1<=(nlstate+ndeath);l1++){
       }                   if(l1==k1) continue;
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");                i=(k1-1)*(nlstate+ndeath)+l1;
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);                if(i<=j) continue;
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);                for (age=bage; age<=fage; age ++){
       for (j=1; j<= nlstate+1 ; j ++) {                  if ((int)age %5==0){
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
         else fprintf(ficgp," \%%*lf (\%%*lf)");                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
       }                       cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
       fprintf(ficgp,"\" t\"\" w l 0,");                    mu1=mu[i][(int) age]/stepm*YEARM ;
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);                    mu2=mu[j][(int) age]/stepm*YEARM;
       for (j=1; j<= nlstate+1 ; j ++) {                    c12=cv12/sqrt(v1*v2);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");                    /* Computing eigen value of matrix of covariance */
         else fprintf(ficgp," \%%*lf (\%%*lf)");                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
       }                       lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");                    /* Eigen vectors */
       else fprintf(ficgp,"\" t\"\" w l 0,");                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
     }                    /*v21=sqrt(1.-v11*v11); *//* error */
   }                    v21=(lc1-v1)/cv12*v11;
                       v12=-v21;
   /*3eme*/                    v22=v11;
                       tnalp=v21/v11;
   for (k1=1; k1<= m ; k1 ++) {                     if(first1==1){
     for (cpt=1; cpt<= nlstate ; cpt ++) {                      first1=0;
       k=2+nlstate*(2*cpt-2);                      printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);                    }
       fprintf(ficgp,"set ter png small\n\                    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);
 set size 0.65,0.65\n\                    /*printf(fignu*/
 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);                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");                    if(first==1){
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);                      first=0;
         fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);                      fprintf(ficgp,"\nset parametric;unset label");
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");                      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,"\" t \"e%d1\" w l",cpt);                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                               fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
       */   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
       for (i=1; i< nlstate ; i ++) {  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
         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);                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                                       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(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,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
   /* CV preval stable (period) */                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
   for (k1=1; k1<= m ; k1 ++) {                       fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
     for (cpt=1; cpt<=nlstate ; cpt ++) {                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
       k=3;                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);                    }else{
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\                      first=0;
 set ter png small\nset size 0.65,0.65\n\                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 unset log y\n\                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);                      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",\
       for (i=1; i< nlstate ; i ++)                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
         fprintf(ficgp,"+$%d",k+i+1);                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);                    }/* if first */
                         } /* age mod 5 */
       l=3+(nlstate+ndeath)*cpt;                } /* end loop age */
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
       for (i=1; i< nlstate ; i ++) {                first=1;
         l=3+(nlstate+ndeath)*cpt;              } /*l12 */
         fprintf(ficgp,"+$%d",l+i+1);            } /* k12 */
       }          } /*l1 */
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);           }/* k1 */
     }       } /* loop covariates */
   }      }
       free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
   /* proba elementaires */    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
   for(i=1,jk=1; i <=nlstate; i++){    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
     for(k=1; k <=(nlstate+ndeath); k++){    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
       if (k != i) {    free_vector(xp,1,npar);
         for(j=1; j <=ncovmodel; j++){    fclose(ficresprob);
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);    fclose(ficresprobcov);
           jk++;     fclose(ficresprobcor);
           fprintf(ficgp,"\n");    fflush(ficgp);
         }    fflush(fichtmcov);
       }  }
     }  
    }  
   /******************* Printing html file ***********/
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
      for(jk=1; jk <=m; jk++) {                    int lastpass, int stepm, int weightopt, char model[],\
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);                     int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
        if (ng==2)                    int popforecast, int estepm ,\
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");                    double jprev1, double mprev1,double anprev1, \
        else                    double jprev2, double mprev2,double anprev2){
          fprintf(ficgp,"\nset title \"Probability\"\n");    int jj1, k1, i1, cpt;
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);  
        i=1;     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
        for(k2=1; k2<=nlstate; k2++) {     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
          k3=i;  </ul>");
          for(k=1; k<=(nlstate+ndeath); k++) {     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
            if (k != k2){   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
              if(ng==2)             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);     fprintf(fichtm,"\
              else   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
              ij=1;     fprintf(fichtm,"\
              for(j=3; j <=ncovmodel; j++) {   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);     fprintf(fichtm,"\
                  ij++;   - (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",
                else             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);     fprintf(fichtm,"\
              }   - Population projections by age and states: \
              fprintf(ficgp,")/(1");     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                
              for(k1=1; k1 <=nlstate; k1++){     fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);  
                ij=1;   m=cptcoveff;
                for(j=3; j <=ncovmodel; j++){   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {  
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);   jj1=0;
                    ij++;   for(k1=1; k1<=m;k1++){
                  }     for(i1=1; i1<=ncodemax[k1];i1++){
                  else       jj1++;
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);       if (cptcovn > 0) {
                }         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                fprintf(ficgp,")");         for (cpt=1; cpt<=cptcoveff;cpt++)
              }           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");       }
              i=i+ncovmodel;       /* Pij */
            }       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> \
          } /* end k */  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
        } /* end k2 */       /* Quasi-incidences */
      } /* end jk */       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
    } /* end ng */   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> \
    fflush(ficgp);   <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
 }  /* end gnuplot */         /* 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> \
 /*************** Moving average **************/  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){         }
        for(cpt=1; cpt<=nlstate;cpt++) {
   int i, cpt, cptcod;          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> \
   int modcovmax =1;  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
   int mobilavrange, mob;       }
   double age;     } /* end i1 */
    }/* End k1 */
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose    fprintf(fichtm,"</ul>");
                            a covariate has 2 modalities */  
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */  
    fprintf(fichtm,"\
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
     if(mobilav==1) mobilavrange=5; /* default */   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
     else mobilavrange=mobilav;  
     for (age=bage; age<=fage; age++)   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
       for (i=1; i<=nlstate;i++)           subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
         for (cptcod=1;cptcod<=modcovmax;cptcod++)   fprintf(fichtm,"\
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
     /* We keep the original values on the extreme ages bage, fage and for            subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2  
        we use a 5 terms etc. until the borders are no more concerned.    fprintf(fichtm,"\
     */    - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
     for (mob=3;mob <=mobilavrange;mob=mob+2){           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){   fprintf(fichtm,"\
         for (i=1; i<=nlstate;i++){   - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
           for (cptcod=1;cptcod<=modcovmax;cptcod++){     <a href=\"%s\">%s</a> <br>\n</li>",
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
               for (cpt=1;cpt<=(mob-1)/2;cpt++){   fprintf(fichtm,"\
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];   - (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): \
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];     <a href=\"%s\">%s</a> <br>\n</li>",
               }             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;   fprintf(fichtm,"\
           }   - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), eij are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences (i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
         }           estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
       }/* end age */   fprintf(fichtm,"\
     }/* end mob */   - 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",
   }else return -1;           subdirf2(fileres,"t"),subdirf2(fileres,"t"));
   return 0;   fprintf(fichtm,"\
 }/* End movingaverage */   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
            subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
   
 /************** Forecasting ******************/  /*  if(popforecast==1) fprintf(fichtm,"\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){  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
   /* proj1, year, month, day of starting projection   /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
      agemin, agemax range of age  /*      <br>",fileres,fileres,fileres,fileres); */
      dateprev1 dateprev2 range of dates during which prevalence is computed  /*  else  */
      anproj2 year of en of projection (same day and month as proj1).  /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
   */   fflush(fichtm);
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
   int *popage;  
   double agec; /* generic age */   m=cptcoveff;
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   double *popeffectif,*popcount;  
   double ***p3mat;   jj1=0;
   double ***mobaverage;   for(k1=1; k1<=m;k1++){
   char fileresf[FILENAMELENGTH];     for(i1=1; i1<=ncodemax[k1];i1++){
        jj1++;
   agelim=AGESUP;       if (cptcovn > 0) {
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
           for (cpt=1; cpt<=cptcoveff;cpt++)
   strcpy(fileresf,"f");            fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
   strcat(fileresf,fileres);         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   if((ficresf=fopen(fileresf,"w"))==NULL) {       }
     printf("Problem with forecast resultfile: %s\n", fileresf);       for(cpt=1; cpt<=nlstate;cpt++) {
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
   }  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
   printf("Computing forecasting: result on file '%s' \n", fileresf);  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);       }
        fprintf(fichtm,"\n<br>- Total life expectancy by age and \
   if (cptcoveff==0) ncodemax[cptcoveff]=1;  health expectancies in states (1) and (2): %s%d.png<br>\
   <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
   if (mobilav!=0) {     } /* end i1 */
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);   }/* End k1 */
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){   fprintf(fichtm,"</ul>");
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);   fflush(fichtm);
       printf(" Error in movingaverage mobilav=%d\n",mobilav);  }
     }  
   }  /******************* Gnuplot file **************/
   void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   stepsize=(int) (stepm+YEARM-1)/YEARM;  
   if (stepm<=12) stepsize=1;    char dirfileres[132],optfileres[132];
   if(estepm < stepm){    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     printf ("Problem %d lower than %d\n",estepm, stepm);    int ng;
   }  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
   else  hstepm=estepm;     /*     printf("Problem with file %s",optionfilegnuplot); */
   /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
   hstepm=hstepm/stepm;   /*   } */
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and  
                                fractional in yp1 */    /*#ifdef windows */
   anprojmean=yp;    fprintf(ficgp,"cd \"%s\" \n",pathc);
   yp2=modf((yp1*12),&yp);      /*#endif */
   mprojmean=yp;    m=pow(2,cptcoveff);
   yp1=modf((yp2*30.5),&yp);  
   jprojmean=yp;    strcpy(dirfileres,optionfilefiname);
   if(jprojmean==0) jprojmean=1;    strcpy(optfileres,"vpl");
   if(mprojmean==0) jprojmean=1;   /* 1eme*/
     for (cpt=1; cpt<= nlstate ; cpt ++) {
   i1=cptcoveff;     for (k1=1; k1<= m ; k1 ++) {
   if (cptcovn < 1){i1=1;}       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
          fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);        fprintf(ficgp,"set xlabel \"Age\" \n\
     set ylabel \"Probability\" \n\
   fprintf(ficresf,"#****** Routine prevforecast **\n");  set ter png small\n\
   set size 0.65,0.65\n\
 /*            if (h==(int)(YEARM*yearp)){ */  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){  
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){       for (i=1; i<= nlstate ; i ++) {
       k=k+1;         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficresf,"\n#******");         else fprintf(ficgp," \%%*lf (\%%*lf)");
       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]]);       fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
       }       for (i=1; i<= nlstate ; i ++) {
       fprintf(ficresf,"******\n");         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");         else fprintf(ficgp," \%%*lf (\%%*lf)");
       for(j=1; j<=nlstate+ndeath;j++){        }
         for(i=1; i<=nlstate;i++)                     fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
           fprintf(ficresf," p%d%d",i,j);       for (i=1; i<= nlstate ; i ++) {
         fprintf(ficresf," p.%d",j);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       }         else fprintf(ficgp," \%%*lf (\%%*lf)");
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {        }  
         fprintf(ficresf,"\n");       fprintf(ficgp,"\" t\"\" w l 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);        }
     }
         for (agec=fage; agec>=(ageminpar-1); agec--){     /*2 eme*/
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);    
           nhstepm = nhstepm/hstepm;     for (k1=1; k1<= m ; k1 ++) {
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
           oldm=oldms;savm=savms;      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);       
               for (i=1; i<= nlstate+1 ; i ++) {
           for (h=0; h<=nhstepm; h++){        k=2*i;
             if (h*hstepm/YEARM*stepm ==yearp) {        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
               fprintf(ficresf,"\n");        for (j=1; j<= nlstate+1 ; j ++) {
               for(j=1;j<=cptcoveff;j++)           if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          else fprintf(ficgp," \%%*lf (\%%*lf)");
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);        }  
             }         if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
             for(j=1; j<=nlstate+ndeath;j++) {        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
               ppij=0.;        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
               for(i=1; i<=nlstate;i++) {        for (j=1; j<= nlstate+1 ; j ++) {
                 if (mobilav==1)           if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];          else fprintf(ficgp," \%%*lf (\%%*lf)");
                 else {        }  
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];        fprintf(ficgp,"\" t\"\" w l 0,");
                 }        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                 if (h*hstepm/YEARM*stepm== yearp) {        for (j=1; j<= nlstate+1 ; j ++) {
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                 }          else fprintf(ficgp," \%%*lf (\%%*lf)");
               } /* end i */        }  
               if (h*hstepm/YEARM*stepm==yearp) {        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
                 fprintf(ficresf," %.3f", ppij);        else fprintf(ficgp,"\" t\"\" w l 0,");
               }      }
             }/* end j */    }
           } /* end h */   
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    /*3eme*/
         } /* end agec */   
       } /* end yearp */    for (k1=1; k1<= m ; k1 ++) {
     } /* end cptcod */      for (cpt=1; cpt<= nlstate ; cpt ++) {
   } /* end  cptcov */        /*       k=2+nlstate*(2*cpt-2); */
                k=2+(nlstate+1)*(cpt-1);
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
         fprintf(ficgp,"set ter png small\n\
   fclose(ficresf);  set size 0.65,0.65\n\
 }  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
         /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 /************** Forecasting *****not tested NB*************/          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 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){          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
             fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
   int *popage;          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
   double calagedatem, agelim, kk1, kk2;         
   double *popeffectif,*popcount;        */
   double ***p3mat,***tabpop,***tabpopprev;        for (i=1; i< nlstate ; i ++) {
   double ***mobaverage;          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);
   char filerespop[FILENAMELENGTH];          /*      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);*/
          
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        }
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
   agelim=AGESUP;      }
   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);    /* CV preval stable (period) */
       for (k1=1; k1<= m ; k1 ++) {
         for (cpt=1; cpt<=nlstate ; cpt ++) {
   strcpy(filerespop,"pop");         k=3;
   strcat(filerespop,fileres);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
   if((ficrespop=fopen(filerespop,"w"))==NULL) {        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
     printf("Problem with forecast resultfile: %s\n", filerespop);  set ter png small\nset size 0.65,0.65\n\
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);  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);
   printf("Computing forecasting: result on file '%s' \n", filerespop);       
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);        for (i=1; i< nlstate ; i ++)
           fprintf(ficgp,"+$%d",k+i+1);
   if (cptcoveff==0) ncodemax[cptcoveff]=1;        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
        
   if (mobilav!=0) {        l=3+(nlstate+ndeath)*cpt;
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){        for (i=1; i< nlstate ; i ++) {
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);          l=3+(nlstate+ndeath)*cpt;
       printf(" Error in movingaverage mobilav=%d\n",mobilav);          fprintf(ficgp,"+$%d",l+i+1);
     }        }
   }        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
       }
   stepsize=(int) (stepm+YEARM-1)/YEARM;    }  
   if (stepm<=12) stepsize=1;   
       /* proba elementaires */
   agelim=AGESUP;    for(i=1,jk=1; i <=nlstate; i++){
         for(k=1; k <=(nlstate+ndeath); k++){
   hstepm=1;        if (k != i) {
   hstepm=hstepm/stepm;           for(j=1; j <=ncovmodel; j++){
               fprintf(ficgp,"p%d=%f ",jk,p[jk]);
   if (popforecast==1) {            jk++;
     if((ficpop=fopen(popfile,"r"))==NULL) {            fprintf(ficgp,"\n");
       printf("Problem with population file : %s\n",popfile);exit(0);          }
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);        }
     }       }
     popage=ivector(0,AGESUP);     }
     popeffectif=vector(0,AGESUP);  
     popcount=vector(0,AGESUP);     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
            for(jk=1; jk <=m; jk++) {
     i=1;            fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;         if (ng==2)
               fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
     imx=i;         else
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];           fprintf(ficgp,"\nset title \"Probability\"\n");
   }         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
          i=1;
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){         for(k2=1; k2<=nlstate; k2++) {
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){           k3=i;
       k=k+1;           for(k=1; k<=(nlstate+ndeath); k++) {
       fprintf(ficrespop,"\n#******");             if (k != k2){
       for(j=1;j<=cptcoveff;j++) {               if(ng==2)
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
       }               else
       fprintf(ficrespop,"******\n");                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
       fprintf(ficrespop,"# Age");               ij=1;
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);               for(j=3; j <=ncovmodel; j++) {
       if (popforecast==1)  fprintf(ficrespop," [Population]");                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                          fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
       for (cpt=0; cpt<=0;cpt++) {                    ij++;
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);                    }
                          else
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){                    fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);                }
           nhstepm = nhstepm/hstepm;                fprintf(ficgp,")/(1");
                          
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);               for(k1=1; k1 <=nlstate; k1++){  
           oldm=oldms;savm=savms;                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);                   ij=1;
                          for(j=3; j <=ncovmodel; j++){
           for (h=0; h<=nhstepm; h++){                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
             if (h==(int) (calagedatem+YEARM*cpt)) {                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);                     ij++;
             }                    }
             for(j=1; j<=nlstate+ndeath;j++) {                   else
               kk1=0.;kk2=0;                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
               for(i=1; i<=nlstate;i++) {                               }
                 if (mobilav==1)                  fprintf(ficgp,")");
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];               }
                 else {               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                 }               i=i+ncovmodel;
               }             }
               if (h==(int)(calagedatem+12*cpt)){           } /* end k */
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;         } /* end k2 */
                   /*fprintf(ficrespop," %.3f", kk1);       } /* end jk */
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/     } /* end ng */
               }     fflush(ficgp);
             }  }  /* end gnuplot */
             for(i=1; i<=nlstate;i++){  
               kk1=0.;  
                 for(j=1; j<=nlstate;j++){  /*************** Moving average **************/
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                 }  
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];    int i, cpt, cptcod;
             }    int modcovmax =1;
     int mobilavrange, mob;
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)     double age;
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);  
           }    modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                             a covariate has 2 modalities */
         }    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
       }  
      if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
   /******/      if(mobilav==1) mobilavrange=5; /* default */
       else mobilavrange=mobilav;
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {       for (age=bage; age<=fage; age++)
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);           for (i=1; i<=nlstate;i++)
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){           for (cptcod=1;cptcod<=modcovmax;cptcod++)
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
           nhstepm = nhstepm/hstepm;       /* We keep the original values on the extreme ages bage, fage and for
                    fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);         we use a 5 terms etc. until the borders are no more concerned.
           oldm=oldms;savm=savms;      */
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        for (mob=3;mob <=mobilavrange;mob=mob+2){
           for (h=0; h<=nhstepm; h++){        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
             if (h==(int) (calagedatem+YEARM*cpt)) {          for (i=1; i<=nlstate;i++){
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);            for (cptcod=1;cptcod<=modcovmax;cptcod++){
             }               mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
             for(j=1; j<=nlstate+ndeath;j++) {                for (cpt=1;cpt<=(mob-1)/2;cpt++){
               kk1=0.;kk2=0;                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
               for(i=1; i<=nlstate;i++) {                                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];                    }
               }              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                    }
             }          }
           }        }/* end age */
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      }/* end mob */
         }    }else return -1;
       }    return 0;
    }   }/* End movingaverage */
   }  
    
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  /************** Forecasting ******************/
   prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
   if (popforecast==1) {    /* proj1, year, month, day of starting projection
     free_ivector(popage,0,AGESUP);       agemin, agemax range of age
     free_vector(popeffectif,0,AGESUP);       dateprev1 dateprev2 range of dates during which prevalence is computed
     free_vector(popcount,0,AGESUP);       anproj2 year of en of projection (same day and month as proj1).
   }    */
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    int *popage;
   fclose(ficrespop);    double agec; /* generic age */
 } /* End of popforecast */    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
     double *popeffectif,*popcount;
 int fileappend(FILE *fichier, char *optionfich)    double ***p3mat;
 {    double ***mobaverage;
   if((fichier=fopen(optionfich,"a"))==NULL) {    char fileresf[FILENAMELENGTH];
     printf("Problem with file: %s\n", optionfich);  
     fprintf(ficlog,"Problem with file: %s\n", optionfich);    agelim=AGESUP;
     return (0);    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
   }   
   fflush(fichier);    strcpy(fileresf,"f");
   return (1);    strcat(fileresf,fileres);
 }    if((ficresf=fopen(fileresf,"w"))==NULL) {
       printf("Problem with forecast resultfile: %s\n", fileresf);
       fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 /**************** function prwizard **********************/    }
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)    printf("Computing forecasting: result on file '%s' \n", fileresf);
 {    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
   
   /* Wizard to print covariance matrix template */    if (cptcoveff==0) ncodemax[cptcoveff]=1;
   
   char ca[32], cb[32], cc[32];    if (mobilav!=0) {
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   int numlinepar;      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      }
   for(i=1; i <=nlstate; i++){    }
     jj=0;  
     for(j=1; j <=nlstate+ndeath; j++){    stepsize=(int) (stepm+YEARM-1)/YEARM;
       if(j==i) continue;    if (stepm<=12) stepsize=1;
       jj++;    if(estepm < stepm){
       /*ca[0]= k+'a'-1;ca[1]='\0';*/      printf ("Problem %d lower than %d\n",estepm, stepm);
       printf("%1d%1d",i,j);    }
       fprintf(ficparo,"%1d%1d",i,j);    else  hstepm=estepm;  
       for(k=1; k<=ncovmodel;k++){  
         /*        printf(" %lf",param[i][j][k]); */    hstepm=hstepm/stepm;
         /*        fprintf(ficparo," %lf",param[i][j][k]); */    yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
         printf(" 0.");                                 fractional in yp1 */
         fprintf(ficparo," 0.");    anprojmean=yp;
       }    yp2=modf((yp1*12),&yp);
       printf("\n");    mprojmean=yp;
       fprintf(ficparo,"\n");    yp1=modf((yp2*30.5),&yp);
     }    jprojmean=yp;
   }    if(jprojmean==0) jprojmean=1;
   printf("# Scales (for hessian or gradient estimation)\n");    if(mprojmean==0) jprojmean=1;
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");  
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/     i1=cptcoveff;
   for(i=1; i <=nlstate; i++){    if (cptcovn < 1){i1=1;}
     jj=0;   
     for(j=1; j <=nlstate+ndeath; j++){    fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
       if(j==i) continue;   
       jj++;    fprintf(ficresf,"#****** Routine prevforecast **\n");
       fprintf(ficparo,"%1d%1d",i,j);  
       printf("%1d%1d",i,j);  /*            if (h==(int)(YEARM*yearp)){ */
       fflush(stdout);    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
       for(k=1; k<=ncovmodel;k++){      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
         /*      printf(" %le",delti3[i][j][k]); */        k=k+1;
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */        fprintf(ficresf,"\n#******");
         printf(" 0.");        for(j=1;j<=cptcoveff;j++) {
         fprintf(ficparo," 0.");          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]]);
       }        }
       numlinepar++;        fprintf(ficresf,"******\n");
       printf("\n");        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
       fprintf(ficparo,"\n");        for(j=1; j<=nlstate+ndeath;j++){
     }          for(i=1; i<=nlstate;i++)              
   }            fprintf(ficresf," p%d%d",i,j);
   printf("# Covariance matrix\n");          fprintf(ficresf," p.%d",j);
 /* # 121 Var(a12)\n\ */        }
 /* # 122 Cov(b12,a12) Var(b12)\n\ */        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */          fprintf(ficresf,"\n");
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
 /* # 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 (agec=fage; agec>=(ageminpar-1); agec--){
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */            nhstepm = nhstepm/hstepm;
   fflush(stdout);            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   fprintf(ficparo,"# Covariance matrix\n");            oldm=oldms;savm=savms;
   /* # 121 Var(a12)\n\ */            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
   /* # 122 Cov(b12,a12) Var(b12)\n\ */         
   /* #   ...\n\ */            for (h=0; h<=nhstepm; h++){
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */              if (h*hstepm/YEARM*stepm ==yearp) {
                   fprintf(ficresf,"\n");
   for(itimes=1;itimes<=2;itimes++){                for(j=1;j<=cptcoveff;j++)
     jj=0;                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     for(i=1; i <=nlstate; i++){                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
       for(j=1; j <=nlstate+ndeath; j++){              }
         if(j==i) continue;              for(j=1; j<=nlstate+ndeath;j++) {
         for(k=1; k<=ncovmodel;k++){                ppij=0.;
           jj++;                for(i=1; i<=nlstate;i++) {
           ca[0]= k+'a'-1;ca[1]='\0';                  if (mobilav==1)
           if(itimes==1){                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
             printf("#%1d%1d%d",i,j,k);                  else {
             fprintf(ficparo,"#%1d%1d%d",i,j,k);                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
           }else{                  }
             printf("%1d%1d%d",i,j,k);                  if (h*hstepm/YEARM*stepm== yearp) {
             fprintf(ficparo,"%1d%1d%d",i,j,k);                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
             /*  printf(" %.5le",matcov[i][j]); */                  }
           }                } /* end i */
           ll=0;                if (h*hstepm/YEARM*stepm==yearp) {
           for(li=1;li <=nlstate; li++){                  fprintf(ficresf," %.3f", ppij);
             for(lj=1;lj <=nlstate+ndeath; lj++){                }
               if(lj==li) continue;              }/* end j */
               for(lk=1;lk<=ncovmodel;lk++){            } /* end h */
                 ll++;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                 if(ll<=jj){          } /* end agec */
                   cb[0]= lk +'a'-1;cb[1]='\0';        } /* end yearp */
                   if(ll<jj){      } /* end cptcod */
                     if(itimes==1){    } /* end  cptcov */
                       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);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                     }else{  
                       printf(" 0.");    fclose(ficresf);
                       fprintf(ficparo," 0.");  }
                     }  
                   }else{  /************** Forecasting *****not tested NB*************/
                     if(itimes==1){  populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
                       printf(" Var(%s%1d%1d)",ca,i,j);   
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                     }else{    int *popage;
                       printf(" 0.");    double calagedatem, agelim, kk1, kk2;
                       fprintf(ficparo," 0.");    double *popeffectif,*popcount;
                     }    double ***p3mat,***tabpop,***tabpopprev;
                   }    double ***mobaverage;
                 }    char filerespop[FILENAMELENGTH];
               } /* end lk */  
             } /* end lj */    tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           } /* end li */    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           printf("\n");    agelim=AGESUP;
           fprintf(ficparo,"\n");    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
           numlinepar++;   
         } /* end k*/    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
       } /*end j */   
     } /* end i */   
   } /* end itimes */    strcpy(filerespop,"pop");
     strcat(filerespop,fileres);
 } /* end of prwizard */    if((ficrespop=fopen(filerespop,"w"))==NULL) {
 /******************* Gompertz Likelihood ******************************/      printf("Problem with forecast resultfile: %s\n", filerespop);
 double gompertz(double x[])      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 {     }
   double A,B,L=0.0,sump=0.,num=0.;    printf("Computing forecasting: result on file '%s' \n", filerespop);
   int i,n=0; /* n is the size of the sample */    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
   for (i=0;i<=imx-1 ; i++) {  
     sump=sump+weight[i];    if (cptcoveff==0) ncodemax[cptcoveff]=1;
     /*    sump=sump+1;*/  
     num=num+1;    if (mobilav!=0) {
   }      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   /* for (i=0; i<=imx; i++)         printf(" Error in movingaverage mobilav=%d\n",mobilav);
      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]);*/      }
     }
   for (i=1;i<=imx ; i++)  
     {    stepsize=(int) (stepm+YEARM-1)/YEARM;
       if (cens[i]==1 & wav[i]>1)    if (stepm<=12) stepsize=1;
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));   
           agelim=AGESUP;
       if (cens[i]==0 & wav[i]>1)   
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))    hstepm=1;
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);      hstepm=hstepm/stepm;
          
       if (wav[i]>1 & agecens[i]>15) {    if (popforecast==1) {
         L=L+A*weight[i];      if((ficpop=fopen(popfile,"r"))==NULL) {
         /*      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("Problem with population file : %s\n",popfile);exit(0);
       }        fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
     }      }
       popage=ivector(0,AGESUP);
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/      popeffectif=vector(0,AGESUP);
        popcount=vector(0,AGESUP);
   return -2*L*num/sump;     
 }      i=1;  
       while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 /******************* Printing html file ***********/     
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \      imx=i;
                   int lastpass, int stepm, int weightopt, char model[],\      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   int imx,  double p[],double **matcov,double agemortsup){    }
   int i,k;  
     for(cptcov=1,k=0;cptcov<=i2;cptcov++){
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);        k=k+1;
   for (i=1;i<=2;i++)         fprintf(ficrespop,"\n#******");
     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]));        for(j=1;j<=cptcoveff;j++) {
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   fprintf(fichtm,"</ul>");        }
         fprintf(ficrespop,"******\n");
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");        fprintf(ficrespop,"# Age");
         for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
  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>");        if (popforecast==1)  fprintf(ficrespop," [Population]");
        
  for (k=agegomp;k<(agemortsup-2);k++)         for (cpt=0; cpt<=0;cpt++) {
    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]);          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
          
            for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
   fflush(fichtm);            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
 }            nhstepm = nhstepm/hstepm;
            
 /******************* Gnuplot file **************/            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){            oldm=oldms;savm=savms;
             hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   char dirfileres[132],optfileres[132];         
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;            for (h=0; h<=nhstepm; h++){
   int ng;              if (h==(int) (calagedatem+YEARM*cpt)) {
                 fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
               }
   /*#ifdef windows */              for(j=1; j<=nlstate+ndeath;j++) {
   fprintf(ficgp,"cd \"%s\" \n",pathc);                kk1=0.;kk2=0;
     /*#endif */                for(i=1; i<=nlstate;i++) {              
                   if (mobilav==1)
                     kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
   strcpy(dirfileres,optionfilefiname);                  else {
   strcpy(optfileres,"vpl");                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
   fprintf(ficgp,"set out \"graphmort.png\"\n ");                   }
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");                 }
   fprintf(ficgp, "set ter png small\n set log y\n");                 if (h==(int)(calagedatem+12*cpt)){
   fprintf(ficgp, "set size 0.65,0.65\n");                  tabpop[(int)(agedeb)][j][cptcod]=kk1;
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);                    /*fprintf(ficrespop," %.3f", kk1);
                       if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 }                 }
               }
               for(i=1; i<=nlstate;i++){
                 kk1=0.;
                   for(j=1; j<=nlstate;j++){
 /***********************************************/                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
 /**************** Main Program *****************/                  }
 /***********************************************/                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
               }
 int main(int argc, char *argv[])  
 {              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;            }
   int jj, ll, li, lj, lk, imk;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int numlinepar=0; /* Current linenumber of parameter file */          }
   int itimes;        }
   int NDIM=2;   
     /******/
   char ca[32], cb[32], cc[32];  
   /*  FILE *fichtm; *//* Html File */        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
   /* FILE *ficgp;*/ /*Gnuplot File */          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   struct stat info;          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
   double agedeb, agefin,hf;            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;            nhstepm = nhstepm/hstepm;
            
   double fret;            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double **xi,tmp,delta;            oldm=oldms;savm=savms;
             hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   double dum; /* Dummy variable */            for (h=0; h<=nhstepm; h++){
   double ***p3mat;              if (h==(int) (calagedatem+YEARM*cpt)) {
   double ***mobaverage;                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   int *indx;              }
   char line[MAXLINE], linepar[MAXLINE];              for(j=1; j<=nlstate+ndeath;j++) {
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];                kk1=0.;kk2=0;
   char pathr[MAXLINE], pathimach[MAXLINE];                 for(i=1; i<=nlstate;i++) {              
   int firstobs=1, lastobs=10;                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
   int sdeb, sfin; /* Status at beginning and end */                }
   int c,  h , cpt,l;                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
   int ju,jl, mi;              }
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;            }
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */          }
   int mobilav=0,popforecast=0;        }
   int hstepm, nhstepm;     }
   int agemortsup;    }
   float  sumlpop=0.;   
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;  
     if (popforecast==1) {
   double bage, fage, age, agelim, agebase;      free_ivector(popage,0,AGESUP);
   double ftolpl=FTOL;      free_vector(popeffectif,0,AGESUP);
   double **prlim;      free_vector(popcount,0,AGESUP);
   double *severity;    }
   double ***param; /* Matrix of parameters */    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   double  *p;    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   double **matcov; /* Matrix of covariance */    fclose(ficrespop);
   double ***delti3; /* Scale */  } /* End of popforecast */
   double *delti; /* Scale */  
   double ***eij, ***vareij;  int fileappend(FILE *fichier, char *optionfich)
   double **varpl; /* Variances of prevalence limits by age */  {
   double *epj, vepp;    if((fichier=fopen(optionfich,"a"))==NULL) {
   double kk1, kk2;      printf("Problem with file: %s\n", optionfich);
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;      fprintf(ficlog,"Problem with file: %s\n", optionfich);
   double **ximort;      return (0);
   char *alph[]={"a","a","b","c","d","e"}, str[4];    }
   int *dcwave;    fflush(fichier);
     return (1);
   char z[1]="c", occ;  }
   
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];  
   char strstart[80], *strt, strtend[80];  /**************** function prwizard **********************/
   char *stratrunc;  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
   int lstra;  {
   
   long total_usecs;    /* Wizard to print covariance matrix template */
    
 /*   setlocale (LC_ALL, ""); */    char ca[32], cb[32], cc[32];
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
 /*   textdomain (PACKAGE); */    int numlinepar;
 /*   setlocale (LC_CTYPE, ""); */  
 /*   setlocale (LC_MESSAGES, ""); */    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */    for(i=1; i <=nlstate; i++){
   (void) gettimeofday(&start_time,&tzp);      jj=0;
   curr_time=start_time;      for(j=1; j <=nlstate+ndeath; j++){
   tm = *localtime(&start_time.tv_sec);        if(j==i) continue;
   tmg = *gmtime(&start_time.tv_sec);        jj++;
   strcpy(strstart,asctime(&tm));        /*ca[0]= k+'a'-1;ca[1]='\0';*/
         printf("%1d%1d",i,j);
 /*  printf("Localtime (at start)=%s",strstart); */        fprintf(ficparo,"%1d%1d",i,j);
 /*  tp.tv_sec = tp.tv_sec +86400; */        for(k=1; k<=ncovmodel;k++){
 /*  tm = *localtime(&start_time.tv_sec); */          /*        printf(" %lf",param[i][j][k]); */
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */          /*        fprintf(ficparo," %lf",param[i][j][k]); */
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */          printf(" 0.");
 /*   tmg.tm_hour=tmg.tm_hour + 1; */          fprintf(ficparo," 0.");
 /*   tp.tv_sec = mktime(&tmg); */        }
 /*   strt=asctime(&tmg); */        printf("\n");
 /*   printf("Time(after) =%s",strstart);  */        fprintf(ficparo,"\n");
 /*  (void) time (&time_value);      }
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);    }
 *  tm = *localtime(&time_value);    printf("# Scales (for hessian or gradient estimation)\n");
 *  strstart=asctime(&tm);    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);     npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
 */    for(i=1; i <=nlstate; i++){
       jj=0;
   nberr=0; /* Number of errors and warnings */      for(j=1; j <=nlstate+ndeath; j++){
   nbwarn=0;        if(j==i) continue;
   getcwd(pathcd, size);        jj++;
         fprintf(ficparo,"%1d%1d",i,j);
   printf("\n%s\n%s",version,fullversion);        printf("%1d%1d",i,j);
   if(argc <=1){        fflush(stdout);
     printf("\nEnter the parameter file name: ");        for(k=1; k<=ncovmodel;k++){
     scanf("%s",pathtot);          /*      printf(" %le",delti3[i][j][k]); */
   }          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
   else{          printf(" 0.");
     strcpy(pathtot,argv[1]);          fprintf(ficparo," 0.");
   }        }
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/        numlinepar++;
   /*cygwin_split_path(pathtot,path,optionfile);        printf("\n");
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/        fprintf(ficparo,"\n");
   /* cutv(path,optionfile,pathtot,'\\');*/      }
     }
   /* Split argv[0], imach program to get pathimach */    printf("# Covariance matrix\n");
   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);  /* # 121 Var(a12)\n\ */
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);  /* # 122 Cov(b12,a12) Var(b12)\n\ */
   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
  /*   strcpy(pathimach,argv[0]); */  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */  /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);  /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);  /* # 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(command,"mkdir ");    fflush(stdout);
   strcat(command,optionfilefiname);    fprintf(ficparo,"# Covariance matrix\n");
   if((outcmd=system(command)) != 0){    /* # 121 Var(a12)\n\ */
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);    /* # 122 Cov(b12,a12) Var(b12)\n\ */
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */    /* #   ...\n\ */
     /* fclose(ficlog); */    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 /*     exit(1); */   
   }    for(itimes=1;itimes<=2;itimes++){
 /*   if((imk=mkdir(optionfilefiname))<0){ */      jj=0;
 /*     perror("mkdir"); */      for(i=1; i <=nlstate; i++){
 /*   } */        for(j=1; j <=nlstate+ndeath; j++){
           if(j==i) continue;
   /*-------- arguments in the command line --------*/          for(k=1; k<=ncovmodel;k++){
             jj++;
   /* Log file */            ca[0]= k+'a'-1;ca[1]='\0';
   strcat(filelog, optionfilefiname);            if(itimes==1){
   strcat(filelog,".log");    /* */              printf("#%1d%1d%d",i,j,k);
   if((ficlog=fopen(filelog,"w"))==NULL)    {              fprintf(ficparo,"#%1d%1d%d",i,j,k);
     printf("Problem with logfile %s\n",filelog);            }else{
     goto end;              printf("%1d%1d%d",i,j,k);
   }              fprintf(ficparo,"%1d%1d%d",i,j,k);
   fprintf(ficlog,"Log filename:%s\n",filelog);              /*  printf(" %.5le",matcov[i][j]); */
   fprintf(ficlog,"\n%s\n%s",version,fullversion);            }
   fprintf(ficlog,"\nEnter the parameter file name: \n");            ll=0;
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\            for(li=1;li <=nlstate; li++){
  path=%s \n\              for(lj=1;lj <=nlstate+ndeath; lj++){
  optionfile=%s\n\                if(lj==li) continue;
  optionfilext=%s\n\                for(lk=1;lk<=ncovmodel;lk++){
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);                  ll++;
                   if(ll<=jj){
   printf("Local time (at start):%s",strstart);                    cb[0]= lk +'a'-1;cb[1]='\0';
   fprintf(ficlog,"Local time (at start): %s",strstart);                    if(ll<jj){
   fflush(ficlog);                      if(itimes==1){
 /*   (void) gettimeofday(&curr_time,&tzp); */                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                       }else{
   /* */                        printf(" 0.");
   strcpy(fileres,"r");                        fprintf(ficparo," 0.");
   strcat(fileres, optionfilefiname);                      }
   strcat(fileres,".txt");    /* Other files have txt extension */                    }else{
                       if(itimes==1){
   /*---------arguments file --------*/                        printf(" Var(%s%1d%1d)",ca,i,j);
                         fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
   if((ficpar=fopen(optionfile,"r"))==NULL)    {                      }else{
     printf("Problem with optionfile %s\n",optionfile);                        printf(" 0.");
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);                        fprintf(ficparo," 0.");
     fflush(ficlog);                      }
     goto end;                    }
   }                  }
                 } /* end lk */
               } /* end lj */
             } /* end li */
   strcpy(filereso,"o");            printf("\n");
   strcat(filereso,fileres);            fprintf(ficparo,"\n");
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */            numlinepar++;
     printf("Problem with Output resultfile: %s\n", filereso);          } /* end k*/
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);        } /*end j */
     fflush(ficlog);      } /* end i */
     goto end;    } /* end itimes */
   }  
   } /* end of prwizard */
   /* Reads comments: lines beginning with '#' */  /******************* Gompertz Likelihood ******************************/
   numlinepar=0;  double gompertz(double x[])
   while((c=getc(ficpar))=='#' && c!= EOF){  {
     ungetc(c,ficpar);    double A,B,L=0.0,sump=0.,num=0.;
     fgets(line, MAXLINE, ficpar);    int i,n=0; /* n is the size of the sample */
     numlinepar++;  
     puts(line);    for (i=0;i<=imx-1 ; i++) {
     fputs(line,ficparo);      sump=sump+weight[i];
     fputs(line,ficlog);      /*    sump=sump+1;*/
   }      num=num+1;
   ungetc(c,ficpar);    }
    
   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);   
   numlinepar++;    /* for (i=0; i<=imx; 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 (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(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);  
   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    for (i=1;i<=imx ; i++)
   fflush(ficlog);      {
   while((c=getc(ficpar))=='#' && c!= EOF){        if (cens[i] == 1 && wav[i]>1)
     ungetc(c,ficpar);          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
     fgets(line, MAXLINE, ficpar);       
     numlinepar++;        if (cens[i] == 0 && wav[i]>1)
     puts(line);          A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
     fputs(line,ficparo);               +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
     fputs(line,ficlog);       
   }        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
   ungetc(c,ficpar);        if (wav[i] > 1 ) { /* ??? */
           L=L+A*weight[i];
              /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
   covar=matrix(0,NCOVMAX,1,n);         }
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/      }
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;  
    /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */   
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */    return -2*L*num/sump;
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/  }
   
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);  /******************* Printing html file ***********/
   delti=delti3[1][1];  void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/                    int lastpass, int stepm, int weightopt, char model[],\
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */                    int imx,  double p[],double **matcov,double agemortsup){
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);    int i,k;
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);  
     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);    fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);     fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
     fclose (ficparo);    for (i=1;i<=2;i++)
     fclose (ficlog);      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]));
     exit(0);    fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
   }    fprintf(fichtm,"</ul>");
   else if(mle==-3) {  
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);  
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);   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>");
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);  
     matcov=matrix(1,npar,1,npar);   for (k=agegomp;k<(agemortsup-2);k++)
   }     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]);
   else{  
     /* Read guess parameters */   
     /* Reads comments: lines beginning with '#' */    fflush(fichtm);
     while((c=getc(ficpar))=='#' && c!= EOF){  }
       ungetc(c,ficpar);  
       fgets(line, MAXLINE, ficpar);  /******************* Gnuplot file **************/
       numlinepar++;  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
       puts(line);  
       fputs(line,ficparo);    char dirfileres[132],optfileres[132];
       fputs(line,ficlog);    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     }    int ng;
     ungetc(c,ficpar);  
       
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    /*#ifdef windows */
     for(i=1; i <=nlstate; i++){    fprintf(ficgp,"cd \"%s\" \n",pathc);
       j=0;      /*#endif */
       for(jj=1; jj <=nlstate+ndeath; jj++){  
         if(jj==i) continue;  
         j++;    strcpy(dirfileres,optionfilefiname);
         fscanf(ficpar,"%1d%1d",&i1,&j1);    strcpy(optfileres,"vpl");
         if ((i1 != i) && (j1 != j)){    fprintf(ficgp,"set out \"graphmort.png\"\n ");
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
           exit(1);    fprintf(ficgp, "set ter png small\n set log y\n");
         }    fprintf(ficgp, "set size 0.65,0.65\n");
         fprintf(ficparo,"%1d%1d",i1,j1);    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
         if(mle==1)  
           printf("%1d%1d",i,j);  }
         fprintf(ficlog,"%1d%1d",i,j);  
         for(k=1; k<=ncovmodel;k++){  
           fscanf(ficpar," %lf",&param[i][j][k]);  
           if(mle==1){  
             printf(" %lf",param[i][j][k]);  
             fprintf(ficlog," %lf",param[i][j][k]);  /***********************************************/
           }  /**************** Main Program *****************/
           else  /***********************************************/
             fprintf(ficlog," %lf",param[i][j][k]);  
           fprintf(ficparo," %lf",param[i][j][k]);  int main(int argc, char *argv[])
         }  {
         fscanf(ficpar,"\n");    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
         numlinepar++;    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
         if(mle==1)    int linei, month, year,iout;
           printf("\n");    int jj, ll, li, lj, lk, imk;
         fprintf(ficlog,"\n");    int numlinepar=0; /* Current linenumber of parameter file */
         fprintf(ficparo,"\n");    int itimes;
       }    int NDIM=2;
     }    
     fflush(ficlog);    char ca[32], cb[32], cc[32];
     char dummy[]="                         ";
     /*  FILE *fichtm; *//* Html File */
     p=param[1][1];    /* FILE *ficgp;*/ /*Gnuplot File */
         struct stat info;
     /* Reads comments: lines beginning with '#' */    double agedeb, agefin,hf;
     while((c=getc(ficpar))=='#' && c!= EOF){    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
       ungetc(c,ficpar);  
       fgets(line, MAXLINE, ficpar);    double fret;
       numlinepar++;    double **xi,tmp,delta;
       puts(line);  
       fputs(line,ficparo);    double dum; /* Dummy variable */
       fputs(line,ficlog);    double ***p3mat;
     }    double ***mobaverage;
     ungetc(c,ficpar);    int *indx;
     char line[MAXLINE], linepar[MAXLINE];
     for(i=1; i <=nlstate; i++){    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
       for(j=1; j <=nlstate+ndeath-1; j++){    char pathr[MAXLINE], pathimach[MAXLINE];
         fscanf(ficpar,"%1d%1d",&i1,&j1);    char **bp, *tok, *val; /* pathtot */
         if ((i1-i)*(j1-j)!=0){    int firstobs=1, lastobs=10;
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);    int sdeb, sfin; /* Status at beginning and end */
           exit(1);    int c,  h , cpt,l;
         }    int ju,jl, mi;
         printf("%1d%1d",i,j);    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
         fprintf(ficparo,"%1d%1d",i1,j1);    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
         fprintf(ficlog,"%1d%1d",i1,j1);    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
         for(k=1; k<=ncovmodel;k++){    int mobilav=0,popforecast=0;
           fscanf(ficpar,"%le",&delti3[i][j][k]);    int hstepm, nhstepm;
           printf(" %le",delti3[i][j][k]);    int agemortsup;
           fprintf(ficparo," %le",delti3[i][j][k]);    float  sumlpop=0.;
           fprintf(ficlog," %le",delti3[i][j][k]);    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;
         fscanf(ficpar,"\n");  
         numlinepar++;    double bage, fage, age, agelim, agebase;
         printf("\n");    double ftolpl=FTOL;
         fprintf(ficparo,"\n");    double **prlim;
         fprintf(ficlog,"\n");    double *severity;
       }    double ***param; /* Matrix of parameters */
     }    double  *p;
     fflush(ficlog);    double **matcov; /* Matrix of covariance */
     double ***delti3; /* Scale */
     delti=delti3[1][1];    double *delti; /* Scale */
     double ***eij, ***vareij;
     double **varpl; /* Variances of prevalence limits by age */
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */    double *epj, vepp;
       double kk1, kk2;
     /* Reads comments: lines beginning with '#' */    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
     while((c=getc(ficpar))=='#' && c!= EOF){    double **ximort;
       ungetc(c,ficpar);    char *alph[]={"a","a","b","c","d","e"}, str[4];
       fgets(line, MAXLINE, ficpar);    int *dcwave;
       numlinepar++;  
       puts(line);    char z[1]="c", occ;
       fputs(line,ficparo);  
       fputs(line,ficlog);    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
     }    char  *strt, strtend[80];
     ungetc(c,ficpar);    char *stratrunc;
       int lstra;
     matcov=matrix(1,npar,1,npar);  
     for(i=1; i <=npar; i++){    long total_usecs;
       fscanf(ficpar,"%s",&str);   
       if(mle==1)  /*   setlocale (LC_ALL, ""); */
         printf("%s",str);  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
       fprintf(ficlog,"%s",str);  /*   textdomain (PACKAGE); */
       fprintf(ficparo,"%s",str);  /*   setlocale (LC_CTYPE, ""); */
       for(j=1; j <=i; j++){  /*   setlocale (LC_MESSAGES, ""); */
         fscanf(ficpar," %le",&matcov[i][j]);  
         if(mle==1){    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
           printf(" %.5le",matcov[i][j]);    (void) gettimeofday(&start_time,&tzp);
         }    curr_time=start_time;
         fprintf(ficlog," %.5le",matcov[i][j]);    tm = *localtime(&start_time.tv_sec);
         fprintf(ficparo," %.5le",matcov[i][j]);    tmg = *gmtime(&start_time.tv_sec);
       }    strcpy(strstart,asctime(&tm));
       fscanf(ficpar,"\n");  
       numlinepar++;  /*  printf("Localtime (at start)=%s",strstart); */
       if(mle==1)  /*  tp.tv_sec = tp.tv_sec +86400; */
         printf("\n");  /*  tm = *localtime(&start_time.tv_sec); */
       fprintf(ficlog,"\n");  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
       fprintf(ficparo,"\n");  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
     }  /*   tmg.tm_hour=tmg.tm_hour + 1; */
     for(i=1; i <=npar; i++)  /*   tp.tv_sec = mktime(&tmg); */
       for(j=i+1;j<=npar;j++)  /*   strt=asctime(&tmg); */
         matcov[i][j]=matcov[j][i];  /*   printf("Time(after) =%s",strstart);  */
       /*  (void) time (&time_value);
     if(mle==1)  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
       printf("\n");  *  tm = *localtime(&time_value);
     fprintf(ficlog,"\n");  *  strstart=asctime(&tm);
       *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
     fflush(ficlog);  */
       
     /*-------- Rewriting parameter file ----------*/    nberr=0; /* Number of errors and warnings */
     strcpy(rfileres,"r");    /* "Rparameterfile */    nbwarn=0;
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/    getcwd(pathcd, size);
     strcat(rfileres,".");    /* */  
     strcat(rfileres,optionfilext);    /* Other files have txt extension */    printf("\n%s\n%s",version,fullversion);
     if((ficres =fopen(rfileres,"w"))==NULL) {    if(argc <=1){
       printf("Problem writing new parameter file: %s\n", fileres);goto end;      printf("\nEnter the parameter file name: ");
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;      fgets(pathr,FILENAMELENGTH,stdin);
     }      i=strlen(pathr);
     fprintf(ficres,"#%s\n",version);      if(pathr[i-1]=='\n')
   }    /* End of mle != -3 */        pathr[i-1]='\0';
      for (tok = pathr; tok != NULL; ){
   /*-------- data file ----------*/        printf("Pathr |%s|\n",pathr);
   if((fic=fopen(datafile,"r"))==NULL)    {        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
     printf("Problem with datafile: %s\n", datafile);goto end;        printf("val= |%s| pathr=%s\n",val,pathr);
     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;        strcpy (pathtot, val);
   }        if(pathr[0] == '\0') break; /* Dirty */
       }
   n= lastobs;    }
   severity = vector(1,maxwav);    else{
   outcome=imatrix(1,maxwav+1,1,n);      strcpy(pathtot,argv[1]);
   num=lvector(1,n);    }
   moisnais=vector(1,n);    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
   annais=vector(1,n);    /*cygwin_split_path(pathtot,path,optionfile);
   moisdc=vector(1,n);      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
   andc=vector(1,n);    /* cutv(path,optionfile,pathtot,'\\');*/
   agedc=vector(1,n);  
   cod=ivector(1,n);    /* Split argv[0], imach program to get pathimach */
   weight=vector(1,n);    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */    split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   mint=matrix(1,maxwav,1,n);    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   anint=matrix(1,maxwav,1,n);   /*   strcpy(pathimach,argv[0]); */
   s=imatrix(1,maxwav+1,1,n);    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
   tab=ivector(1,NCOVMAX);    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
   ncodemax=ivector(1,8);    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
     chdir(path); /* Can be a relative path */
   i=1;    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
   while (fgets(line, MAXLINE, fic) != NULL)    {      printf("Current directory %s!\n",pathcd);
     if ((i >= firstobs) && (i <=lastobs)) {    strcpy(command,"mkdir ");
       for(j=0; line[j] != '\n';j++){  /* Untabifies line */    strcat(command,optionfilefiname);
         if(line[j] == '\t')    if((outcmd=system(command)) != 0){
           line[j] = ' ';      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); */
       for (j=maxwav;j>=1;j--){      /* fclose(ficlog); */
         cutv(stra, strb,line,' '); s[j][i]=atoi(strb);   /*     exit(1); */
         strcpy(line,stra);    }
         cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);  /*   if((imk=mkdir(optionfilefiname))<0){ */
         cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);  /*     perror("mkdir"); */
       }  /*   } */
           
       cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);    /*-------- arguments in the command line --------*/
       cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);  
     /* Log file */
       cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);    strcat(filelog, optionfilefiname);
       cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);    strcat(filelog,".log");    /* */
     if((ficlog=fopen(filelog,"w"))==NULL)    {
       cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);      printf("Problem with logfile %s\n",filelog);
       for (j=ncovcol;j>=1;j--){      goto end;
         cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);    }
       }     fprintf(ficlog,"Log filename:%s\n",filelog);
       lstra=strlen(stra);    fprintf(ficlog,"\n%s\n%s",version,fullversion);
       if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */    fprintf(ficlog,"\nEnter the parameter file name: \n");
         stratrunc = &(stra[lstra-9]);    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
         num[i]=atol(stratrunc);   path=%s \n\
       }   optionfile=%s\n\
       else   optionfilext=%s\n\
         num[i]=atol(stra);   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
           
       /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){    printf("Local time (at start):%s",strstart);
         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;}*/    fprintf(ficlog,"Local time (at start): %s",strstart);
     fflush(ficlog);
       i=i+1;  /*   (void) gettimeofday(&curr_time,&tzp); */
     }  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   }  
   /* printf("ii=%d", ij);    /* */
      scanf("%d",i);*/    strcpy(fileres,"r");
   imx=i-1; /* Number of individuals */    strcat(fileres, optionfilefiname);
     strcat(fileres,".txt");    /* Other files have txt extension */
   /* for (i=1; i<=imx; i++){  
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;    /*---------arguments file --------*/
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;  
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;    if((ficpar=fopen(optionfile,"r"))==NULL)    {
     }*/      printf("Problem with optionfile %s\n",optionfile);
    /*  for (i=1; i<=imx; i++){      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
      if (s[4][i]==9)  s[4][i]=-1;       fflush(ficlog);
      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]));}*/      goto end;
       }
   /* for (i=1; i<=imx; i++) */  
    
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;  
      else weight[i]=1;*/    strcpy(filereso,"o");
     strcat(filereso,fileres);
   /* Calculation of the number of parameters from char model */    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */      printf("Problem with Output resultfile: %s\n", filereso);
   Tprod=ivector(1,15);       fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
   Tvaraff=ivector(1,15);       fflush(ficlog);
   Tvard=imatrix(1,15,1,2);      goto end;
   Tage=ivector(1,15);          }
      
   if (strlen(model) >1){ /* If there is at least 1 covariate */    /* Reads comments: lines beginning with '#' */
     j=0, j1=0, k1=1, k2=1;    numlinepar=0;
     j=nbocc(model,'+'); /* j=Number of '+' */    while((c=getc(ficpar))=='#' && c!= EOF){
     j1=nbocc(model,'*'); /* j1=Number of '*' */      ungetc(c,ficpar);
     cptcovn=j+1;       fgets(line, MAXLINE, ficpar);
     cptcovprod=j1; /*Number of products */      numlinepar++;
           puts(line);
     strcpy(modelsav,model);       fputs(line,ficparo);
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){      fputs(line,ficlog);
       printf("Error. Non available option model=%s ",model);    }
       fprintf(ficlog,"Error. Non available option model=%s ",model);    ungetc(c,ficpar);
       goto end;  
     }    fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
         numlinepar++;
     /* This loop fills the array Tvar from the string 'model'.*/    printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
     for(i=(j+1); i>=1;i--){    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);
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */     fflush(ficlog);
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */    while((c=getc(ficpar))=='#' && c!= EOF){
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/      ungetc(c,ficpar);
       /*scanf("%d",i);*/      fgets(line, MAXLINE, ficpar);
       if (strchr(strb,'*')) {  /* Model includes a product */      numlinepar++;
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/      puts(line);
         if (strcmp(strc,"age")==0) { /* Vn*age */      fputs(line,ficparo);
           cptcovprod--;      fputs(line,ficlog);
           cutv(strb,stre,strd,'V');    }
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/    ungetc(c,ficpar);
           cptcovage++;  
             Tage[cptcovage]=i;     
             /*printf("stre=%s ", stre);*/    covar=matrix(0,NCOVMAX,1,n);
         }    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
         else if (strcmp(strd,"age")==0) { /* or age*Vn */    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
           cptcovprod--;  
           cutv(strb,stre,strc,'V');    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
           Tvar[i]=atoi(stre);    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
           cptcovage++;    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
           Tage[cptcovage]=i;  
         }    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         else {  /* Age is not in the model */    delti=delti3[1][1];
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
           Tvar[i]=ncovcol+k1;    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
           Tprod[k1]=i;      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           Tvard[k1][1]=atoi(strc); /* m*/      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           Tvard[k1][2]=atoi(stre); /* n */      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
           Tvar[cptcovn+k2]=Tvard[k1][1];      fclose (ficparo);
           Tvar[cptcovn+k2+1]=Tvard[k1][2];       fclose (ficlog);
           for (k=1; k<=lastobs;k++)       goto end;
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];      exit(0);
           k1++;    }
           k2=k2+2;    else if(mle==-3) {
         }      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
       }      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
       else { /* no more sum */      fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
        /*  scanf("%d",i);*/      matcov=matrix(1,npar,1,npar);
       cutv(strd,strc,strb,'V');    }
       Tvar[i]=atoi(strc);    else{
       }      /* Read guess parameters */
       strcpy(modelsav,stra);        /* Reads comments: lines beginning with '#' */
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);      while((c=getc(ficpar))=='#' && c!= EOF){
         scanf("%d",i);*/        ungetc(c,ficpar);
     } /* end of loop + */        fgets(line, MAXLINE, ficpar);
   } /* end model */        numlinepar++;
           puts(line);
   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.        fputs(line,ficparo);
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/        fputs(line,ficlog);
       }
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);      ungetc(c,ficpar);
   printf("cptcovprod=%d ", cptcovprod);     
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
       for(i=1; i <=nlstate; i++){
   scanf("%d ",i);        j=0;
   fclose(fic);*/        for(jj=1; jj <=nlstate+ndeath; jj++){
           if(jj==i) continue;
     /*  if(mle==1){*/          j++;
   if (weightopt != 1) { /* Maximisation without weights*/          fscanf(ficpar,"%1d%1d",&i1,&j1);
     for(i=1;i<=n;i++) weight[i]=1.0;          if ((i1 != i) && (j1 != j)){
   }            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
     /*-calculation of age at interview from date of interview and age at death -*/  It might be a problem of design; if ncovcol and the model are correct\n \
   agev=matrix(1,maxwav,1,imx);  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
             exit(1);
   for (i=1; i<=imx; i++) {          }
     for(m=2; (m<= maxwav); m++) {          fprintf(ficparo,"%1d%1d",i1,j1);
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){          if(mle==1)
         anint[m][i]=9999;            printf("%1d%1d",i,j);
         s[m][i]=-1;          fprintf(ficlog,"%1d%1d",i,j);
       }          for(k=1; k<=ncovmodel;k++){
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){            fscanf(ficpar," %lf",&param[i][j][k]);
         nberr++;            if(mle==1){
         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(" %lf",param[i][j][k]);
         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," %lf",param[i][j][k]);
         s[m][i]=-1;            }
       }            else
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){              fprintf(ficlog," %lf",param[i][j][k]);
         nberr++;            fprintf(ficparo," %lf",param[i][j][k]);
         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]);           }
         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]);           fscanf(ficpar,"\n");
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */          numlinepar++;
       }          if(mle==1)
     }            printf("\n");
   }          fprintf(ficlog,"\n");
           fprintf(ficparo,"\n");
   for (i=1; i<=imx; i++)  {        }
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);      }  
     for(m=firstpass; (m<= lastpass); m++){      fflush(ficlog);
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){  
         if (s[m][i] >= nlstate+1) {      p=param[1][1];
           if(agedc[i]>0)     
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)      /* Reads comments: lines beginning with '#' */
               agev[m][i]=agedc[i];      while((c=getc(ficpar))=='#' && c!= EOF){
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/        ungetc(c,ficpar);
             else {        fgets(line, MAXLINE, ficpar);
               if ((int)andc[i]!=9999){        numlinepar++;
                 nbwarn++;        puts(line);
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);        fputs(line,ficparo);
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);        fputs(line,ficlog);
                 agev[m][i]=-1;      }
               }      ungetc(c,ficpar);
             }  
         }      for(i=1; i <=nlstate; i++){
         else if(s[m][i] !=9){ /* Standard case, age in fractional        for(j=1; j <=nlstate+ndeath-1; j++){
                                  years but with the precision of a month */          fscanf(ficpar,"%1d%1d",&i1,&j1);
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);          if ((i1-i)*(j1-j)!=0){
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
             agev[m][i]=1;            exit(1);
           else if(agev[m][i] <agemin){           }
             agemin=agev[m][i];          printf("%1d%1d",i,j);
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/          fprintf(ficparo,"%1d%1d",i1,j1);
           }          fprintf(ficlog,"%1d%1d",i1,j1);
           else if(agev[m][i] >agemax){          for(k=1; k<=ncovmodel;k++){
             agemax=agev[m][i];            fscanf(ficpar,"%le",&delti3[i][j][k]);
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/            printf(" %le",delti3[i][j][k]);
           }            fprintf(ficparo," %le",delti3[i][j][k]);
           /*agev[m][i]=anint[m][i]-annais[i];*/            fprintf(ficlog," %le",delti3[i][j][k]);
           /*     agev[m][i] = age[i]+2*m;*/          }
         }          fscanf(ficpar,"\n");
         else { /* =9 */          numlinepar++;
           agev[m][i]=1;          printf("\n");
           s[m][i]=-1;          fprintf(ficparo,"\n");
         }          fprintf(ficlog,"\n");
       }        }
       else /*= 0 Unknown */      }
         agev[m][i]=1;      fflush(ficlog);
     }  
           delti=delti3[1][1];
   }  
   for (i=1; i<=imx; i++)  {  
     for(m=firstpass; (m<=lastpass); m++){      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
       if (s[m][i] > (nlstate+ndeath)) {   
         nberr++;      /* Reads comments: lines beginning with '#' */
         printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);           while((c=getc(ficpar))=='#' && c!= EOF){
         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);             ungetc(c,ficpar);
         goto end;        fgets(line, MAXLINE, ficpar);
       }        numlinepar++;
     }        puts(line);
   }        fputs(line,ficparo);
         fputs(line,ficlog);
   /*for (i=1; i<=imx; i++){      }
   for (m=firstpass; (m<lastpass); m++){      ungetc(c,ficpar);
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);   
 }      matcov=matrix(1,npar,1,npar);
       for(i=1; i <=npar; i++){
 }*/        fscanf(ficpar,"%s",&str);
         if(mle==1)
           printf("%s",str);
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);        fprintf(ficlog,"%s",str);
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);         fprintf(ficparo,"%s",str);
         for(j=1; j <=i; j++){
   agegomp=(int)agemin;          fscanf(ficpar," %le",&matcov[i][j]);
   free_vector(severity,1,maxwav);          if(mle==1){
   free_imatrix(outcome,1,maxwav+1,1,n);            printf(" %.5le",matcov[i][j]);
   free_vector(moisnais,1,n);          }
   free_vector(annais,1,n);          fprintf(ficlog," %.5le",matcov[i][j]);
   /* free_matrix(mint,1,maxwav,1,n);          fprintf(ficparo," %.5le",matcov[i][j]);
      free_matrix(anint,1,maxwav,1,n);*/        }
   free_vector(moisdc,1,n);        fscanf(ficpar,"\n");
   free_vector(andc,1,n);        numlinepar++;
         if(mle==1)
              printf("\n");
   wav=ivector(1,imx);        fprintf(ficlog,"\n");
   dh=imatrix(1,lastpass-firstpass+1,1,imx);        fprintf(ficparo,"\n");
   bh=imatrix(1,lastpass-firstpass+1,1,imx);      }
   mw=imatrix(1,lastpass-firstpass+1,1,imx);      for(i=1; i <=npar; i++)
            for(j=i+1;j<=npar;j++)
   /* Concatenates waves */          matcov[i][j]=matcov[j][i];
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);     
       if(mle==1)
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */        printf("\n");
       fprintf(ficlog,"\n");
   Tcode=ivector(1,100);     
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);       fflush(ficlog);
   ncodemax[1]=1;     
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);      /*-------- Rewriting parameter file ----------*/
             strcpy(rfileres,"r");    /* "Rparameterfile */
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of       strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                                  the estimations*/      strcat(rfileres,".");    /* */
   h=0;      strcat(rfileres,optionfilext);    /* Other files have txt extension */
   m=pow(2,cptcoveff);      if((ficres =fopen(rfileres,"w"))==NULL) {
          printf("Problem writing new parameter file: %s\n", fileres);goto end;
   for(k=1;k<=cptcoveff; k++){        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
     for(i=1; i <=(m/pow(2,k));i++){      }
       for(j=1; j <= ncodemax[k]; j++){      fprintf(ficres,"#%s\n",version);
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){    }    /* End of mle != -3 */
           h++;  
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;    /*-------- data file ----------*/
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/    if((fic=fopen(datafile,"r"))==NULL)    {
         }       printf("Problem while opening datafile: %s\n", datafile);goto end;
       }      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
     }    }
   }   
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);     n= lastobs;
      codtab[1][2]=1;codtab[2][2]=2; */    severity = vector(1,maxwav);
   /* for(i=1; i <=m ;i++){     outcome=imatrix(1,maxwav+1,1,n);
      for(k=1; k <=cptcovn; k++){    num=lvector(1,n);
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);    moisnais=vector(1,n);
      }    annais=vector(1,n);
      printf("\n");    moisdc=vector(1,n);
      }    andc=vector(1,n);
      scanf("%d",i);*/    agedc=vector(1,n);
         cod=ivector(1,n);
   /*------------ gnuplot -------------*/    weight=vector(1,n);
   strcpy(optionfilegnuplot,optionfilefiname);    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
   if(mle==-3)    mint=matrix(1,maxwav,1,n);
     strcat(optionfilegnuplot,"-mort");    anint=matrix(1,maxwav,1,n);
   strcat(optionfilegnuplot,".gp");    s=imatrix(1,maxwav+1,1,n);
     tab=ivector(1,NCOVMAX);
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {    ncodemax=ivector(1,8);
     printf("Problem with file %s",optionfilegnuplot);  
   }    i=1;
   else{    linei=0;
     fprintf(ficgp,"\n# %s\n", version);     while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
     fprintf(ficgp,"# %s\n", optionfilegnuplot);       linei=linei+1;
     fprintf(ficgp,"set missing 'NaNq'\n");      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
   }        if(line[j] == '\t')
   /*  fclose(ficgp);*/          line[j] = ' ';
   /*--------- index.htm --------*/      }
       for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */        ;
   if(mle==-3)      };
     strcat(optionfilehtm,"-mort");      line[j+1]=0;  /* Trims blanks at end of line */
   strcat(optionfilehtm,".htm");      if(line[0]=='#'){
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {        fprintf(ficlog,"Comment line\n%s\n",line);
     printf("Problem with %s \n",optionfilehtm), exit(0);        printf("Comment line\n%s\n",line);
   }        continue;
       }
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */  
   strcat(optionfilehtmcov,"-cov.htm");      for (j=maxwav;j>=1;j--){
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {        cutv(stra, strb,line,' ');
     printf("Problem with %s \n",optionfilehtmcov), exit(0);        errno=0;
   }        lval=strtol(strb,&endptr,10);
   else{        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \        if( strb[0]=='\0' || (*endptr != '\0')){
 <hr size=\"2\" color=\"#EC5E5E\"> \n\          printf("Error reading data around '%d' at line number %d %s for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\          exit(1);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);        }
   }        s[j][i]=lval;
        
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \        strcpy(line,stra);
 <hr size=\"2\" color=\"#EC5E5E\"> \n\        cutv(stra, strb,line,' ');
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\        if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 \n\        }
 <hr  size=\"2\" color=\"#EC5E5E\">\        else  if(iout=sscanf(strb,"%s.") != 0){
  <ul><li><h4>Parameter files</h4>\n\          month=99;
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\          year=9999;
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\        }else{
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\          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);
  - Date and time at start: %s</ul>\n",\          exit(1);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\        }
           fileres,fileres,\        anint[j][i]= (double) year;
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);        mint[j][i]= (double)month;
   fflush(fichtm);        strcpy(line,stra);
       } /* ENd Waves */
   strcpy(pathr,path);     
   strcat(pathr,optionfilefiname);      cutv(stra, strb,line,' ');
   chdir(optionfilefiname); /* Move to directory named optionfile */      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
         }
   /* Calculates basic frequencies. Computes observed prevalence at single age      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
      and prints on file fileres'p'. */        month=99;
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);        year=9999;
       }else{
   fprintf(fichtm,"\n");        printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\        exit(1);
 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",\      andc[i]=(double) year;
           imx,agemin,agemax,jmin,jmax,jmean);      moisdc[i]=(double) month;
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      strcpy(line,stra);
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */     
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      cutv(stra, strb,line,' ');
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */      }
           else  if(iout=sscanf(strb,"%s.") != 0){
            month=99;
   /* For Powell, parameters are in a vector p[] starting at p[1]        year=9999;
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */      }else{
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */        printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line,j);
         exit(1);
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/      }
   if (mle==-3){      annais[i]=(double)(year);
     ximort=matrix(1,NDIM,1,NDIM);      moisnais[i]=(double)(month);
     cens=ivector(1,n);      strcpy(line,stra);
     ageexmed=vector(1,n);     
     agecens=vector(1,n);      cutv(stra, strb,line,' ');
     dcwave=ivector(1,n);      errno=0;
        dval=strtod(strb,&endptr);
     for (i=1; i<=imx; i++){      if( strb[0]=='\0' || (*endptr != '\0')){
       dcwave[i]=-1;        printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
       for (j=1; j<=lastpass; j++)        exit(1);
         if (s[j][i]>nlstate) {      }
           dcwave[i]=j;      weight[i]=dval;
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/      strcpy(line,stra);
           break;     
         }      for (j=ncovcol;j>=1;j--){
     }        cutv(stra, strb,line,' ');
         errno=0;
     for (i=1; i<=imx; i++) {        lval=strtol(strb,&endptr,10);
       if (wav[i]>0){        if( strb[0]=='\0' || (*endptr != '\0')){
         ageexmed[i]=agev[mw[1][i]][i];          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);
         j=wav[i];agecens[i]=1.;           exit(1);
         if (ageexmed[i]>1 & wav[i]>0) agecens[i]=agev[mw[j][i]][i];        }
         cens[i]=1;        if(lval <-1 || lval >1){
                   printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
         if (ageexmed[i]<1) cens[i]=-1;   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
         if (agedc[i]< AGESUP & agedc[i]>1 & dcwave[i]>firstpass & dcwave[i]<=lastpass) cens[i]=0 ;   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 \
       else cens[i]=-1;   build V1=0 V2=0 for the reference value (1),\n \
     }          V1=1 V2=0 for (2) \n \
        and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
     for (i=1;i<=NDIM;i++) {   output of IMaCh is often meaningless.\n \
       for (j=1;j<=NDIM;j++)   Exiting.\n",lval,linei, i,line,j);
         ximort[i][j]=(i == j ? 1.0 : 0.0);          exit(1);
     }        }
         covar[j][i]=(double)(lval);
     p[1]=0.1; p[2]=0.1;        strcpy(line,stra);
     /*printf("%lf %lf", p[1], p[2]);*/      }
           lstra=strlen(stra);
          
   printf("Powell\n");  fprintf(ficlog,"Powell\n");      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
   strcpy(filerespow,"pow-mort");         stratrunc = &(stra[lstra-9]);
   strcat(filerespow,fileres);        num[i]=atol(stratrunc);
   if((ficrespow=fopen(filerespow,"w"))==NULL) {      }
     printf("Problem with resultfile: %s\n", filerespow);      else
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);        num[i]=atol(stra);
   }      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
   fprintf(ficrespow,"# Powell\n# iter -2*LL");        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;}*/
   /*  for (i=1;i<=nlstate;i++)     
     for(j=1;j<=nlstate+ndeath;j++)      i=i+1;
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);    } /* End loop reading  data */
   */    fclose(fic);
   fprintf(ficrespow,"\n");    /* printf("ii=%d", ij);
        scanf("%d",i);*/
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);    imx=i-1; /* Number of individuals */
     fclose(ficrespow);  
         /* for (i=1; i<=imx; i++){
     hesscov(matcov, p, NDIM,delti, 1e-4, gompertz);       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;
     for(i=1; i <=NDIM; i++)      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
       for(j=i+1;j<=NDIM;j++)      }*/
         matcov[i][j]=matcov[j][i];     /*  for (i=1; i<=imx; i++){
            if (s[4][i]==9)  s[4][i]=-1;
     printf("\nCovariance matrix\n ");       printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/
     for(i=1; i <=NDIM; i++) {   
       for(j=1;j<=NDIM;j++){     /* for (i=1; i<=imx; i++) */
         printf("%f ",matcov[i][j]);   
       }     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
       printf("\n ");       else weight[i]=1;*/
     }  
         /* Calculation of the number of parameters from char model */
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
     for (i=1;i<=NDIM;i++)     Tprod=ivector(1,15);
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));    Tvaraff=ivector(1,15);
     Tvard=imatrix(1,15,1,2);
 lsurv=vector(1,AGESUP);    Tage=ivector(1,15);      
     lpop=vector(1,AGESUP);     
     tpop=vector(1,AGESUP);    if (strlen(model) >1){ /* If there is at least 1 covariate */
     lsurv[agegomp]=100000;      j=0, j1=0, k1=1, k2=1;
          j=nbocc(model,'+'); /* j=Number of '+' */
      for (k=agegomp;k<=AGESUP;k++) {      j1=nbocc(model,'*'); /* j1=Number of '*' */
       agemortsup=k;      cptcovn=j+1;
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;      cptcovprod=j1; /*Number of products */
     }     
          strcpy(modelsav,model);
       for (k=agegomp;k<agemortsup;k++)      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));        printf("Error. Non available option model=%s ",model);
         fprintf(ficlog,"Error. Non available option model=%s ",model);
     for (k=agegomp;k<agemortsup;k++){        goto end;
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;      }
       sumlpop=sumlpop+lpop[k];     
     }      /* This loop fills the array Tvar from the string 'model'.*/
   
  tpop[agegomp]=sumlpop;      for(i=(j+1); i>=1;i--){
     for (k=agegomp;k<(agemortsup-3);k++){        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
       /*  tpop[k+1]=2;*/        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
       tpop[k+1]=tpop[k]-lpop[k];        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
        }        /*scanf("%d",i);*/
            if (strchr(strb,'*')) {  /* Model includes a product */
              cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
        printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");          if (strcmp(strc,"age")==0) { /* Vn*age */
     for (k=agegomp;k<(agemortsup-2);k++)             cptcovprod--;
       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]);            cutv(strb,stre,strd,'V');
             Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
             cptcovage++;
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */              Tage[cptcovage]=i;
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);              /*printf("stre=%s ", stre);*/
               }
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \          else if (strcmp(strd,"age")==0) { /* or age*Vn */
                      stepm, weightopt,\            cptcovprod--;
                      model,imx,p,matcov,agemortsup);            cutv(strb,stre,strc,'V');
             Tvar[i]=atoi(stre);
     free_vector(lsurv,1,AGESUP);            cptcovage++;
     free_vector(lpop,1,AGESUP);            Tage[cptcovage]=i;
     free_vector(tpop,1,AGESUP);          }
   } /* Endof if mle==-3 */          else {  /* Age is not in the model */
             cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
   else{ /* For mle >=1 */            Tvar[i]=ncovcol+k1;
               cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */            Tprod[k1]=i;
     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);            Tvard[k1][1]=atoi(strc); /* m*/
     for (k=1; k<=npar;k++)            Tvard[k1][2]=atoi(stre); /* n */
       printf(" %d %8.5f",k,p[k]);            Tvar[cptcovn+k2]=Tvard[k1][1];
     printf("\n");            Tvar[cptcovn+k2+1]=Tvard[k1][2];
     globpr=1; /* to print the contributions */            for (k=1; k<=lastobs;k++)
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);            k1++;
     for (k=1; k<=npar;k++)            k2=k2+2;
       printf(" %d %8.5f",k,p[k]);          }
     printf("\n");        }
     if(mle>=1){ /* Could be 1 or 2 */        else { /* no more sum */
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
     }         /*  scanf("%d",i);*/
             cutv(strd,strc,strb,'V');
     /*--------- results files --------------*/        Tvar[i]=atoi(strc);
     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);        }
             strcpy(modelsav,stra);  
             /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");          scanf("%d",i);*/
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      } /* end of loop + */
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    } /* end model */
     for(i=1,jk=1; i <=nlstate; i++){   
       for(k=1; k <=(nlstate+ndeath); k++){    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
         if (k != i) {      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
           printf("%d%d ",i,k);  
           fprintf(ficlog,"%d%d ",i,k);    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
           fprintf(ficres,"%1d%1d ",i,k);    printf("cptcovprod=%d ", cptcovprod);
           for(j=1; j <=ncovmodel; j++){    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
             printf("%f ",p[jk]);  
             fprintf(ficlog,"%f ",p[jk]);    scanf("%d ",i);*/
             fprintf(ficres,"%f ",p[jk]);  
             jk++;       /*  if(mle==1){*/
           }    if (weightopt != 1) { /* Maximisation without weights*/
           printf("\n");      for(i=1;i<=n;i++) weight[i]=1.0;
           fprintf(ficlog,"\n");    }
           fprintf(ficres,"\n");      /*-calculation of age at interview from date of interview and age at death -*/
         }    agev=matrix(1,maxwav,1,imx);
       }  
     }    for (i=1; i<=imx; i++) {
     if(mle!=0){      for(m=2; (m<= maxwav); m++) {
       /* Computing hessian and covariance matrix */        if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
       ftolhess=ftol; /* Usually correct */          anint[m][i]=9999;
       hesscov(matcov, p, npar, delti, ftolhess, func);          s[m][i]=-1;
     }        }
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
     printf("# Scales (for hessian or gradient estimation)\n");          nberr++;
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");          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);
     for(i=1,jk=1; i <=nlstate; 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);
       for(j=1; j <=nlstate+ndeath; j++){          s[m][i]=-1;
         if (j!=i) {        }
           fprintf(ficres,"%1d%1d",i,j);        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
           printf("%1d%1d",i,j);          nberr++;
           fprintf(ficlog,"%1d%1d",i,j);          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]);
           for(k=1; k<=ncovmodel;k++){          fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]);
             printf(" %.5e",delti[jk]);          s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
             fprintf(ficlog," %.5e",delti[jk]);        }
             fprintf(ficres," %.5e",delti[jk]);      }
             jk++;    }
           }  
           printf("\n");    for (i=1; i<=imx; i++)  {
           fprintf(ficlog,"\n");      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
           fprintf(ficres,"\n");      for(m=firstpass; (m<= lastpass); m++){
         }        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
       }          if (s[m][i] >= nlstate+1) {
     }            if(agedc[i]>0)
                   if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
     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");                agev[m][i]=agedc[i];
     if(mle>=1)            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
       printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");              else {
     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 ((int)andc[i]!=9999){
     /* # 121 Var(a12)\n\ */                  nbwarn++;
     /* # 122 Cov(b12,a12) Var(b12)\n\ */                  printf("Warning negative age at death: %ld line:%d\n",num[i],i);
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */                  agev[m][i]=-1;
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */                }
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */              }
     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */          }
     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */          else if(s[m][i] !=9){ /* Standard case, age in fractional
                                        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]);
     /* Just to have a covariance matrix which will be more understandable            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
        even is we still don't want to manage dictionary of variables              agev[m][i]=1;
     */            else if(agev[m][i] <agemin){
     for(itimes=1;itimes<=2;itimes++){              agemin=agev[m][i];
       jj=0;              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
       for(i=1; i <=nlstate; i++){            }
         for(j=1; j <=nlstate+ndeath; j++){            else if(agev[m][i] >agemax){
           if(j==i) continue;              agemax=agev[m][i];
           for(k=1; k<=ncovmodel;k++){              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
             jj++;            }
             ca[0]= k+'a'-1;ca[1]='\0';            /*agev[m][i]=anint[m][i]-annais[i];*/
             if(itimes==1){            /*     agev[m][i] = age[i]+2*m;*/
               if(mle>=1)          }
                 printf("#%1d%1d%d",i,j,k);          else { /* =9 */
               fprintf(ficlog,"#%1d%1d%d",i,j,k);            agev[m][i]=1;
               fprintf(ficres,"#%1d%1d%d",i,j,k);            s[m][i]=-1;
             }else{          }
               if(mle>=1)        }
                 printf("%1d%1d%d",i,j,k);        else /*= 0 Unknown */
               fprintf(ficlog,"%1d%1d%d",i,j,k);          agev[m][i]=1;
               fprintf(ficres,"%1d%1d%d",i,j,k);      }
             }     
             ll=0;    }
             for(li=1;li <=nlstate; li++){    for (i=1; i<=imx; i++)  {
               for(lj=1;lj <=nlstate+ndeath; lj++){      for(m=firstpass; (m<=lastpass); m++){
                 if(lj==li) continue;        if (s[m][i] > (nlstate+ndeath)) {
                 for(lk=1;lk<=ncovmodel;lk++){          nberr++;
                   ll++;          printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);    
                   if(ll<=jj){          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);    
                     cb[0]= lk +'a'-1;cb[1]='\0';          goto end;
                     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);    /*for (i=1; i<=imx; i++){
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);    for (m=firstpass; (m<lastpass); m++){
                       }else{       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                         if(mle>=1)  }
                           printf(" %.5e",matcov[jj][ll]);   
                         fprintf(ficlog," %.5e",matcov[jj][ll]);   }*/
                         fprintf(ficres," %.5e",matcov[jj][ll]);   
                       }  
                     }else{    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
                       if(itimes==1){    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
                         if(mle>=1)  
                           printf(" Var(%s%1d%1d)",ca,i,j);    agegomp=(int)agemin;
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);    free_vector(severity,1,maxwav);
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);    free_imatrix(outcome,1,maxwav+1,1,n);
                       }else{    free_vector(moisnais,1,n);
                         if(mle>=1)    free_vector(annais,1,n);
                           printf(" %.5e",matcov[jj][ll]);     /* free_matrix(mint,1,maxwav,1,n);
                         fprintf(ficlog," %.5e",matcov[jj][ll]);        free_matrix(anint,1,maxwav,1,n);*/
                         fprintf(ficres," %.5e",matcov[jj][ll]);     free_vector(moisdc,1,n);
                       }    free_vector(andc,1,n);
                     }  
                   }     
                 } /* end lk */    wav=ivector(1,imx);
               } /* end lj */    dh=imatrix(1,lastpass-firstpass+1,1,imx);
             } /* end li */    bh=imatrix(1,lastpass-firstpass+1,1,imx);
             if(mle>=1)    mw=imatrix(1,lastpass-firstpass+1,1,imx);
               printf("\n");     
             fprintf(ficlog,"\n");    /* Concatenates waves */
             fprintf(ficres,"\n");    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
             numlinepar++;  
           } /* end k*/    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
         } /*end j */  
       } /* end i */    Tcode=ivector(1,100);
     } /* end itimes */    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
         ncodemax[1]=1;
     fflush(ficlog);    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
     fflush(ficres);       
         codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
     while((c=getc(ficpar))=='#' && c!= EOF){                                   the estimations*/
       ungetc(c,ficpar);    h=0;
       fgets(line, MAXLINE, ficpar);    m=pow(2,cptcoveff);
       puts(line);   
       fputs(line,ficparo);    for(k=1;k<=cptcoveff; k++){
     }      for(i=1; i <=(m/pow(2,k));i++){
     ungetc(c,ficpar);        for(j=1; j <= ncodemax[k]; j++){
               for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
     estepm=0;            h++;
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
     if (estepm==0 || estepm < stepm) estepm=stepm;            /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
     if (fage <= 2) {          }
       bage = ageminpar;        }
       fage = agemaxpar;      }
     }    }
         /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");       codtab[1][2]=1;codtab[2][2]=2; */
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);    /* for(i=1; i <=m ;i++){
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);       for(k=1; k <=cptcovn; k++){
            printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
     while((c=getc(ficpar))=='#' && c!= EOF){       }
       ungetc(c,ficpar);       printf("\n");
       fgets(line, MAXLINE, ficpar);       }
       puts(line);       scanf("%d",i);*/
       fputs(line,ficparo);     
     }    /*------------ gnuplot -------------*/
     ungetc(c,ficpar);    strcpy(optionfilegnuplot,optionfilefiname);
         if(mle==-3)
     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);      strcat(optionfilegnuplot,"-mort");
     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);    strcat(optionfilegnuplot,".gp");
     fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);  
     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
     fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);      printf("Problem with file %s",optionfilegnuplot);
         }
     while((c=getc(ficpar))=='#' && c!= EOF){    else{
       ungetc(c,ficpar);      fprintf(ficgp,"\n# %s\n", version);
       fgets(line, MAXLINE, ficpar);      fprintf(ficgp,"# %s\n", optionfilegnuplot);
       puts(line);      fprintf(ficgp,"set missing 'NaNq'\n");
       fputs(line,ficparo);    }
     }    /*  fclose(ficgp);*/
     ungetc(c,ficpar);    /*--------- index.htm --------*/
       
         strcpy(optionfilehtm,optionfilefiname); /* Main html file */
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;    if(mle==-3)
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;      strcat(optionfilehtm,"-mort");
         strcat(optionfilehtm,".htm");
     fscanf(ficpar,"pop_based=%d\n",&popbased);    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
     fprintf(ficparo,"pop_based=%d\n",popbased);         printf("Problem with %s \n",optionfilehtm), exit(0);
     fprintf(ficres,"pop_based=%d\n",popbased);       }
       
     while((c=getc(ficpar))=='#' && c!= EOF){    strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
       ungetc(c,ficpar);    strcat(optionfilehtmcov,"-cov.htm");
       fgets(line, MAXLINE, ficpar);    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
       puts(line);      printf("Problem with %s \n",optionfilehtmcov), exit(0);
       fputs(line,ficparo);    }
     }    else{
     ungetc(c,ficpar);    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
       <hr size=\"2\" color=\"#EC5E5E\"> \n\
     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);  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
     fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
     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);    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
     /* day and month of proj2 are not used but only year anproj2.*/  <hr size=\"2\" color=\"#EC5E5E\"> \n\
       Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
       \n\
       <hr  size=\"2\" color=\"#EC5E5E\">\
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/   <ul><li><h4>Parameter files</h4>\n\
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/   - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
        - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */   - Log file of the run: <a href=\"%s\">%s</a><br>\n\
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
        - Date and time at start: %s</ul>\n",\
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);            fileres,fileres,\
                   filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
    /*------------ free_vector  -------------*/    fflush(fichtm);
    /*  chdir(path); */  
      strcpy(pathr,path);
     free_ivector(wav,1,imx);    strcat(pathr,optionfilefiname);
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);    chdir(optionfilefiname); /* Move to directory named optionfile */
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);   
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);       /* Calculates basic frequencies. Computes observed prevalence at single age
     free_lvector(num,1,n);       and prints on file fileres'p'. */
     free_vector(agedc,1,n);    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
     /*free_matrix(covar,0,NCOVMAX,1,n);*/  
     /*free_matrix(covar,1,NCOVMAX,1,n);*/    fprintf(fichtm,"\n");
     fclose(ficparo);    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
     fclose(ficres);  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);
     /*--------------- Prevalence limit  (stable prevalence) --------------*/    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
         oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     strcpy(filerespl,"pl");      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     strcat(filerespl,fileres);      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     if((ficrespl=fopen(filerespl,"w"))==NULL) {      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
       printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;     
       fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;     
     }    /* For Powell, parameters are in a vector p[] starting at p[1]
     printf("Computing stable prevalence: result on file '%s' \n", filerespl);       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
     fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);    p=param[1][1]; /* *(*(*(param +1)+1)+0) */
     fprintf(ficrespl, "#Local time at start: %s", strstart);  
     fprintf(ficrespl,"#Stable prevalence \n");    globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
     fprintf(ficrespl,"#Age ");  
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);    if (mle==-3){
     fprintf(ficrespl,"\n");      ximort=matrix(1,NDIM,1,NDIM);
         cens=ivector(1,n);
     prlim=matrix(1,nlstate,1,nlstate);      ageexmed=vector(1,n);
       agecens=vector(1,n);
     agebase=ageminpar;      dcwave=ivector(1,n);
     agelim=agemaxpar;   
     ftolpl=1.e-10;      for (i=1; i<=imx; i++){
     i1=cptcoveff;        dcwave[i]=-1;
     if (cptcovn < 1){i1=1;}        for (m=firstpass; m<=lastpass; m++)
           if (s[m][i]>nlstate) {
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){            dcwave[i]=m;
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){            /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
         k=k+1;            break;
         /*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 (i=1; i<=imx; i++) {
         for(j=1;j<=cptcoveff;j++) {        if (wav[i]>0){
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          ageexmed[i]=agev[mw[1][i]][i];
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          j=wav[i];
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          agecens[i]=1.;
         }  
         fprintf(ficrespl,"******\n");          if (ageexmed[i]> 1 && wav[i] > 0){
         printf("******\n");            agecens[i]=agev[mw[j][i]][i];
         fprintf(ficlog,"******\n");            cens[i]= 1;
                   }else if (ageexmed[i]< 1)
         for (age=agebase; age<=agelim; age++){            cens[i]= -1;
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);          if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
           fprintf(ficrespl,"%.0f ",age );            cens[i]=0 ;
           for(j=1;j<=cptcoveff;j++)        }
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        else cens[i]=-1;
           for(i=1; i<=nlstate;i++)      }
             fprintf(ficrespl," %.5f", prlim[i][i]);     
           fprintf(ficrespl,"\n");      for (i=1;i<=NDIM;i++) {
         }        for (j=1;j<=NDIM;j++)
       }          ximort[i][j]=(i == j ? 1.0 : 0.0);
     }      }
     fclose(ficrespl);     
       p[1]=0.0268; p[NDIM]=0.083;
     /*------------- h Pij x at various ages ------------*/      /*printf("%lf %lf", p[1], p[2]);*/
        
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);     
     if((ficrespij=fopen(filerespij,"w"))==NULL) {      printf("Powell\n");  fprintf(ficlog,"Powell\n");
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;      strcpy(filerespow,"pow-mort");
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;      strcat(filerespow,fileres);
     }      if((ficrespow=fopen(filerespow,"w"))==NULL) {
     printf("Computing pij: result on file '%s' \n", filerespij);        printf("Problem with resultfile: %s\n", filerespow);
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
         }
     stepsize=(int) (stepm+YEARM-1)/YEARM;      fprintf(ficrespow,"# Powell\n# iter -2*LL");
     /*if (stepm<=24) stepsize=2;*/      /*  for (i=1;i<=nlstate;i++)
           for(j=1;j<=nlstate+ndeath;j++)
     agelim=AGESUP;          if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
     hstepm=stepsize*YEARM; /* Every year of age */      */
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */       fprintf(ficrespow,"\n");
      
     /* hstepm=1;   aff par mois*/      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
     fprintf(ficrespij, "#Local time at start: %s", strstart);      fclose(ficrespow);
     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++){      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){  
         k=k+1;      for(i=1; i <=NDIM; i++)
         fprintf(ficrespij,"\n#****** ");        for(j=i+1;j<=NDIM;j++)
         for(j=1;j<=cptcoveff;j++)           matcov[i][j]=matcov[j][i];
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);     
         fprintf(ficrespij,"******\n");      printf("\nCovariance matrix\n ");
               for(i=1; i <=NDIM; i++) {
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */        for(j=1;j<=NDIM;j++){
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */           printf("%f ",matcov[i][j]);
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */        }
         printf("\n ");
           /*      nhstepm=nhstepm*YEARM; aff par mois*/      }
      
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
           oldm=oldms;savm=savms;      for (i=1;i<=NDIM;i++)
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);          printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");  
           for(i=1; i<=nlstate;i++)      lsurv=vector(1,AGESUP);
             for(j=1; j<=nlstate+ndeath;j++)      lpop=vector(1,AGESUP);
               fprintf(ficrespij," %1d-%1d",i,j);      tpop=vector(1,AGESUP);
           fprintf(ficrespij,"\n");      lsurv[agegomp]=100000;
           for (h=0; h<=nhstepm; h++){     
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );      for (k=agegomp;k<=AGESUP;k++) {
             for(i=1; i<=nlstate;i++)        agemortsup=k;
               for(j=1; j<=nlstate+ndeath;j++)        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);      }
             fprintf(ficrespij,"\n");     
           }      for (k=agegomp;k<agemortsup;k++)
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
           fprintf(ficrespij,"\n");     
         }      for (k=agegomp;k<agemortsup;k++){
       }        lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
     }        sumlpop=sumlpop+lpop[k];
       }
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);     
       tpop[agegomp]=sumlpop;
     fclose(ficrespij);      for (k=agegomp;k<(agemortsup-3);k++){
         /*  tpop[k+1]=2;*/
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);        tpop[k+1]=tpop[k]-lpop[k];
     for(i=1;i<=AGESUP;i++)      }
       for(j=1;j<=NCOVMAX;j++)     
         for(k=1;k<=NCOVMAX;k++)     
           probs[i][j][k]=0.;      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
       for (k=agegomp;k<(agemortsup-2);k++)
     /*---------- Forecasting ------------------*/        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]);
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/     
     if(prevfcast==1){     
       /*    if(stepm ==1){*/      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/     
       /*      }  */      printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
       /*      else{ */                       stepm, weightopt,\
       /*        erreur=108; */                       model,imx,p,matcov,agemortsup);
       /*        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); */      free_vector(lsurv,1,AGESUP);
       /*      } */      free_vector(lpop,1,AGESUP);
     }      free_vector(tpop,1,AGESUP);
       } /* Endof if mle==-3 */
    
     /*---------- Health expectancies and variances ------------*/    else{ /* For mle >=1 */
    
     strcpy(filerest,"t");      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
     strcat(filerest,fileres);      printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
     if((ficrest=fopen(filerest,"w"))==NULL) {      for (k=1; k<=npar;k++)
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;        printf(" %d %8.5f",k,p[k]);
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;      printf("\n");
     }      globpr=1; /* to print the contributions */
     printf("Computing Total LEs with variances: file '%s' \n", filerest);       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
     fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest);       printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
       for (k=1; k<=npar;k++)
         printf(" %d %8.5f",k,p[k]);
     strcpy(filerese,"e");      printf("\n");
     strcat(filerese,fileres);      if(mle>=1){ /* Could be 1 or 2 */
     if((ficreseij=fopen(filerese,"w"))==NULL) {        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);      }
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);     
     }      /*--------- results files --------------*/
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);      fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);     
      
     strcpy(fileresv,"v");      fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     strcat(fileresv,fileres);      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     if((ficresvij=fopen(fileresv,"w"))==NULL) {      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);      for(i=1,jk=1; i <=nlstate; i++){
       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);        for(k=1; k <=(nlstate+ndeath); k++){
     }          if (k != i) {
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);            printf("%d%d ",i,k);
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);            fprintf(ficlog,"%d%d ",i,k);
             fprintf(ficres,"%1d%1d ",i,k);
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */            for(j=1; j <=ncovmodel; j++){
     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);              printf("%lf ",p[jk]);
     /*  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",\              fprintf(ficlog,"%lf ",p[jk]);
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);              fprintf(ficres,"%lf ",p[jk]);
     */              jk++;
             }
     if (mobilav!=0) {            printf("\n");
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            fprintf(ficlog,"\n");
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){            fprintf(ficres,"\n");
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);          }
         printf(" Error in movingaverage mobilav=%d\n",mobilav);        }
       }      }
     }      if(mle!=0){
         /* Computing hessian and covariance matrix */
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){        ftolhess=ftol; /* Usually correct */
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){        hesscov(matcov, p, npar, delti, ftolhess, func);
         k=k+1;       }
         fprintf(ficrest,"\n#****** ");      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
         for(j=1;j<=cptcoveff;j++)       printf("# Scales (for hessian or gradient estimation)\n");
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
         fprintf(ficrest,"******\n");      for(i=1,jk=1; i <=nlstate; i++){
         for(j=1; j <=nlstate+ndeath; j++){
         fprintf(ficreseij,"\n#****** ");          if (j!=i) {
         for(j=1;j<=cptcoveff;j++)             fprintf(ficres,"%1d%1d",i,j);
           fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            printf("%1d%1d",i,j);
         fprintf(ficreseij,"******\n");            fprintf(ficlog,"%1d%1d",i,j);
             for(k=1; k<=ncovmodel;k++){
         fprintf(ficresvij,"\n#****** ");              printf(" %.5e",delti[jk]);
         for(j=1;j<=cptcoveff;j++)               fprintf(ficlog," %.5e",delti[jk]);
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);              fprintf(ficres," %.5e",delti[jk]);
         fprintf(ficresvij,"******\n");              jk++;
             }
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);            printf("\n");
         oldm=oldms;savm=savms;            fprintf(ficlog,"\n");
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);              fprintf(ficres,"\n");
            }
         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){      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");
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);      if(mle>=1)
         }        printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
       fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
         fprintf(ficrest, "#Local time at start: %s", strstart);      /* # 121 Var(a12)\n\ */
         fprintf(ficrest,"#Total LEs with variances: e.. (std) ");      /* # 122 Cov(b12,a12) Var(b12)\n\ */
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);      /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
         fprintf(ficrest,"\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\ */
         epj=vector(1,nlstate+1);      /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
         for(age=bage; age <=fage ;age++){      /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
           if (popbased==1) {     
             if(mobilav ==0){     
               for(i=1; i<=nlstate;i++)      /* Just to have a covariance matrix which will be more understandable
                 prlim[i][i]=probs[(int)age][i][k];         even is we still don't want to manage dictionary of variables
             }else{ /* mobilav */       */
               for(i=1; i<=nlstate;i++)      for(itimes=1;itimes<=2;itimes++){
                 prlim[i][i]=mobaverage[(int)age][i][k];        jj=0;
             }        for(i=1; i <=nlstate; i++){
           }          for(j=1; j <=nlstate+ndeath; j++){
                     if(j==i) continue;
           fprintf(ficrest," %4.0f",age);            for(k=1; k<=ncovmodel;k++){
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){              jj++;
             for(i=1, epj[j]=0.;i <=nlstate;i++) {              ca[0]= k+'a'-1;ca[1]='\0';
               epj[j] += prlim[i][i]*eij[i][j][(int)age];              if(itimes==1){
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/                if(mle>=1)
             }                  printf("#%1d%1d%d",i,j,k);
             epj[nlstate+1] +=epj[j];                fprintf(ficlog,"#%1d%1d%d",i,j,k);
           }                fprintf(ficres,"#%1d%1d%d",i,j,k);
               }else{
           for(i=1, vepp=0.;i <=nlstate;i++)                if(mle>=1)
             for(j=1;j <=nlstate;j++)                  printf("%1d%1d%d",i,j,k);
               vepp += vareij[i][j][(int)age];                fprintf(ficlog,"%1d%1d%d",i,j,k);
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));                fprintf(ficres,"%1d%1d%d",i,j,k);
           for(j=1;j <=nlstate;j++){              }
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));              ll=0;
           }              for(li=1;li <=nlstate; li++){
           fprintf(ficrest,"\n");                for(lj=1;lj <=nlstate+ndeath; lj++){
         }                  if(lj==li) continue;
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);                  for(lk=1;lk<=ncovmodel;lk++){
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);                    ll++;
         free_vector(epj,1,nlstate+1);                    if(ll<=jj){
       }                      cb[0]= lk +'a'-1;cb[1]='\0';
     }                      if(ll<jj){
     free_vector(weight,1,n);                        if(itimes==1){
     free_imatrix(Tvard,1,15,1,2);                          if(mle>=1)
     free_imatrix(s,1,maxwav+1,1,n);                            printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     free_matrix(anint,1,maxwav,1,n);                           fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     free_matrix(mint,1,maxwav,1,n);                          fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     free_ivector(cod,1,n);                        }else{
     free_ivector(tab,1,NCOVMAX);                          if(mle>=1)
     fclose(ficreseij);                            printf(" %.5e",matcov[jj][ll]);
     fclose(ficresvij);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
     fclose(ficrest);                          fprintf(ficres," %.5e",matcov[jj][ll]);
     fclose(ficpar);                        }
                         }else{
     /*------- Variance of stable prevalence------*/                           if(itimes==1){
                           if(mle>=1)
     strcpy(fileresvpl,"vpl");                            printf(" Var(%s%1d%1d)",ca,i,j);
     strcat(fileresvpl,fileres);                          fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {                          fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
       printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);                        }else{
       exit(0);                          if(mle>=1)
     }                            printf(" %.5e",matcov[jj][ll]);
     printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
                           fprintf(ficres," %.5e",matcov[jj][ll]);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){                        }
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){                      }
         k=k+1;                    }
         fprintf(ficresvpl,"\n#****** ");                  } /* end lk */
         for(j=1;j<=cptcoveff;j++)                 } /* end lj */
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);              } /* end li */
         fprintf(ficresvpl,"******\n");              if(mle>=1)
                       printf("\n");
         varpl=matrix(1,nlstate,(int) bage, (int) fage);              fprintf(ficlog,"\n");
         oldm=oldms;savm=savms;              fprintf(ficres,"\n");
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);              numlinepar++;
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);            } /* end k*/
       }          } /*end j */
     }        } /* end i */
       } /* end itimes */
     fclose(ficresvpl);     
       fflush(ficlog);
     /*---------- End : free ----------------*/      fflush(ficres);
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);     
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);      while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
   }  /* mle==-3 arrives here for freeing */        fgets(line, MAXLINE, ficpar);
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);        puts(line);
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);        fputs(line,ficparo);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);      }
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);      ungetc(c,ficpar);
        
     free_matrix(covar,0,NCOVMAX,1,n);      estepm=0;
     free_matrix(matcov,1,npar,1,npar);      fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
     /*free_vector(delti,1,npar);*/      if (estepm==0 || estepm < stepm) estepm=stepm;
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);       if (fage <= 2) {
     free_matrix(agev,1,maxwav,1,imx);        bage = ageminpar;
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);        fage = agemaxpar;
       }
     free_ivector(ncodemax,1,8);     
     free_ivector(Tvar,1,15);      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
     free_ivector(Tprod,1,15);      fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
     free_ivector(Tvaraff,1,15);      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
     free_ivector(Tage,1,15);     
     free_ivector(Tcode,1,100);      while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
   fflush(fichtm);        puts(line);
   fflush(ficgp);        fputs(line,ficparo);
         }
       ungetc(c,ficpar);
   if((nberr >0) || (nbwarn>0)){     
     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);      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(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);      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);
   }else{      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("End of Imach\n");      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,"End of Imach\n");      fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
   }     
   printf("See log file on %s\n",filelog);      while((c=getc(ficpar))=='#' && c!= EOF){
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */        ungetc(c,ficpar);
   (void) gettimeofday(&end_time,&tzp);        fgets(line, MAXLINE, ficpar);
   tm = *localtime(&end_time.tv_sec);        puts(line);
   tmg = *gmtime(&end_time.tv_sec);        fputs(line,ficparo);
   strcpy(strtend,asctime(&tm));      }
   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);       ungetc(c,ficpar);
   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));     
       dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
   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);      fscanf(ficpar,"pop_based=%d\n",&popbased);
   /*  printf("Total time was %d uSec.\n", total_usecs);*/      fprintf(ficparo,"pop_based=%d\n",popbased);  
 /*   if(fileappend(fichtm,optionfilehtm)){ */      fprintf(ficres,"pop_based=%d\n",popbased);  
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);     
   fclose(fichtm);      while((c=getc(ficpar))=='#' && c!= EOF){
   fclose(fichtmcov);        ungetc(c,ficpar);
   fclose(ficgp);        fgets(line, MAXLINE, ficpar);
   fclose(ficlog);        puts(line);
   /*------ End -----------*/        fputs(line,ficparo);
       }
   chdir(path);      ungetc(c,ficpar);
 #ifndef UNIX     
   /*  strcpy(plotcmd,"\""); */      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);
 #endif      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);
   strcpy(plotcmd,pathimach);      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);
   /*strcat(plotcmd,CHARSEPARATOR);*/      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);
   strcat(plotcmd,GNUPLOTPROGRAM);      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);
 #ifndef UNIX      /* day and month of proj2 are not used but only year anproj2.*/
   strcat(plotcmd,".exe");     
   /*  strcat(plotcmd,"\"");*/     
 #endif     
   if(stat(plotcmd,&info)){      /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);      /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
   }     
       replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 #ifndef UNIX      printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
   strcpy(plotcmd,"\"");     
 #endif      printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
   strcat(plotcmd,pathimach);                   model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
   strcat(plotcmd,GNUPLOTPROGRAM);                   jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 #ifndef UNIX       
   strcat(plotcmd,".exe");     /*------------ free_vector  -------------*/
   strcat(plotcmd,"\"");     /*  chdir(path); */
 #endif   
   strcat(plotcmd," ");      free_ivector(wav,1,imx);
   strcat(plotcmd,optionfilegnuplot);      free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
   printf("Starting graphs with: %s",plotcmd);fflush(stdout);      free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
       free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
   if((outcmd=system(plotcmd)) != 0){      free_lvector(num,1,n);
     printf("\n Problem with gnuplot\n");      free_vector(agedc,1,n);
   }      /*free_matrix(covar,0,NCOVMAX,1,n);*/
   printf(" Wait...");      /*free_matrix(covar,1,NCOVMAX,1,n);*/
   while (z[0] != 'q') {      fclose(ficparo);
     /* chdir(path); */      fclose(ficres);
     printf("\nType e to edit output files, g to graph again and q for exiting: ");  
     scanf("%s",z);  
 /*     if (z[0] == 'c') system("./imach"); */      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
     if (z[0] == 'e') {   
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);      strcpy(filerespl,"pl");
       system(optionfilehtm);      strcat(filerespl,fileres);
     }      if((ficrespl=fopen(filerespl,"w"))==NULL) {
     else if (z[0] == 'g') system(plotcmd);        printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     else if (z[0] == 'q') exit(0);        fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
   }      }
   end:      printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
   while (z[0] != 'q') {      fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
     printf("\nType  q for exiting: ");      pstamp(ficrespl);
     scanf("%s",z);      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.108  
changed lines
  Added in v.1.125


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