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

version 1.105, 2006/01/05 20:23:19 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.105  2006/01/05 20:23:19  lievre    Revision 1.125  2006/04/04 15:20:31  lievre
   *** empty log message ***    Errors in calculation of health expectancies. Age was not initialized.
     Forecasting file added.
   Revision 1.104  2005/09/30 16:11:43  lievre  
   (Module): sump fixed, loop imx fixed, and simplifications.    Revision 1.124  2006/03/22 17:13:53  lievre
   (Module): If the status is missing at the last wave but we know    Parameters are printed with %lf instead of %f (more numbers after the comma).
   that the person is alive, then we can code his/her status as -2    The log-likelihood is printed in the log file
   (instead of missing=-1 in earlier versions) and his/her  
   contributions to the likelihood is 1 - Prob of dying from last    Revision 1.123  2006/03/20 10:52:43  brouard
   health status (= 1-p13= p11+p12 in the easiest case of somebody in    * imach.c (Module): <title> changed, corresponds to .htm file
   the healthy state at last known wave). Version is 0.98    name. <head> headers where missing.
   
   Revision 1.103  2005/09/30 15:54:49  lievre    * imach.c (Module): Weights can have a decimal point as for
   (Module): sump fixed, loop imx fixed, and simplifications.    English (a comma might work with a correct LC_NUMERIC environment,
     otherwise the weight is truncated).
   Revision 1.102  2004/09/15 17:31:30  brouard    Modification of warning when the covariates values are not 0 or
   Add the possibility to read data file including tab characters.    1.
     Version 0.98g
   Revision 1.101  2004/09/15 10:38:38  brouard  
   Fix on curr_time    Revision 1.122  2006/03/20 09:45:41  brouard
     (Module): Weights can have a decimal point as for
   Revision 1.100  2004/07/12 18:29:06  brouard    English (a comma might work with a correct LC_NUMERIC environment,
   Add version for Mac OS X. Just define UNIX in Makefile    otherwise the weight is truncated).
     Modification of warning when the covariates values are not 0 or
   Revision 1.99  2004/06/05 08:57:40  brouard    1.
   *** empty log message ***    Version 0.98g
   
   Revision 1.98  2004/05/16 15:05:56  brouard    Revision 1.121  2006/03/16 17:45:01  lievre
   New version 0.97 . First attempt to estimate force of mortality    * imach.c (Module): Comments concerning covariates added
   directly from the data i.e. without the need of knowing the health  
   state at each age, but using a Gompertz model: log u =a + b*age .    * imach.c (Module): refinements in the computation of lli if
   This is the basic analysis of mortality and should be done before any    status=-2 in order to have more reliable computation if stepm is
   other analysis, in order to test if the mortality estimated from the    not 1 month. Version 0.98f
   cross-longitudinal survey is different from the mortality estimated  
   from other sources like vital statistic data.    Revision 1.120  2006/03/16 15:10:38  lievre
     (Module): refinements in the computation of lli if
   The same imach parameter file can be used but the option for mle should be -3.    status=-2 in order to have more reliable computation if stepm is
     not 1 month. Version 0.98f
   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.    Revision 1.119  2006/03/15 17:42:26  brouard
     (Module): Bug if status = -2, the loglikelihood was
   The output is very simple: only an estimate of the intercept and of    computed as likelihood omitting the logarithm. Version O.98e
   the slope with 95% confident intervals.  
     Revision 1.118  2006/03/14 18:20:07  brouard
   Current limitations:    (Module): varevsij Comments added explaining the second
   A) Even if you enter covariates, i.e. with the    table of variances if popbased=1 .
   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   B) There is no computation of Life Expectancy nor Life Table.    (Module): Function pstamp added
     (Module): Version 0.98d
   Revision 1.97  2004/02/20 13:25:42  lievre  
   Version 0.96d. Population forecasting command line is (temporarily)    Revision 1.117  2006/03/14 17:16:22  brouard
   suppressed.    (Module): varevsij Comments added explaining the second
     table of variances if popbased=1 .
   Revision 1.96  2003/07/15 15:38:55  brouard    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is    (Module): Function pstamp added
   rewritten within the same printf. Workaround: many printfs.    (Module): Version 0.98d
   
   Revision 1.95  2003/07/08 07:54:34  brouard    Revision 1.116  2006/03/06 10:29:27  brouard
   * imach.c (Repository):    (Module): Variance-covariance wrong links and
   (Repository): Using imachwizard code to output a more meaningful covariance    varian-covariance of ej. is needed (Saito).
   matrix (cov(a12,c31) instead of numbers.  
     Revision 1.115  2006/02/27 12:17:45  brouard
   Revision 1.94  2003/06/27 13:00:02  brouard    (Module): One freematrix added in mlikeli! 0.98c
   Just cleaning  
     Revision 1.114  2006/02/26 12:57:58  brouard
   Revision 1.93  2003/06/25 16:33:55  brouard    (Module): Some improvements in processing parameter
   (Module): On windows (cygwin) function asctime_r doesn't    filename with strsep.
   exist so I changed back to asctime which exists.  
   (Module): Version 0.96b    Revision 1.113  2006/02/24 14:20:24  brouard
     (Module): Memory leaks checks with valgrind and:
   Revision 1.92  2003/06/25 16:30:45  brouard    datafile was not closed, some imatrix were not freed and on matrix
   (Module): On windows (cygwin) function asctime_r doesn't    allocation too.
   exist so I changed back to asctime which exists.  
     Revision 1.112  2006/01/30 09:55:26  brouard
   Revision 1.91  2003/06/25 15:30:29  brouard    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   * imach.c (Repository): Duplicated warning errors corrected.  
   (Repository): Elapsed time after each iteration is now output. It    Revision 1.111  2006/01/25 20:38:18  brouard
   helps to forecast when convergence will be reached. Elapsed time    (Module): Lots of cleaning and bugs added (Gompertz)
   is stamped in powell.  We created a new html file for the graphs    (Module): Comments can be added in data file. Missing date values
   concerning matrix of covariance. It has extension -cov.htm.    can be a simple dot '.'.
   
   Revision 1.90  2003/06/24 12:34:15  brouard    Revision 1.110  2006/01/25 00:51:50  brouard
   (Module): Some bugs corrected for windows. Also, when    (Module): Lots of cleaning and bugs added (Gompertz)
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.109  2006/01/24 19:37:15  brouard
     (Module): Comments (lines starting with a #) are allowed in data.
   Revision 1.89  2003/06/24 12:30:52  brouard  
   (Module): Some bugs corrected for windows. Also, when    Revision 1.108  2006/01/19 18:05:42  lievre
   mle=-1 a template is output in file "or"mypar.txt with the design    Gnuplot problem appeared...
   of the covariance matrix to be input.    To be fixed
   
   Revision 1.88  2003/06/23 17:54:56  brouard    Revision 1.107  2006/01/19 16:20:37  brouard
   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.    Test existence of gnuplot in imach path
   
   Revision 1.87  2003/06/18 12:26:01  brouard    Revision 1.106  2006/01/19 13:24:36  brouard
   Version 0.96    Some cleaning and links added in html output
   
   Revision 1.86  2003/06/17 20:04:08  brouard    Revision 1.105  2006/01/05 20:23:19  lievre
   (Module): Change position of html and gnuplot routines and added    *** empty log message ***
   routine fileappend.  
     Revision 1.104  2005/09/30 16:11:43  lievre
   Revision 1.85  2003/06/17 13:12:43  brouard    (Module): sump fixed, loop imx fixed, and simplifications.
   * imach.c (Repository): Check when date of death was earlier that    (Module): If the status is missing at the last wave but we know
   current date of interview. It may happen when the death was just    that the person is alive, then we can code his/her status as -2
   prior to the death. In this case, dh was negative and likelihood    (instead of missing=-1 in earlier versions) and his/her
   was wrong (infinity). We still send an "Error" but patch by    contributions to the likelihood is 1 - Prob of dying from last
   assuming that the date of death was just one stepm after the    health status (= 1-p13= p11+p12 in the easiest case of somebody in
   interview.    the healthy state at last known wave). Version is 0.98
   (Repository): Because some people have very long ID (first column)  
   we changed int to long in num[] and we added a new lvector for    Revision 1.103  2005/09/30 15:54:49  lievre
   memory allocation. But we also truncated to 8 characters (left    (Module): sump fixed, loop imx fixed, and simplifications.
   truncation)  
   (Repository): No more line truncation errors.    Revision 1.102  2004/09/15 17:31:30  brouard
     Add the possibility to read data file including tab characters.
   Revision 1.84  2003/06/13 21:44:43  brouard  
   * imach.c (Repository): Replace "freqsummary" at a correct    Revision 1.101  2004/09/15 10:38:38  brouard
   place. It differs from routine "prevalence" which may be called    Fix on curr_time
   many times. Probs is memory consuming and must be used with  
   parcimony.    Revision 1.100  2004/07/12 18:29:06  brouard
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    Add version for Mac OS X. Just define UNIX in Makefile
   
   Revision 1.83  2003/06/10 13:39:11  lievre    Revision 1.99  2004/06/05 08:57:40  brouard
   *** empty log message ***    *** empty log message ***
   
   Revision 1.82  2003/06/05 15:57:20  brouard    Revision 1.98  2004/05/16 15:05:56  brouard
   Add log in  imach.c and  fullversion number is now printed.    New version 0.97 . First attempt to estimate force of mortality
     directly from the data i.e. without the need of knowing the health
 */    state at each age, but using a Gompertz model: log u =a + b*age .
 /*    This is the basic analysis of mortality and should be done before any
    Interpolated Markov Chain    other analysis, in order to test if the mortality estimated from the
     cross-longitudinal survey is different from the mortality estimated
   Short summary of the programme:    from other sources like vital statistic data.
     
   This program computes Healthy Life Expectancies from    The same imach parameter file can be used but the option for mle should be -3.
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a  
   first survey ("cross") where individuals from different ages are    Agnès, who wrote this part of the code, tried to keep most of the
   interviewed on their health status or degree of disability (in the    former routines in order to include the new code within the former code.
   case of a health survey which is our main interest) -2- at least a  
   second wave of interviews ("longitudinal") which measure each change    The output is very simple: only an estimate of the intercept and of
   (if any) in individual health status.  Health expectancies are    the slope with 95% confident intervals.
   computed from the time spent in each health state according to a  
   model. More health states you consider, more time is necessary to reach the    Current limitations:
   Maximum Likelihood of the parameters involved in the model.  The    A) Even if you enter covariates, i.e. with the
   simplest model is the multinomial logistic model where pij is the    model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   probability to be observed in state j at the second wave    B) There is no computation of Life Expectancy nor Life Table.
   conditional to be observed in state i at the first wave. Therefore  
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    Revision 1.97  2004/02/20 13:25:42  lievre
   'age' is age and 'sex' is a covariate. If you want to have a more    Version 0.96d. Population forecasting command line is (temporarily)
   complex model than "constant and age", you should modify the program    suppressed.
   where the markup *Covariates have to be included here again* invites  
   you to do it.  More covariates you add, slower the    Revision 1.96  2003/07/15 15:38:55  brouard
   convergence.    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
     rewritten within the same printf. Workaround: many printfs.
   The advantage of this computer programme, compared to a simple  
   multinomial logistic model, is clear when the delay between waves is not    Revision 1.95  2003/07/08 07:54:34  brouard
   identical for each individual. Also, if a individual missed an    * imach.c (Repository):
   intermediate interview, the information is lost, but taken into    (Repository): Using imachwizard code to output a more meaningful covariance
   account using an interpolation or extrapolation.      matrix (cov(a12,c31) instead of numbers.
   
   hPijx is the probability to be observed in state i at age x+h    Revision 1.94  2003/06/27 13:00:02  brouard
   conditional to the observed state i at age x. The delay 'h' can be    Just cleaning
   split into an exact number (nh*stepm) of unobserved intermediate  
   states. This elementary transition (by month, quarter,    Revision 1.93  2003/06/25 16:33:55  brouard
   semester or year) is modelled as a multinomial logistic.  The hPx    (Module): On windows (cygwin) function asctime_r doesn't
   matrix is simply the matrix product of nh*stepm elementary matrices    exist so I changed back to asctime which exists.
   and the contribution of each individual to the likelihood is simply    (Module): Version 0.96b
   hPijx.  
     Revision 1.92  2003/06/25 16:30:45  brouard
   Also this programme outputs the covariance matrix of the parameters but also    (Module): On windows (cygwin) function asctime_r doesn't
   of the life expectancies. It also computes the stable prevalence.     exist so I changed back to asctime which exists.
     
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    Revision 1.91  2003/06/25 15:30:29  brouard
            Institut national d'études démographiques, Paris.    * imach.c (Repository): Duplicated warning errors corrected.
   This software have been partly granted by Euro-REVES, a concerted action    (Repository): Elapsed time after each iteration is now output. It
   from the European Union.    helps to forecast when convergence will be reached. Elapsed time
   It is copyrighted identically to a GNU software product, ie programme and    is stamped in powell.  We created a new html file for the graphs
   software can be distributed freely for non commercial use. Latest version    concerning matrix of covariance. It has extension -cov.htm.
   can be accessed at http://euroreves.ined.fr/imach .  
     Revision 1.90  2003/06/24 12:34:15  brouard
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    (Module): Some bugs corrected for windows. Also, when
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    mle=-1 a template is output in file "or"mypar.txt with the design
       of the covariance matrix to be input.
   **********************************************************************/  
 /*    Revision 1.89  2003/06/24 12:30:52  brouard
   main    (Module): Some bugs corrected for windows. Also, when
   read parameterfile    mle=-1 a template is output in file "or"mypar.txt with the design
   read datafile    of the covariance matrix to be input.
   concatwav  
   freqsummary    Revision 1.88  2003/06/23 17:54:56  brouard
   if (mle >= 1)    * 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.
     mlikeli  
   print results files    Revision 1.87  2003/06/18 12:26:01  brouard
   if mle==1     Version 0.96
      computes hessian  
   read end of parameter file: agemin, agemax, bage, fage, estepm    Revision 1.86  2003/06/17 20:04:08  brouard
       begin-prev-date,...    (Module): Change position of html and gnuplot routines and added
   open gnuplot file    routine fileappend.
   open html file  
   stable prevalence    Revision 1.85  2003/06/17 13:12:43  brouard
    for age prevalim()    * imach.c (Repository): Check when date of death was earlier that
   h Pij x    current date of interview. It may happen when the death was just
   variance of p varprob    prior to the death. In this case, dh was negative and likelihood
   forecasting if prevfcast==1 prevforecast call prevalence()    was wrong (infinity). We still send an "Error" but patch by
   health expectancies    assuming that the date of death was just one stepm after the
   Variance-covariance of DFLE    interview.
   prevalence()    (Repository): Because some people have very long ID (first column)
    movingaverage()    we changed int to long in num[] and we added a new lvector for
   varevsij()     memory allocation. But we also truncated to 8 characters (left
   if popbased==1 varevsij(,popbased)    truncation)
   total life expectancies    (Repository): No more line truncation errors.
   Variance of stable prevalence  
  end    Revision 1.84  2003/06/13 21:44:43  brouard
 */    * imach.c (Repository): Replace "freqsummary" at a correct
     place. It differs from routine "prevalence" which may be called
     many times. Probs is memory consuming and must be used with
     parcimony.
      Version 0.95a3 (should output exactly the same maximization than 0.8a2)
 #include <math.h>  
 #include <stdio.h>    Revision 1.83  2003/06/10 13:39:11  lievre
 #include <stdlib.h>    *** empty log message ***
 #include <unistd.h>  
     Revision 1.82  2003/06/05 15:57:20  brouard
 /* #include <sys/time.h> */    Add log in  imach.c and  fullversion number is now printed.
 #include <time.h>  
 #include "timeval.h"  */
   /*
 /* #include <libintl.h> */     Interpolated Markov Chain
 /* #define _(String) gettext (String) */  
     Short summary of the programme:
 #define MAXLINE 256   
 #define GNUPLOTPROGRAM "gnuplot"    This program computes Healthy Life Expectancies from
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
 #define FILENAMELENGTH 132    first survey ("cross") where individuals from different ages are
 /*#define DEBUG*/    interviewed on their health status or degree of disability (in the
 /*#define windows*/    case of a health survey which is our main interest) -2- at least a
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */    second wave of interviews ("longitudinal") which measure each change
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */    (if any) in individual health status.  Health expectancies are
     computed from the time spent in each health state according to a
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */    model. More health states you consider, more time is necessary to reach the
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */    Maximum Likelihood of the parameters involved in the model.  The
     simplest model is the multinomial logistic model where pij is the
 #define NINTERVMAX 8    probability to be observed in state j at the second wave
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */    conditional to be observed in state i at the first wave. Therefore
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
 #define NCOVMAX 8 /* Maximum number of covariates */    'age' is age and 'sex' is a covariate. If you want to have a more
 #define MAXN 20000    complex model than "constant and age", you should modify the program
 #define YEARM 12. /* Number of months per year */    where the markup *Covariates have to be included here again* invites
 #define AGESUP 130    you to do it.  More covariates you add, slower the
 #define AGEBASE 40    convergence.
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */  
 #ifdef UNIX    The advantage of this computer programme, compared to a simple
 #define DIRSEPARATOR '/'    multinomial logistic model, is clear when the delay between waves is not
 #define ODIRSEPARATOR '\\'    identical for each individual. Also, if a individual missed an
 #else    intermediate interview, the information is lost, but taken into
 #define DIRSEPARATOR '\\'    account using an interpolation or extrapolation.  
 #define ODIRSEPARATOR '/'  
 #endif    hPijx is the probability to be observed in state i at age x+h
     conditional to the observed state i at age x. The delay 'h' can be
 /* $Id$ */    split into an exact number (nh*stepm) of unobserved intermediate
 /* $State$ */    states. This elementary transition (by month, quarter,
     semester or year) is modelled as a multinomial logistic.  The hPx
 char version[]="Imach version 0.98, September 2005, INED-EUROREVES ";    matrix is simply the matrix product of nh*stepm elementary matrices
 char fullversion[]="$Revision$ $Date$";     and the contribution of each individual to the likelihood is simply
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */    hPijx.
 int nvar;  
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;    Also this programme outputs the covariance matrix of the parameters but also
 int npar=NPARMAX;    of the life expectancies. It also computes the period (stable) prevalence.
 int nlstate=2; /* Number of live states */   
 int ndeath=1; /* Number of dead states */    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */             Institut national d'études démographiques, Paris.
 int popbased=0;    This software have been partly granted by Euro-REVES, a concerted action
     from the European Union.
 int *wav; /* Number of waves for this individuual 0 is possible */    It is copyrighted identically to a GNU software product, ie programme and
 int maxwav; /* Maxim number of waves */    software can be distributed freely for non commercial use. Latest version
 int jmin, jmax; /* min, max spacing between 2 waves */    can be accessed at http://euroreves.ined.fr/imach .
 int gipmx, gsw; /* Global variables on the number of contributions   
                    to the likelihood and the sum of weights (done by funcone)*/    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 int mle, weightopt;    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 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 */    **********************************************************************/
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between  /*
            * wave mi and wave mi+1 is not an exact multiple of stepm. */    main
 double jmean; /* Mean space between 2 waves */    read parameterfile
 double **oldm, **newm, **savm; /* Working pointers to matrices */    read datafile
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */    concatwav
 FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;    freqsummary
 FILE *ficlog, *ficrespow;    if (mle >= 1)
 int globpr; /* Global variable for printing or not */      mlikeli
 double fretone; /* Only one call to likelihood */    print results files
 long ipmx; /* Number of contributions */    if mle==1
 double sw; /* Sum of weights */       computes hessian
 char filerespow[FILENAMELENGTH];    read end of parameter file: agemin, agemax, bage, fage, estepm
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */        begin-prev-date,...
 FILE *ficresilk;    open gnuplot file
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;    open html file
 FILE *ficresprobmorprev;    period (stable) prevalence
 FILE *fichtm, *fichtmcov; /* Html File */     for age prevalim()
 FILE *ficreseij;    h Pij x
 char filerese[FILENAMELENGTH];    variance of p varprob
 FILE  *ficresvij;    forecasting if prevfcast==1 prevforecast call prevalence()
 char fileresv[FILENAMELENGTH];    health expectancies
 FILE  *ficresvpl;    Variance-covariance of DFLE
 char fileresvpl[FILENAMELENGTH];    prevalence()
 char title[MAXLINE];     movingaverage()
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];    varevsij()
 char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH];    if popbased==1 varevsij(,popbased)
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];     total life expectancies
 char command[FILENAMELENGTH];    Variance of period (stable) prevalence
 int  outcmd=0;   end
   */
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  
   
 char filelog[FILENAMELENGTH]; /* Log file */  
 char filerest[FILENAMELENGTH];   
 char fileregp[FILENAMELENGTH];  #include <math.h>
 char popfile[FILENAMELENGTH];  #include <stdio.h>
   #include <stdlib.h>
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  #include <string.h>
   #include <unistd.h>
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  
 struct timezone tzp;  #include <limits.h>
 extern int gettimeofday();  #include <sys/types.h>
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  #include <sys/stat.h>
 long time_value;  #include <errno.h>
 extern long time();  extern int errno;
 char strcurr[80], strfor[80];  
   /* #include <sys/time.h> */
 #define NR_END 1  #include <time.h>
 #define FREE_ARG char*  #include "timeval.h"
 #define FTOL 1.0e-10  
   /* #include <libintl.h> */
 #define NRANSI   /* #define _(String) gettext (String) */
 #define ITMAX 200   
   #define MAXLINE 256
 #define TOL 2.0e-4   
   #define GNUPLOTPROGRAM "gnuplot"
 #define CGOLD 0.3819660   /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 #define ZEPS 1.0e-10   #define FILENAMELENGTH 132
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   
   #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 #define GOLD 1.618034   #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 #define GLIMIT 100.0   
 #define TINY 1.0e-20   #define MAXPARM 30 /* Maximum number of parameters for the optimization */
   #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
 static double maxarg1,maxarg2;  
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  #define NINTERVMAX 8
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
     #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  #define NCOVMAX 8 /* Maximum number of covariates */
 #define rint(a) floor(a+0.5)  #define MAXN 20000
   #define YEARM 12. /* Number of months per year */
 static double sqrarg;  #define AGESUP 130
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  #define AGEBASE 40
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 int agegomp= AGEGOMP;  #ifdef UNIX
   #define DIRSEPARATOR '/'
 int imx;   #define CHARSEPARATOR "/"
 int stepm=1;  #define ODIRSEPARATOR '\\'
 /* Stepm, step in month: minimum step interpolation*/  #else
   #define DIRSEPARATOR '\\'
 int estepm;  #define CHARSEPARATOR "\\"
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  #define ODIRSEPARATOR '/'
   #endif
 int m,nb;  
 long *num;  /* $Id$ */
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  /* $State$ */
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  
 double **pmmij, ***probs;  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
 double *ageexmed,*agecens;  char fullversion[]="$Revision$ $Date$";
 double dateintmean=0;  char strstart[80];
   char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 double *weight;  int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 int **s; /* Status */  int nvar;
 double *agedc, **covar, idx;  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  int npar=NPARMAX;
 double *lsurv, *lpop, *tpop;  int nlstate=2; /* Number of live states */
   int ndeath=1; /* Number of dead states */
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 double ftolhess; /* Tolerance for computing hessian */  int popbased=0;
   
 /**************** split *************************/  int *wav; /* Number of waves for this individuual 0 is possible */
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  int maxwav; /* Maxim number of waves */
 {  int jmin, jmax; /* min, max spacing between 2 waves */
   /* From a file name with full path (either Unix or Windows) we extract the directory (dirc)  int ijmin, ijmax; /* Individuals having jmin and jmax */
      the name of the file (name), its extension only (ext) and its first part of the name (finame)  int gipmx, gsw; /* Global variables on the number of contributions
   */                      to the likelihood and the sum of weights (done by funcone)*/
   char  *ss;                            /* pointer */  int mle, weightopt;
   int   l1, l2;                         /* length counters */  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 */
   l1 = strlen(path );                   /* length of path */  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );             * wave mi and wave mi+1 is not an exact multiple of stepm. */
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  double jmean; /* Mean space between 2 waves */
   if ( ss == NULL ) {                   /* no directory, so use current */  double **oldm, **newm, **savm; /* Working pointers to matrices */
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
     /* get current working directory */  FILE *ficlog, *ficrespow;
     /*    extern  char* getcwd ( char *buf , int len);*/  int globpr; /* Global variable for printing or not */
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  double fretone; /* Only one call to likelihood */
       return( GLOCK_ERROR_GETCWD );  long ipmx; /* Number of contributions */
     }  double sw; /* Sum of weights */
     strcpy( name, path );               /* we've got it */  char filerespow[FILENAMELENGTH];
   } else {                              /* strip direcotry from path */  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
     ss++;                               /* after this, the filename */  FILE *ficresilk;
     l2 = strlen( ss );                  /* length of filename */  FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  FILE *ficresprobmorprev;
     strcpy( name, ss );         /* save file name */  FILE *fichtm, *fichtmcov; /* Html File */
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  FILE *ficreseij;
     dirc[l1-l2] = 0;                    /* add zero */  char filerese[FILENAMELENGTH];
   }  FILE *ficresstdeij;
   l1 = strlen( dirc );                  /* length of directory */  char fileresstde[FILENAMELENGTH];
   /*#ifdef windows  FILE *ficrescveij;
   if ( dirc[l1-1] != '\\' ) { dirc[l1] = '\\'; dirc[l1+1] = 0; }  char filerescve[FILENAMELENGTH];
 #else  FILE  *ficresvij;
   if ( dirc[l1-1] != '/' ) { dirc[l1] = '/'; dirc[l1+1] = 0; }  char fileresv[FILENAMELENGTH];
 #endif  FILE  *ficresvpl;
   */  char fileresvpl[FILENAMELENGTH];
   ss = strrchr( name, '.' );            /* find last / */  char title[MAXLINE];
   if (ss >0){  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
     ss++;  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
     strcpy(ext,ss);                     /* save extension */  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
     l1= strlen( name);  char command[FILENAMELENGTH];
     l2= strlen(ss)+1;  int  outcmd=0;
     strncpy( finame, name, l1-l2);  
     finame[l1-l2]= 0;  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
   }  
   return( 0 );                          /* we're done */  char filelog[FILENAMELENGTH]; /* Log file */
 }  char filerest[FILENAMELENGTH];
   char fileregp[FILENAMELENGTH];
   char popfile[FILENAMELENGTH];
 /******************************************/  
   char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 void replace_back_to_slash(char *s, char*t)  
 {  struct timeval start_time, end_time, curr_time, last_time, forecast_time;
   int i;  struct timezone tzp;
   int lg=0;  extern int gettimeofday();
   i=0;  struct tm tmg, tm, tmf, *gmtime(), *localtime();
   lg=strlen(t);  long time_value;
   for(i=0; i<= lg; i++) {  extern long time();
     (s[i] = t[i]);  char strcurr[80], strfor[80];
     if (t[i]== '\\') s[i]='/';  
   }  char *endptr;
 }  long lval;
   double dval;
 int nbocc(char *s, char occ)  
 {  #define NR_END 1
   int i,j=0;  #define FREE_ARG char*
   int lg=20;  #define FTOL 1.0e-10
   i=0;  
   lg=strlen(s);  #define NRANSI
   for(i=0; i<= lg; i++) {  #define ITMAX 200
   if  (s[i] == occ ) j++;  
   }  #define TOL 2.0e-4
   return j;  
 }  #define CGOLD 0.3819660
   #define ZEPS 1.0e-10
 void cutv(char *u,char *v, char*t, char occ)  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
 {  
   /* cuts string t into u and v where u ends before first occurence of char 'occ'   #define GOLD 1.618034
      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')  #define GLIMIT 100.0
      gives u="abcedf" and v="ghi2j" */  #define TINY 1.0e-20
   int i,lg,j,p=0;  
   i=0;  static double maxarg1,maxarg2;
   for(j=0; j<=strlen(t)-1; j++) {  #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
   }   
   #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
   lg=strlen(t);  #define rint(a) floor(a+0.5)
   for(j=0; j<p; j++) {  
     (u[j] = t[j]);  static double sqrarg;
   }  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
      u[p]='\0';  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
   int agegomp= AGEGOMP;
    for(j=0; j<= lg; j++) {  
     if (j>=(p+1))(v[j-p-1] = t[j]);  int imx;
   }  int stepm=1;
 }  /* Stepm, step in month: minimum step interpolation*/
   
 /********************** nrerror ********************/  int estepm;
   /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
 void nrerror(char error_text[])  
 {  int m,nb;
   fprintf(stderr,"ERREUR ...\n");  long *num;
   fprintf(stderr,"%s\n",error_text);  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
   exit(EXIT_FAILURE);  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 }  double **pmmij, ***probs;
 /*********************** vector *******************/  double *ageexmed,*agecens;
 double *vector(int nl, int nh)  double dateintmean=0;
 {  
   double *v;  double *weight;
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));  int **s; /* Status */
   if (!v) nrerror("allocation failure in vector");  double *agedc, **covar, idx;
   return v-nl+NR_END;  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
 }  double *lsurv, *lpop, *tpop;
   
 /************************ free vector ******************/  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
 void free_vector(double*v, int nl, int nh)  double ftolhess; /* Tolerance for computing hessian */
 {  
   free((FREE_ARG)(v+nl-NR_END));  /**************** split *************************/
 }  static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
   {
 /************************ivector *******************************/    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 int *ivector(long nl,long nh)       the name of the file (name), its extension only (ext) and its first part of the name (finame)
 {    */
   int *v;    char  *ss;                            /* pointer */
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));    int   l1, l2;                         /* length counters */
   if (!v) nrerror("allocation failure in ivector");  
   return v-nl+NR_END;    l1 = strlen(path );                   /* length of path */
 }    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
     ss= strrchr( path, DIRSEPARATOR );            /* find last / */
 /******************free ivector **************************/    if ( ss == NULL ) {                   /* no directory, so determine current directory */
 void free_ivector(int *v, long nl, long nh)      strcpy( name, path );               /* we got the fullname name because no directory */
 {      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
   free((FREE_ARG)(v+nl-NR_END));        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 }      /* get current working directory */
       /*    extern  char* getcwd ( char *buf , int len);*/
 /************************lvector *******************************/      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
 long *lvector(long nl,long nh)        return( GLOCK_ERROR_GETCWD );
 {      }
   long *v;      /* got dirc from getcwd*/
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));      printf(" DIRC = %s \n",dirc);
   if (!v) nrerror("allocation failure in ivector");    } else {                              /* strip direcotry from path */
   return v-nl+NR_END;      ss++;                               /* after this, the filename */
 }      l2 = strlen( ss );                  /* length of filename */
       if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 /******************free lvector **************************/      strcpy( name, ss );         /* save file name */
 void free_lvector(long *v, long nl, long nh)      strncpy( dirc, path, l1 - l2 );     /* now the directory */
 {      dirc[l1-l2] = 0;                    /* add zero */
   free((FREE_ARG)(v+nl-NR_END));      printf(" DIRC2 = %s \n",dirc);
 }    }
     /* We add a separator at the end of dirc if not exists */
 /******************* imatrix *******************************/    l1 = strlen( dirc );                  /* length of directory */
 int **imatrix(long nrl, long nrh, long ncl, long nch)     if( dirc[l1-1] != DIRSEPARATOR ){
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */       dirc[l1] =  DIRSEPARATOR;
 {       dirc[l1+1] = 0;
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;       printf(" DIRC3 = %s \n",dirc);
   int **m;     }
       ss = strrchr( name, '.' );            /* find last / */
   /* allocate pointers to rows */     if (ss >0){
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));       ss++;
   if (!m) nrerror("allocation failure 1 in matrix()");       strcpy(ext,ss);                     /* save extension */
   m += NR_END;       l1= strlen( name);
   m -= nrl;       l2= strlen(ss)+1;
         strncpy( finame, name, l1-l2);
         finame[l1-l2]= 0;
   /* allocate rows and set pointers to them */     }
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));   
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");     return( 0 );                          /* we're done */
   m[nrl] += NR_END;   }
   m[nrl] -= ncl;   
     
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;   /******************************************/
     
   /* return pointer to array of pointers to rows */   void replace_back_to_slash(char *s, char*t)
   return m;   {
 }     int i;
     int lg=0;
 /****************** free_imatrix *************************/    i=0;
 void free_imatrix(m,nrl,nrh,ncl,nch)    lg=strlen(t);
       int **m;    for(i=0; i<= lg; i++) {
       long nch,ncl,nrh,nrl;       (s[i] = t[i]);
      /* free an int matrix allocated by imatrix() */       if (t[i]== '\\') s[i]='/';
 {     }
   free((FREE_ARG) (m[nrl]+ncl-NR_END));   }
   free((FREE_ARG) (m+nrl-NR_END));   
 }   int nbocc(char *s, char occ)
   {
 /******************* matrix *******************************/    int i,j=0;
 double **matrix(long nrl, long nrh, long ncl, long nch)    int lg=20;
 {    i=0;
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;    lg=strlen(s);
   double **m;    for(i=0; i<= lg; i++) {
     if  (s[i] == occ ) j++;
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));    }
   if (!m) nrerror("allocation failure 1 in matrix()");    return j;
   m += NR_END;  }
   m -= nrl;  
   void cutv(char *u,char *v, char*t, char occ)
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  {
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    /* cuts string t into u and v where u ends before first occurence of char 'occ'
   m[nrl] += NR_END;       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
   m[nrl] -= ncl;       gives u="abcedf" and v="ghi2j" */
     int i,lg,j,p=0;
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    i=0;
   return m;    for(j=0; j<=strlen(t)-1; j++) {
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])       if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
    */    }
 }  
     lg=strlen(t);
 /*************************free matrix ************************/    for(j=0; j<p; j++) {
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)      (u[j] = t[j]);
 {    }
   free((FREE_ARG)(m[nrl]+ncl-NR_END));       u[p]='\0';
   free((FREE_ARG)(m+nrl-NR_END));  
 }     for(j=0; j<= lg; j++) {
       if (j>=(p+1))(v[j-p-1] = t[j]);
 /******************* ma3x *******************************/    }
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)  }
 {  
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;  /********************** nrerror ********************/
   double ***m;  
   void nrerror(char error_text[])
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  {
   if (!m) nrerror("allocation failure 1 in matrix()");    fprintf(stderr,"ERREUR ...\n");
   m += NR_END;    fprintf(stderr,"%s\n",error_text);
   m -= nrl;    exit(EXIT_FAILURE);
   }
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  /*********************** vector *******************/
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  double *vector(int nl, int nh)
   m[nrl] += NR_END;  {
   m[nrl] -= ncl;    double *v;
     v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    if (!v) nrerror("allocation failure in vector");
     return 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()");  
   m[nrl][ncl] += NR_END;  /************************ free vector ******************/
   m[nrl][ncl] -= nll;  void free_vector(double*v, int nl, int nh)
   for (j=ncl+1; j<=nch; j++)   {
     m[nrl][j]=m[nrl][j-1]+nlay;    free((FREE_ARG)(v+nl-NR_END));
     }
   for (i=nrl+1; i<=nrh; i++) {  
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;  /************************ivector *******************************/
     for (j=ncl+1; j<=nch; j++)   int *ivector(long nl,long nh)
       m[i][j]=m[i][j-1]+nlay;  {
   }    int *v;
   return m;     v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])    if (!v) nrerror("allocation failure in ivector");
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)    return v-nl+NR_END;
   */  }
 }  
   /******************free ivector **************************/
 /*************************free ma3x ************************/  void free_ivector(int *v, long nl, long nh)
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)  {
 {    free((FREE_ARG)(v+nl-NR_END));
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));  }
   free((FREE_ARG)(m[nrl]+ncl-NR_END));  
   free((FREE_ARG)(m+nrl-NR_END));  /************************lvector *******************************/
 }  long *lvector(long nl,long nh)
   {
 /*************** function subdirf ***********/    long *v;
 char *subdirf(char fileres[])    v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 {    if (!v) nrerror("allocation failure in ivector");
   /* Caution optionfilefiname is hidden */    return v-nl+NR_END;
   strcpy(tmpout,optionfilefiname);  }
   strcat(tmpout,"/"); /* Add to the right */  
   strcat(tmpout,fileres);  /******************free lvector **************************/
   return tmpout;  void free_lvector(long *v, long nl, long nh)
 }  {
     free((FREE_ARG)(v+nl-NR_END));
 /*************** function subdirf2 ***********/  }
 char *subdirf2(char fileres[], char *preop)  
 {  /******************* imatrix *******************************/
     int **imatrix(long nrl, long nrh, long ncl, long nch)
   /* Caution optionfilefiname is hidden */       /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
   strcpy(tmpout,optionfilefiname);  {
   strcat(tmpout,"/");    long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
   strcat(tmpout,preop);    int **m;
   strcat(tmpout,fileres);   
   return tmpout;    /* allocate pointers to rows */
 }    m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
     if (!m) nrerror("allocation failure 1 in matrix()");
 /*************** function subdirf3 ***********/    m += NR_END;
 char *subdirf3(char fileres[], char *preop, char *preop2)    m -= nrl;
 {   
      
   /* Caution optionfilefiname is hidden */    /* allocate rows and set pointers to them */
   strcpy(tmpout,optionfilefiname);    m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
   strcat(tmpout,"/");    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   strcat(tmpout,preop);    m[nrl] += NR_END;
   strcat(tmpout,preop2);    m[nrl] -= ncl;
   strcat(tmpout,fileres);   
   return tmpout;    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
 }   
     /* return pointer to array of pointers to rows */
 /***************** f1dim *************************/    return m;
 extern int ncom;   }
 extern double *pcom,*xicom;  
 extern double (*nrfunc)(double []);   /****************** free_imatrix *************************/
    void free_imatrix(m,nrl,nrh,ncl,nch)
 double f1dim(double x)         int **m;
 {         long nch,ncl,nrh,nrl;
   int j;        /* free an int matrix allocated by imatrix() */
   double f;  {
   double *xt;     free((FREE_ARG) (m[nrl]+ncl-NR_END));
      free((FREE_ARG) (m+nrl-NR_END));
   xt=vector(1,ncom);   }
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];   
   f=(*nrfunc)(xt);   /******************* matrix *******************************/
   free_vector(xt,1,ncom);   double **matrix(long nrl, long nrh, long ncl, long nch)
   return f;   {
 }     long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
     double **m;
 /*****************brent *************************/  
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)     m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 {     if (!m) nrerror("allocation failure 1 in matrix()");
   int iter;     m += NR_END;
   double a,b,d,etemp;    m -= nrl;
   double fu,fv,fw,fx;  
   double ftemp;    m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   double p,q,r,tol1,tol2,u,v,w,x,xm;     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   double e=0.0;     m[nrl] += NR_END;
      m[nrl] -= ncl;
   a=(ax < cx ? ax : cx);   
   b=(ax > cx ? ax : cx);     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   x=w=v=bx;     return m;
   fw=fv=fx=(*f)(x);     /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
   for (iter=1;iter<=ITMAX;iter++) {      */
     xm=0.5*(a+b);   }
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);   
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/  /*************************free matrix ************************/
     printf(".");fflush(stdout);  void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
     fprintf(ficlog,".");fflush(ficlog);  {
 #ifdef DEBUG    free((FREE_ARG)(m[nrl]+ncl-NR_END));
     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);    free((FREE_ARG)(m+nrl-NR_END));
     fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);  }
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */  
 #endif  /******************* ma3x *******************************/
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){   double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
       *xmin=x;   {
       return fx;     long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
     }     double ***m;
     ftemp=fu;  
     if (fabs(e) > tol1) {     m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
       r=(x-w)*(fx-fv);     if (!m) nrerror("allocation failure 1 in matrix()");
       q=(x-v)*(fx-fw);     m += NR_END;
       p=(x-v)*q-(x-w)*r;     m -= nrl;
       q=2.0*(q-r);   
       if (q > 0.0) p = -p;     m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
       q=fabs(q);     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
       etemp=e;     m[nrl] += NR_END;
       e=d;     m[nrl] -= ncl;
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))   
         d=CGOLD*(e=(x >= xm ? a-x : b-x));     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
       else {   
         d=p/q;     m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
         u=x+d;     if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
         if (u-a < tol2 || b-u < tol2)     m[nrl][ncl] += NR_END;
           d=SIGN(tol1,xm-x);     m[nrl][ncl] -= nll;
       }     for (j=ncl+1; j<=nch; j++)
     } else {       m[nrl][j]=m[nrl][j-1]+nlay;
       d=CGOLD*(e=(x >= xm ? a-x : b-x));    
     }     for (i=nrl+1; i<=nrh; i++) {
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));       m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
     fu=(*f)(u);       for (j=ncl+1; j<=nch; j++)
     if (fu <= fx) {         m[i][j]=m[i][j-1]+nlay;
       if (u >= x) a=x; else b=x;     }
       SHFT(v,w,x,u)     return m;
         SHFT(fv,fw,fx,fu)     /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
         } else {              &(m[i][j][k]) <=> *((*(m+i) + j)+k)
           if (u < x) a=u; else b=u;     */
           if (fu <= fw || w == x) {   }
             v=w;   
             w=u;   /*************************free ma3x ************************/
             fv=fw;   void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
             fw=fu;   {
           } else if (fu <= fv || v == x || v == w) {     free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
             v=u;     free((FREE_ARG)(m[nrl]+ncl-NR_END));
             fv=fu;     free((FREE_ARG)(m+nrl-NR_END));
           }   }
         }   
   }   /*************** function subdirf ***********/
   nrerror("Too many iterations in brent");   char *subdirf(char fileres[])
   *xmin=x;   {
   return fx;     /* Caution optionfilefiname is hidden */
 }     strcpy(tmpout,optionfilefiname);
     strcat(tmpout,"/"); /* Add to the right */
 /****************** mnbrak ***********************/    strcat(tmpout,fileres);
     return tmpout;
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,   }
             double (*func)(double))   
 {   /*************** function subdirf2 ***********/
   double ulim,u,r,q, dum;  char *subdirf2(char fileres[], char *preop)
   double fu;   {
     
   *fa=(*func)(*ax);     /* Caution optionfilefiname is hidden */
   *fb=(*func)(*bx);     strcpy(tmpout,optionfilefiname);
   if (*fb > *fa) {     strcat(tmpout,"/");
     SHFT(dum,*ax,*bx,dum)     strcat(tmpout,preop);
       SHFT(dum,*fb,*fa,dum)     strcat(tmpout,fileres);
       }     return tmpout;
   *cx=(*bx)+GOLD*(*bx-*ax);   }
   *fc=(*func)(*cx);   
   while (*fb > *fc) {   /*************** function subdirf3 ***********/
     r=(*bx-*ax)*(*fb-*fc);   char *subdirf3(char fileres[], char *preop, char *preop2)
     q=(*bx-*cx)*(*fb-*fa);   {
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/    
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));     /* Caution optionfilefiname is hidden */
     ulim=(*bx)+GLIMIT*(*cx-*bx);     strcpy(tmpout,optionfilefiname);
     if ((*bx-u)*(u-*cx) > 0.0) {     strcat(tmpout,"/");
       fu=(*func)(u);     strcat(tmpout,preop);
     } else if ((*cx-u)*(u-ulim) > 0.0) {     strcat(tmpout,preop2);
       fu=(*func)(u);     strcat(tmpout,fileres);
       if (fu < *fc) {     return tmpout;
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))   }
           SHFT(*fb,*fc,fu,(*func)(u))   
           }   /***************** f1dim *************************/
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {   extern int ncom;
       u=ulim;   extern double *pcom,*xicom;
       fu=(*func)(u);   extern double (*nrfunc)(double []);
     } else {    
       u=(*cx)+GOLD*(*cx-*bx);   double f1dim(double x)
       fu=(*func)(u);   {
     }     int j;
     SHFT(*ax,*bx,*cx,u)     double f;
       SHFT(*fa,*fb,*fc,fu)     double *xt;
       }    
 }     xt=vector(1,ncom);
     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
 /*************** linmin ************************/    f=(*nrfunc)(xt);
     free_vector(xt,1,ncom);
 int ncom;     return f;
 double *pcom,*xicom;  }
 double (*nrfunc)(double []);   
    /*****************brent *************************/
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))   double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
 {   {
   double brent(double ax, double bx, double cx,     int iter;
                double (*f)(double), double tol, double *xmin);     double a,b,d,etemp;
   double f1dim(double x);     double fu,fv,fw,fx;
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,     double ftemp;
               double *fc, double (*func)(double));     double p,q,r,tol1,tol2,u,v,w,x,xm;
   int j;     double e=0.0;
   double xx,xmin,bx,ax;    
   double fx,fb,fa;    a=(ax < cx ? ax : cx);
      b=(ax > cx ? ax : cx);
   ncom=n;     x=w=v=bx;
   pcom=vector(1,n);     fw=fv=fx=(*f)(x);
   xicom=vector(1,n);     for (iter=1;iter<=ITMAX;iter++) {
   nrfunc=func;       xm=0.5*(a+b);
   for (j=1;j<=n;j++) {       tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
     pcom[j]=p[j];       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
     xicom[j]=xi[j];       printf(".");fflush(stdout);
   }       fprintf(ficlog,".");fflush(ficlog);
   ax=0.0;   #ifdef DEBUG
   xx=1.0;       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);
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);       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);
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 #ifdef DEBUG  #endif
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);      if (fabs(x-xm) <= (tol2-0.5*(b-a))){
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);        *xmin=x;
 #endif        return fx;
   for (j=1;j<=n;j++) {       }
     xi[j] *= xmin;       ftemp=fu;
     p[j] += xi[j];       if (fabs(e) > tol1) {
   }         r=(x-w)*(fx-fv);
   free_vector(xicom,1,n);         q=(x-v)*(fx-fw);
   free_vector(pcom,1,n);         p=(x-v)*q-(x-w)*r;
 }         q=2.0*(q-r);
         if (q > 0.0) p = -p;
 char *asc_diff_time(long time_sec, char ascdiff[])        q=fabs(q);
 {        etemp=e;
   long sec_left, days, hours, minutes;        e=d;
   days = (time_sec) / (60*60*24);        if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
   sec_left = (time_sec) % (60*60*24);          d=CGOLD*(e=(x >= xm ? a-x : b-x));
   hours = (sec_left) / (60*60) ;        else {
   sec_left = (sec_left) %(60*60);          d=p/q;
   minutes = (sec_left) /60;          u=x+d;
   sec_left = (sec_left) % (60);          if (u-a < tol2 || b-u < tol2)
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);              d=SIGN(tol1,xm-x);
   return ascdiff;        }
 }      } else {
         d=CGOLD*(e=(x >= xm ? a-x : b-x));
 /*************** powell ************************/      }
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
             double (*func)(double []))       fu=(*f)(u);
 {       if (fu <= fx) {
   void linmin(double p[], double xi[], int n, double *fret,         if (u >= x) a=x; else b=x;
               double (*func)(double []));         SHFT(v,w,x,u)
   int i,ibig,j;           SHFT(fv,fw,fx,fu)
   double del,t,*pt,*ptt,*xit;          } else {
   double fp,fptt;            if (u < x) a=u; else b=u;
   double *xits;            if (fu <= fw || w == x) {
   int niterf, itmp;              v=w;
               w=u;
   pt=vector(1,n);               fv=fw;
   ptt=vector(1,n);               fw=fu;
   xit=vector(1,n);             } else if (fu <= fv || v == x || v == w) {
   xits=vector(1,n);               v=u;
   *fret=(*func)(p);               fv=fu;
   for (j=1;j<=n;j++) pt[j]=p[j];             }
   for (*iter=1;;++(*iter)) {           }
     fp=(*fret);     }
     ibig=0;     nrerror("Too many iterations in brent");
     del=0.0;     *xmin=x;
     last_time=curr_time;    return fx;
     (void) gettimeofday(&curr_time,&tzp);  }
     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);  
     /*    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);  /****************** mnbrak ***********************/
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);  
     */  void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
    for (i=1;i<=n;i++) {              double (*func)(double))
       printf(" %d %.12f",i, p[i]);  {
       fprintf(ficlog," %d %.12lf",i, p[i]);    double ulim,u,r,q, dum;
       fprintf(ficrespow," %.12lf", p[i]);    double fu;
     }   
     printf("\n");    *fa=(*func)(*ax);
     fprintf(ficlog,"\n");    *fb=(*func)(*bx);
     fprintf(ficrespow,"\n");fflush(ficrespow);    if (*fb > *fa) {
     if(*iter <=3){      SHFT(dum,*ax,*bx,dum)
       tm = *localtime(&curr_time.tv_sec);        SHFT(dum,*fb,*fa,dum)
       strcpy(strcurr,asctime(&tm));        }
 /*       asctime_r(&tm,strcurr); */    *cx=(*bx)+GOLD*(*bx-*ax);
       forecast_time=curr_time;     *fc=(*func)(*cx);
       itmp = strlen(strcurr);    while (*fb > *fc) {
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */      r=(*bx-*ax)*(*fb-*fc);
         strcurr[itmp-1]='\0';      q=(*bx-*cx)*(*fb-*fa);
       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);      u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);        (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
       for(niterf=10;niterf<=30;niterf+=10){      ulim=(*bx)+GLIMIT*(*cx-*bx);
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);      if ((*bx-u)*(u-*cx) > 0.0) {
         tmf = *localtime(&forecast_time.tv_sec);        fu=(*func)(u);
 /*      asctime_r(&tmf,strfor); */      } else if ((*cx-u)*(u-ulim) > 0.0) {
         strcpy(strfor,asctime(&tmf));        fu=(*func)(u);
         itmp = strlen(strfor);        if (fu < *fc) {
         if(strfor[itmp-1]=='\n')          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
         strfor[itmp-1]='\0';            SHFT(*fb,*fc,fu,(*func)(u))
         printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);            }
         fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);      } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
       }        u=ulim;
     }        fu=(*func)(u);
     for (i=1;i<=n;i++) {       } else {
       for (j=1;j<=n;j++) xit[j]=xi[j][i];         u=(*cx)+GOLD*(*cx-*bx);
       fptt=(*fret);         fu=(*func)(u);
 #ifdef DEBUG      }
       printf("fret=%lf \n",*fret);      SHFT(*ax,*bx,*cx,u)
       fprintf(ficlog,"fret=%lf \n",*fret);        SHFT(*fa,*fb,*fc,fu)
 #endif        }
       printf("%d",i);fflush(stdout);  }
       fprintf(ficlog,"%d",i);fflush(ficlog);  
       linmin(p,xit,n,fret,func);   /*************** linmin ************************/
       if (fabs(fptt-(*fret)) > del) {   
         del=fabs(fptt-(*fret));   int ncom;
         ibig=i;   double *pcom,*xicom;
       }   double (*nrfunc)(double []);
 #ifdef DEBUG   
       printf("%d %.12e",i,(*fret));  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
       fprintf(ficlog,"%d %.12e",i,(*fret));  {
       for (j=1;j<=n;j++) {    double brent(double ax, double bx, double cx,
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);                 double (*f)(double), double tol, double *xmin);
         printf(" x(%d)=%.12e",j,xit[j]);    double f1dim(double x);
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
       }                double *fc, double (*func)(double));
       for(j=1;j<=n;j++) {    int j;
         printf(" p=%.12e",p[j]);    double xx,xmin,bx,ax;
         fprintf(ficlog," p=%.12e",p[j]);    double fx,fb,fa;
       }   
       printf("\n");    ncom=n;
       fprintf(ficlog,"\n");    pcom=vector(1,n);
 #endif    xicom=vector(1,n);
     }     nrfunc=func;
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {    for (j=1;j<=n;j++) {
 #ifdef DEBUG      pcom[j]=p[j];
       int k[2],l;      xicom[j]=xi[j];
       k[0]=1;    }
       k[1]=-1;    ax=0.0;
       printf("Max: %.12e",(*func)(p));    xx=1.0;
       fprintf(ficlog,"Max: %.12e",(*func)(p));    mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
       for (j=1;j<=n;j++) {    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
         printf(" %.12e",p[j]);  #ifdef DEBUG
         fprintf(ficlog," %.12e",p[j]);    printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
       }    fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
       printf("\n");  #endif
       fprintf(ficlog,"\n");    for (j=1;j<=n;j++) {
       for(l=0;l<=1;l++) {      xi[j] *= xmin;
         for (j=1;j<=n;j++) {      p[j] += xi[j];
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];    }
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);    free_vector(xicom,1,n);
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);    free_vector(pcom,1,n);
         }  }
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));  
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));  char *asc_diff_time(long time_sec, char ascdiff[])
       }  {
 #endif    long sec_left, days, hours, minutes;
     days = (time_sec) / (60*60*24);
     sec_left = (time_sec) % (60*60*24);
       free_vector(xit,1,n);     hours = (sec_left) / (60*60) ;
       free_vector(xits,1,n);     sec_left = (sec_left) %(60*60);
       free_vector(ptt,1,n);     minutes = (sec_left) /60;
       free_vector(pt,1,n);     sec_left = (sec_left) % (60);
       return;     sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
     }     return ascdiff;
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");   }
     for (j=1;j<=n;j++) {   
       ptt[j]=2.0*p[j]-pt[j];   /*************** powell ************************/
       xit[j]=p[j]-pt[j];   void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
       pt[j]=p[j];               double (*func)(double []))
     }   {
     fptt=(*func)(ptt);     void linmin(double p[], double xi[], int n, double *fret,
     if (fptt < fp) {                 double (*func)(double []));
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);     int i,ibig,j;
       if (t < 0.0) {     double del,t,*pt,*ptt,*xit;
         linmin(p,xit,n,fret,func);     double fp,fptt;
         for (j=1;j<=n;j++) {     double *xits;
           xi[j][ibig]=xi[j][n];     int niterf, itmp;
           xi[j][n]=xit[j];   
         }    pt=vector(1,n);
 #ifdef DEBUG    ptt=vector(1,n);
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);    xit=vector(1,n);
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);    xits=vector(1,n);
         for(j=1;j<=n;j++){    *fret=(*func)(p);
           printf(" %.12e",xit[j]);    for (j=1;j<=n;j++) pt[j]=p[j];
           fprintf(ficlog," %.12e",xit[j]);    for (*iter=1;;++(*iter)) {
         }      fp=(*fret);
         printf("\n");      ibig=0;
         fprintf(ficlog,"\n");      del=0.0;
 #endif      last_time=curr_time;
       }      (void) gettimeofday(&curr_time,&tzp);
     }       printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
   }       fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
 }   /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
      for (i=1;i<=n;i++) {
 /**** Prevalence limit (stable prevalence)  ****************/        printf(" %d %.12f",i, p[i]);
         fprintf(ficlog," %d %.12lf",i, p[i]);
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)        fprintf(ficrespow," %.12lf", p[i]);
 {      }
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit      printf("\n");
      matrix by transitions matrix until convergence is reached */      fprintf(ficlog,"\n");
       fprintf(ficrespow,"\n");fflush(ficrespow);
   int i, ii,j,k;      if(*iter <=3){
   double min, max, maxmin, maxmax,sumnew=0.;        tm = *localtime(&curr_time.tv_sec);
   double **matprod2();        strcpy(strcurr,asctime(&tm));
   double **out, cov[NCOVMAX], **pmij();  /*       asctime_r(&tm,strcurr); */
   double **newm;        forecast_time=curr_time;
   double agefin, delaymax=50 ; /* Max number of years to converge */        itmp = strlen(strcurr);
         if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
   for (ii=1;ii<=nlstate+ndeath;ii++)          strcurr[itmp-1]='\0';
     for (j=1;j<=nlstate+ndeath;j++){        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);        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);
    cov[1]=1.;          tmf = *localtime(&forecast_time.tv_sec);
    /*      asctime_r(&tmf,strfor); */
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */          strcpy(strfor,asctime(&tmf));
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){          itmp = strlen(strfor);
     newm=savm;          if(strfor[itmp-1]=='\n')
     /* Covariates have to be included here again */          strfor[itmp-1]='\0';
      cov[2]=agefin;          printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
             fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
       for (k=1; k<=cptcovn;k++) {        }
         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 (i=1;i<=n;i++) {
       }        for (j=1;j<=n;j++) xit[j]=xi[j][i];
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];        fptt=(*fret);
       for (k=1; k<=cptcovprod;k++)  #ifdef DEBUG
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        printf("fret=%lf \n",*fret);
         fprintf(ficlog,"fret=%lf \n",*fret);
       /*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("%d",i);fflush(stdout);
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/        fprintf(ficlog,"%d",i);fflush(ficlog);
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);        linmin(p,xit,n,fret,func);
         if (fabs(fptt-(*fret)) > del) {
     savm=oldm;          del=fabs(fptt-(*fret));
     oldm=newm;          ibig=i;
     maxmax=0.;        }
     for(j=1;j<=nlstate;j++){  #ifdef DEBUG
       min=1.;        printf("%d %.12e",i,(*fret));
       max=0.;        fprintf(ficlog,"%d %.12e",i,(*fret));
       for(i=1; i<=nlstate; i++) {        for (j=1;j<=n;j++) {
         sumnew=0;          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];          printf(" x(%d)=%.12e",j,xit[j]);
         prlim[i][j]= newm[i][j]/(1-sumnew);          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
         max=FMAX(max,prlim[i][j]);        }
         min=FMIN(min,prlim[i][j]);        for(j=1;j<=n;j++) {
       }          printf(" p=%.12e",p[j]);
       maxmin=max-min;          fprintf(ficlog," p=%.12e",p[j]);
       maxmax=FMAX(maxmax,maxmin);        }
     }        printf("\n");
     if(maxmax < ftolpl){        fprintf(ficlog,"\n");
       return prlim;  #endif
     }      }
   }      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 }  #ifdef DEBUG
         int k[2],l;
 /*************** transition probabilities ***************/         k[0]=1;
         k[1]=-1;
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )        printf("Max: %.12e",(*func)(p));
 {        fprintf(ficlog,"Max: %.12e",(*func)(p));
   double s1, s2;        for (j=1;j<=n;j++) {
   /*double t34;*/          printf(" %.12e",p[j]);
   int i,j,j1, nc, ii, jj;          fprintf(ficlog," %.12e",p[j]);
         }
     for(i=1; i<= nlstate; i++){        printf("\n");
       for(j=1; j<i;j++){        fprintf(ficlog,"\n");
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){        for(l=0;l<=1;l++) {
           /*s2 += param[i][j][nc]*cov[nc];*/          for (j=1;j<=n;j++) {
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];            ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */            printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
         }            fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
         ps[i][j]=s2;          }
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */          printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       }          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       for(j=i+1; j<=nlstate+ndeath;j++){        }
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){  #endif
           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); */  
         }        free_vector(xit,1,n);
         ps[i][j]=s2;        free_vector(xits,1,n);
       }        free_vector(ptt,1,n);
     }        free_vector(pt,1,n);
     /*ps[3][2]=1;*/        return;
           }
     for(i=1; i<= nlstate; i++){      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
       s1=0;      for (j=1;j<=n;j++) {
       for(j=1; j<i; j++)        ptt[j]=2.0*p[j]-pt[j];
         s1+=exp(ps[i][j]);        xit[j]=p[j]-pt[j];
       for(j=i+1; j<=nlstate+ndeath; j++)        pt[j]=p[j];
         s1+=exp(ps[i][j]);      }
       ps[i][i]=1./(s1+1.);      fptt=(*func)(ptt);
       for(j=1; j<i; j++)      if (fptt < fp) {
         ps[i][j]= exp(ps[i][j])*ps[i][i];        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
       for(j=i+1; j<=nlstate+ndeath; j++)        if (t < 0.0) {
         ps[i][j]= exp(ps[i][j])*ps[i][i];          linmin(p,xit,n,fret,func);
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */          for (j=1;j<=n;j++) {
     } /* end i */            xi[j][ibig]=xi[j][n];
                 xi[j][n]=xit[j];
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){          }
       for(jj=1; jj<= nlstate+ndeath; jj++){  #ifdef DEBUG
         ps[ii][jj]=0;          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
         ps[ii][ii]=1;          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
       }          for(j=1;j<=n;j++){
     }            printf(" %.12e",xit[j]);
                 fprintf(ficlog," %.12e",xit[j]);
           }
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */          printf("\n");
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */          fprintf(ficlog,"\n");
 /*         printf("ddd %lf ",ps[ii][jj]); */  #endif
 /*       } */        }
 /*       printf("\n "); */      }
 /*        } */    }
 /*        printf("\n ");printf("%lf ",cov[2]); */  }
        /*  
       for(i=1; i<= npar; i++) printf("%f ",x[i]);  /**** Prevalence limit (stable or period prevalence)  ****************/
       goto end;*/  
     return ps;  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 }  {
     /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 /**************** Product of 2 matrices ******************/       matrix by transitions matrix until convergence is reached */
   
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)    int i, ii,j,k;
 {    double min, max, maxmin, maxmax,sumnew=0.;
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times    double **matprod2();
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */    double **out, cov[NCOVMAX], **pmij();
   /* in, b, out are matrice of pointers which should have been initialized     double **newm;
      before: only the contents of out is modified. The function returns    double agefin, delaymax=50 ; /* Max number of years to converge */
      a pointer to pointers identical to out */  
   long i, j, k;    for (ii=1;ii<=nlstate+ndeath;ii++)
   for(i=nrl; i<= nrh; i++)      for (j=1;j<=nlstate+ndeath;j++){
     for(k=ncolol; k<=ncoloh; k++)        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       for(j=ncl,out[i][k]=0.; j<=nch; j++)      }
         out[i][k] +=in[i][j]*b[j][k];  
      cov[1]=1.;
   return out;   
 }   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
     for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
       newm=savm;
 /************* Higher Matrix Product ***************/      /* Covariates have to be included here again */
        cov[2]=agefin;
 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<=cptcovn;k++) {
   /* Computes the transition matrix starting at age 'age' over           cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
      'nhstepm*hstepm*stepm' months (i.e. until          /*      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]]);*/
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying         }
      nhstepm*hstepm matrices.         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step         for (k=1; k<=cptcovprod;k++)
      (typically every 2 years instead of every month which is too big           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
      for the memory).  
      Model is determined by parameters x and covariates have to be         /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
      included manually here.         /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
         /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
      */      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
   
   int i, j, d, h, k;      savm=oldm;
   double **out, cov[NCOVMAX];      oldm=newm;
   double **newm;      maxmax=0.;
       for(j=1;j<=nlstate;j++){
   /* Hstepm could be zero and should return the unit matrix */        min=1.;
   for (i=1;i<=nlstate+ndeath;i++)        max=0.;
     for (j=1;j<=nlstate+ndeath;j++){        for(i=1; i<=nlstate; i++) {
       oldm[i][j]=(i==j ? 1.0 : 0.0);          sumnew=0;
       po[i][j][0]=(i==j ? 1.0 : 0.0);          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
     }          prlim[i][j]= newm[i][j]/(1-sumnew);
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */          max=FMAX(max,prlim[i][j]);
   for(h=1; h <=nhstepm; h++){          min=FMIN(min,prlim[i][j]);
     for(d=1; d <=hstepm; d++){        }
       newm=savm;        maxmin=max-min;
       /* Covariates have to be included here again */        maxmax=FMAX(maxmax,maxmin);
       cov[1]=1.;      }
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;      if(maxmax < ftolpl){
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];        return prlim;
       for (k=1; k<=cptcovage;k++)      }
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];    }
       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]]];  
   /*************** transition probabilities ***************/
   
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
       /*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,     double s1, s2;
                    pmij(pmmij,cov,ncovmodel,x,nlstate));    /*double t34;*/
       savm=oldm;    int i,j,j1, nc, ii, jj;
       oldm=newm;  
     }      for(i=1; i<= nlstate; i++){
     for(i=1; i<=nlstate+ndeath; i++)        for(j=1; j<i;j++){
       for(j=1;j<=nlstate+ndeath;j++) {          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
         po[i][j][h]=newm[i][j];            /*s2 += param[i][j][nc]*cov[nc];*/
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
          */  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
       }          }
   } /* end h */          ps[i][j]=s2;
   return po;  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
 }        }
         for(j=i+1; j<=nlstate+ndeath;j++){
           for (nc=1, s2=0.;nc <=ncovmodel; nc++){
 /*************** log-likelihood *************/            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
 double func( double *x)  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
 {          }
   int i, ii, j, k, mi, d, kk;          ps[i][j]=s2;
   double l, ll[NLSTATEMAX], cov[NCOVMAX];        }
   double **out;      }
   double sw; /* Sum of weights */      /*ps[3][2]=1;*/
   double lli; /* Individual log likelihood */     
   int s1, s2;      for(i=1; i<= nlstate; i++){
   double bbh, survp;        s1=0;
   long ipmx;        for(j=1; j<i; j++)
   /*extern weight */          s1+=exp(ps[i][j]);
   /* We are differentiating ll according to initial status */        for(j=i+1; j<=nlstate+ndeath; j++)
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/          s1+=exp(ps[i][j]);
   /*for(i=1;i<imx;i++)         ps[i][i]=1./(s1+1.);
     printf(" %d\n",s[4][i]);        for(j=1; j<i; j++)
   */          ps[i][j]= exp(ps[i][j])*ps[i][i];
   cov[1]=1.;        for(j=i+1; j<=nlstate+ndeath; j++)
           ps[i][j]= exp(ps[i][j])*ps[i][i];
   for(k=1; k<=nlstate; k++) ll[k]=0.;        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
       } /* end i */
   if(mle==1){     
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){      for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];        for(jj=1; jj<= nlstate+ndeath; jj++){
       for(mi=1; mi<= wav[i]-1; mi++){          ps[ii][jj]=0;
         for (ii=1;ii<=nlstate+ndeath;ii++)          ps[ii][ii]=1;
           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);     
           }  
         for(d=0; d<dh[mi][i]; d++){  /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
           newm=savm;  /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;  /*         printf("ddd %lf ",ps[ii][jj]); */
           for (kk=1; kk<=cptcovage;kk++) {  /*       } */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];  /*       printf("\n "); */
           }  /*        } */
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,  /*        printf("\n ");printf("%lf ",cov[2]); */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));         /*
           savm=oldm;        for(i=1; i<= npar; i++) printf("%f ",x[i]);
           oldm=newm;        goto end;*/
         } /* end mult */      return ps;
         }
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */  
         /* But now since version 0.9 we anticipate for bias at large stepm.  /**************** Product of 2 matrices ******************/
          * If stepm is larger than one month (smallest stepm) and if the exact delay   
          * (in months) between two waves is not a multiple of stepm, we rounded to   double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
          * the nearest (and in case of equal distance, to the lowest) interval but now  {
          * we keep into memory the bias bh[mi][i] and also the previous matrix product    /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the       b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
          * probability in order to take into account the bias as a fraction of the way    /* in, b, out are matrice of pointers which should have been initialized
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies       before: only the contents of out is modified. The function returns
          * -stepm/2 to stepm/2 .       a pointer to pointers identical to out */
          * For stepm=1 the results are the same as for previous versions of Imach.    long i, j, k;
          * For stepm > 1 the results are less biased than in previous versions.     for(i=nrl; i<= nrh; i++)
          */      for(k=ncolol; k<=ncoloh; k++)
         s1=s[mw[mi][i]][i];        for(j=ncl,out[i][k]=0.; j<=nch; j++)
         s2=s[mw[mi+1][i]][i];          out[i][k] +=in[i][j]*b[j][k];
         bbh=(double)bh[mi][i]/(double)stepm;   
         /* bias bh is positive if real duration    return out;
          * is higher than the multiple of stepm and negative otherwise.  }
          */  
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/  
         if( s2 > nlstate){   /************* Higher Matrix Product ***************/
           /* i.e. if s2 is a death state and if the date of death is known   
              then the contribution to the likelihood is the probability to   double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
              die between last step unit time and current  step unit time,   {
              which is also equal to probability to die before dh     /* Computes the transition matrix starting at age 'age' over
              minus probability to die before dh-stepm .        'nhstepm*hstepm*stepm' months (i.e. until
              In version up to 0.92 likelihood was computed       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
         as if date of death was unknown. Death was treated as any other       nhstepm*hstepm matrices.
         health state: the date of the interview describes the actual state       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
         and not the date of a change in health state. The former idea was       (typically every 2 years instead of every month which is too big
         to consider that at each interview the state was recorded       for the memory).
         (healthy, disable or death) and IMaCh was corrected; but when we       Model is determined by parameters x and covariates have to be
         introduced the exact date of death then we should have modified       included manually here.
         the contribution of an exact death to the likelihood. This new  
         contribution is smaller and very dependent of the step unit       */
         stepm. It is no more the probability to die between last interview  
         and month of death but the probability to survive from last    int i, j, d, h, k;
         interview up to one month before death multiplied by the    double **out, cov[NCOVMAX];
         probability to die within a month. Thanks to Chris    double **newm;
         Jackson for correcting this bug.  Former versions increased  
         mortality artificially. The bad side is that we add another loop    /* Hstepm could be zero and should return the unit matrix */
         which slows down the processing. The difference can be up to 10%    for (i=1;i<=nlstate+ndeath;i++)
         lower mortality.      for (j=1;j<=nlstate+ndeath;j++){
           */        oldm[i][j]=(i==j ? 1.0 : 0.0);
           lli=log(out[s1][s2] - savm[s1][s2]);        po[i][j][0]=(i==j ? 1.0 : 0.0);
       }
     /* Even if hstepm = 1, at least one multiplication by the unit matrix */
         } else if  (s2==-2) {    for(h=1; h <=nhstepm; h++){
           for (j=1,survp=0. ; j<=nlstate; j++)       for(d=1; d <=hstepm; d++){
             survp += out[s1][j];        newm=savm;
           lli= survp;        /* Covariates have to be included here again */
         }        cov[1]=1.;
                 cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
         else if  (s2==-4) {        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
           for (j=3,survp=0. ; j<=nlstate; j++)         for (k=1; k<=cptcovage;k++)
             survp += out[s1][j];          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           lli= survp;        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]]];
           
         else if  (s2==-5) {  
           for (j=1,survp=0. ; j<=2; j++)         /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
             survp += out[s1][j];        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
           lli= survp;        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
         }                     pmij(pmmij,cov,ncovmodel,x,nlstate));
         savm=oldm;
         oldm=newm;
         else{      }
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */      for(i=1; i<=nlstate+ndeath; i++)
           /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */        for(j=1;j<=nlstate+ndeath;j++) {
         }           po[i][j][h]=newm[i][j];
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
         /*if(lli ==000.0)*/           */
         /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */        }
         ipmx +=1;    } /* end h */
         sw += weight[i];    return po;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;  }
       } /* end of wave */  
     } /* end of individual */  
   }  else if(mle==2){  /*************** log-likelihood *************/
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  double func( double *x)
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];  {
       for(mi=1; mi<= wav[i]-1; mi++){    int i, ii, j, k, mi, d, kk;
         for (ii=1;ii<=nlstate+ndeath;ii++)    double l, ll[NLSTATEMAX], cov[NCOVMAX];
           for (j=1;j<=nlstate+ndeath;j++){    double **out;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    double sw; /* Sum of weights */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    double lli; /* Individual log likelihood */
           }    int s1, s2;
         for(d=0; d<=dh[mi][i]; d++){    double bbh, survp;
           newm=savm;    long ipmx;
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    /*extern weight */
           for (kk=1; kk<=cptcovage;kk++) {    /* We are differentiating ll according to initial status */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
           }    /*for(i=1;i<imx;i++)
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,      printf(" %d\n",s[4][i]);
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    */
           savm=oldm;    cov[1]=1.;
           oldm=newm;  
         } /* end mult */    for(k=1; k<=nlstate; k++) ll[k]=0.;
         
         s1=s[mw[mi][i]][i];    if(mle==1){
         s2=s[mw[mi+1][i]][i];      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         bbh=(double)bh[mi][i]/(double)stepm;         for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */        for(mi=1; mi<= wav[i]-1; mi++){
         ipmx +=1;          for (ii=1;ii<=nlstate+ndeath;ii++)
         sw += weight[i];            for (j=1;j<=nlstate+ndeath;j++){
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       } /* end of wave */              savm[ii][j]=(ii==j ? 1.0 : 0.0);
     } /* end of individual */            }
   }  else if(mle==3){  /* exponential inter-extrapolation */          for(d=0; d<dh[mi][i]; d++){
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){            newm=savm;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       for(mi=1; mi<= wav[i]-1; mi++){            for (kk=1; kk<=cptcovage;kk++) {
         for (ii=1;ii<=nlstate+ndeath;ii++)              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
           for (j=1;j<=nlstate+ndeath;j++){            }
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
             savm[ii][j]=(ii==j ? 1.0 : 0.0);                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           }            savm=oldm;
         for(d=0; d<dh[mi][i]; d++){            oldm=newm;
           newm=savm;          } /* end mult */
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;       
           for (kk=1; kk<=cptcovage;kk++) {          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          /* 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
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,           * (in months) between two waves is not a multiple of stepm, we rounded to
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));           * the nearest (and in case of equal distance, to the lowest) interval but now
           savm=oldm;           * we keep into memory the bias bh[mi][i] and also the previous matrix product
           oldm=newm;           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
         } /* end mult */           * probability in order to take into account the bias as a fraction of the way
                  * from savm to out if bh is negative or even beyond if bh is positive. bh varies
         s1=s[mw[mi][i]][i];           * -stepm/2 to stepm/2 .
         s2=s[mw[mi+1][i]][i];           * For stepm=1 the results are the same as for previous versions of Imach.
         bbh=(double)bh[mi][i]/(double)stepm;            * For stepm > 1 the results are less biased than in previous versions.
         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;          s1=s[mw[mi][i]][i];
         sw += weight[i];          s2=s[mw[mi+1][i]][i];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          bbh=(double)bh[mi][i]/(double)stepm;
       } /* end of wave */          /* bias bh is positive if real duration
     } /* end of individual */           * is higher than the multiple of stepm and negative otherwise.
   }else if (mle==4){  /* ml=4 no inter-extrapolation */           */
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          if( s2 > nlstate){
       for(mi=1; mi<= wav[i]-1; mi++){            /* i.e. if s2 is a death state and if the date of death is known
         for (ii=1;ii<=nlstate+ndeath;ii++)               then the contribution to the likelihood is the probability to
           for (j=1;j<=nlstate+ndeath;j++){               die between last step unit time and current  step unit time,
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);               which is also equal to probability to die before dh
             savm[ii][j]=(ii==j ? 1.0 : 0.0);               minus probability to die before dh-stepm .
           }               In version up to 0.92 likelihood was computed
         for(d=0; d<dh[mi][i]; 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
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          and not the date of a change in health state. The former idea was
           for (kk=1; kk<=cptcovage;kk++) {          to consider that at each interview the state was recorded
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          (healthy, disable or death) and IMaCh was corrected; but when we
           }          introduced the exact date of death then we should have modified
                   the contribution of an exact death to the likelihood. This new
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          contribution is smaller and very dependent of the step unit
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          stepm. It is no more the probability to die between last interview
           savm=oldm;          and month of death but the probability to survive from last
           oldm=newm;          interview up to one month before death multiplied by the
         } /* end mult */          probability to die within a month. Thanks to Chris
                 Jackson for correcting this bug.  Former versions increased
         s1=s[mw[mi][i]][i];          mortality artificially. The bad side is that we add another loop
         s2=s[mw[mi+1][i]][i];          which slows down the processing. The difference can be up to 10%
         if( s2 > nlstate){           lower mortality.
           lli=log(out[s1][s2] - savm[s1][s2]);            */
         }else{            lli=log(out[s1][s2] - savm[s1][s2]);
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */  
         }  
         ipmx +=1;          } else if  (s2==-2) {
         sw += weight[i];            for (j=1,survp=0. ; j<=nlstate; j++)
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */            /*survp += out[s1][j]; */
       } /* end of wave */            lli= log(survp);
     } /* end of individual */          }
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */         
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          else if  (s2==-4) {
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            for (j=3,survp=0. ; j<=nlstate; j++)  
       for(mi=1; mi<= wav[i]-1; mi++){              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         for (ii=1;ii<=nlstate+ndeath;ii++)            lli= log(survp);
           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==-5) {
           }            for (j=1,survp=0. ; j<=2; j++)  
         for(d=0; d<dh[mi][i]; d++){              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           newm=savm;            lli= log(survp);
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          }
           for (kk=1; kk<=cptcovage;kk++) {         
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          else{
           }            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 */
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          }
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
           savm=oldm;          /*if(lli ==000.0)*/
           oldm=newm;          /*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 mult */          ipmx +=1;
                 sw += weight[i];
         s1=s[mw[mi][i]][i];          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         s2=s[mw[mi+1][i]][i];        } /* end of wave */
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */      } /* end of individual */
         ipmx +=1;    }  else if(mle==2){
         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++){
       } /* end of wave */          for (ii=1;ii<=nlstate+ndeath;ii++)
     } /* end of individual */            for (j=1;j<=nlstate+ndeath;j++){
   } /* End of if */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */            }
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          for(d=0; d<=dh[mi][i]; d++){
   return -l;            newm=savm;
 }            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
             for (kk=1; kk<=cptcovage;kk++) {
 /*************** log-likelihood *************/              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 double funcone( double *x)            }
 {            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   /* Same as likeli but slower because of a lot of printf and if */                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   int i, ii, j, k, mi, d, kk;            savm=oldm;
   double l, ll[NLSTATEMAX], cov[NCOVMAX];            oldm=newm;
   double **out;          } /* end mult */
   double lli; /* Individual log likelihood */       
   double llt;          s1=s[mw[mi][i]][i];
   int s1, s2;          s2=s[mw[mi+1][i]][i];
   double bbh, survp;          bbh=(double)bh[mi][i]/(double)stepm;
   /*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 */          ipmx +=1;
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/          sw += weight[i];
   /*for(i=1;i<imx;i++)           ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     printf(" %d\n",s[4][i]);        } /* end of wave */
   */      } /* end of individual */
   cov[1]=1.;    }  else if(mle==3){  /* exponential inter-extrapolation */
       for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   for(k=1; k<=nlstate; k++) ll[k]=0.;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         for(mi=1; mi<= wav[i]-1; mi++){
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){          for (ii=1;ii<=nlstate+ndeath;ii++)
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            for (j=1;j<=nlstate+ndeath;j++){
     for(mi=1; mi<= wav[i]-1; mi++){              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       for (ii=1;ii<=nlstate+ndeath;ii++)              savm[ii][j]=(ii==j ? 1.0 : 0.0);
         for (j=1;j<=nlstate+ndeath;j++){            }
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);          for(d=0; d<dh[mi][i]; d++){
           savm[ii][j]=(ii==j ? 1.0 : 0.0);            newm=savm;
         }            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       for(d=0; d<dh[mi][i]; d++){            for (kk=1; kk<=cptcovage;kk++) {
         newm=savm;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         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];
                 bbh=(double)bh[mi][i]/(double)stepm;
       s1=s[mw[mi][i]][i];          lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
       s2=s[mw[mi+1][i]][i];          ipmx +=1;
       bbh=(double)bh[mi][i]/(double)stepm;           sw += weight[i];
       /* bias is positive if real duration          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        * is higher than the multiple of stepm and negative otherwise.        } /* end of wave */
        */      } /* end of individual */
       if( s2 > nlstate && (mle <5) ){  /* Jackson */    }else if (mle==4){  /* ml=4 no inter-extrapolation */
         lli=log(out[s1][s2] - savm[s1][s2]);      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       } else if (mle==1){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */        for(mi=1; mi<= wav[i]-1; mi++){
       } else if(mle==2){          for (ii=1;ii<=nlstate+ndeath;ii++)
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */            for (j=1;j<=nlstate+ndeath;j++){
       } else if(mle==3){  /* exponential inter-extrapolation */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         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 */              savm[ii][j]=(ii==j ? 1.0 : 0.0);
       } else if (mle==4){  /* mle=4 no inter-extrapolation */            }
         lli=log(out[s1][s2]); /* Original formula */          for(d=0; d<dh[mi][i]; d++){
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */            newm=savm;
         lli=log(out[s1][s2]); /* Original formula */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       } /* End of if */            for (kk=1; kk<=cptcovage;kk++) {
       ipmx +=1;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
       sw += weight[i];            }
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;         
 /*       printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
       if(globpr){                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         fprintf(ficresilk,"%9d %6d %1d %1d %1d %1d %3d %10.6f %6.4f\            savm=oldm;
  %10.6f %10.6f %10.6f ", \            oldm=newm;
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],          } /* end mult */
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);       
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){          s1=s[mw[mi][i]][i];
           llt +=ll[k]*gipmx/gsw;          s2=s[mw[mi+1][i]][i];
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);          if( s2 > nlstate){
         }            lli=log(out[s1][s2] - savm[s1][s2]);
         fprintf(ficresilk," %10.6f\n", -llt);          }else{
       }            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
     } /* end of wave */          }
   } /* end of individual */          ipmx +=1;
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];          sw += weight[i];
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */  /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
   if(globpr==0){ /* First time we count the contributions and weights */        } /* end of wave */
     gipmx=ipmx;      } /* end of individual */
     gsw=sw;    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
   }      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++)
             for (j=1;j<=nlstate+ndeath;j++){
 /*************** function likelione ***********/              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))              savm[ii][j]=(ii==j ? 1.0 : 0.0);
 {            }
   /* This routine should help understanding what is done with           for(d=0; d<dh[mi][i]; d++){
      the selection of individuals/waves and            newm=savm;
      to check the exact contribution to the likelihood.            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
      Plotting could be done.            for (kk=1; kk<=cptcovage;kk++) {
    */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   int k;            }
          
   if(*globpri !=0){ /* Just counts and sums, no printings */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
     strcpy(fileresilk,"ilk");                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
     strcat(fileresilk,fileres);            savm=oldm;
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {            oldm=newm;
       printf("Problem with resultfile: %s\n", fileresilk);          } /* end mult */
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);       
     }          s1=s[mw[mi][i]][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");          s2=s[mw[mi+1][i]][i];
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */          ipmx +=1;
     for(k=1; k<=nlstate; k++)           sw += weight[i];
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");          /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/
   }        } /* end of wave */
       } /* end of individual */
   *fretone=(*funcone)(p);    } /* End of if */
   if(*globpri !=0){    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
     fclose(ficresilk);    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
     fflush(fichtm);     return -l;
   }   }
   return;  
 }  /*************** log-likelihood *************/
   double funcone( double *x)
   {
 /*********** Maximum Likelihood Estimation ***************/    /* Same as likeli but slower because of a lot of printf and if */
     int i, ii, j, k, mi, d, kk;
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))    double l, ll[NLSTATEMAX], cov[NCOVMAX];
 {    double **out;
   int i,j, iter;    double lli; /* Individual log likelihood */
   double **xi;    double llt;
   double fret;    int s1, s2;
   double fretone; /* Only one call to likelihood */    double bbh, survp;
   /*  char filerespow[FILENAMELENGTH];*/    /*extern weight */
   xi=matrix(1,npar,1,npar);    /* We are differentiating ll according to initial status */
   for (i=1;i<=npar;i++)    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     for (j=1;j<=npar;j++)    /*for(i=1;i<imx;i++)
       xi[i][j]=(i==j ? 1.0 : 0.0);      printf(" %d\n",s[4][i]);
   printf("Powell\n");  fprintf(ficlog,"Powell\n");    */
   strcpy(filerespow,"pow");     cov[1]=1.;
   strcat(filerespow,fileres);  
   if((ficrespow=fopen(filerespow,"w"))==NULL) {    for(k=1; k<=nlstate; k++) ll[k]=0.;
     printf("Problem with resultfile: %s\n", filerespow);  
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   }      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   fprintf(ficrespow,"# Powell\n# iter -2*LL");      for(mi=1; mi<= wav[i]-1; mi++){
   for (i=1;i<=nlstate;i++)        for (ii=1;ii<=nlstate+ndeath;ii++)
     for(j=1;j<=nlstate+ndeath;j++)          for (j=1;j<=nlstate+ndeath;j++){
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   fprintf(ficrespow,"\n");            savm[ii][j]=(ii==j ? 1.0 : 0.0);
           }
   powell(p,xi,npar,ftol,&iter,&fret,func);        for(d=0; d<dh[mi][i]; d++){
           newm=savm;
   fclose(ficrespow);          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));          for (kk=1; kk<=cptcovage;kk++) {
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));          }
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 }                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           savm=oldm;
 /**** Computes Hessian and covariance matrix ***/          oldm=newm;
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))        } /* end mult */
 {       
   double  **a,**y,*x,pd;        s1=s[mw[mi][i]][i];
   double **hess;        s2=s[mw[mi+1][i]][i];
   int i, j,jk;        bbh=(double)bh[mi][i]/(double)stepm;
   int *indx;        /* bias is positive if real duration
          * is higher than the multiple of stepm and negative otherwise.
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);         */
   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);        if( s2 > nlstate && (mle <5) ){  /* Jackson */
   void lubksb(double **a, int npar, int *indx, double b[]) ;          lli=log(out[s1][s2] - savm[s1][s2]);
   void ludcmp(double **a, int npar, int *indx, double *d) ;        } else if  (s2==-2) {
   double gompertz(double p[]);          for (j=1,survp=0. ; j<=nlstate; j++)
   hess=matrix(1,npar,1,npar);            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           lli= log(survp);
   printf("\nCalculation of the hessian matrix. Wait...\n");        }else if (mle==1){
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
   for (i=1;i<=npar;i++){        } else if(mle==2){
     printf("%d",i);fflush(stdout);          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 */
     fprintf(ficlog,"%d",i);fflush(ficlog);        } 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 */
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);        } else if (mle==4){  /* mle=4 no inter-extrapolation */
               lli=log(out[s1][s2]); /* Original formula */
     /*  printf(" %f ",p[i]);        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/          lli=log(out[s1][s2]); /* Original formula */
   }        } /* End of if */
           ipmx +=1;
   for (i=1;i<=npar;i++) {        sw += weight[i];
     for (j=1;j<=npar;j++)  {        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       if (j>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]); */
         printf(".%d%d",i,j);fflush(stdout);        if(globpr){
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
         hess[i][j]=hessij(p,delti,i,j,func,npar);   %11.6f %11.6f %11.6f ", \
                           num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
         hess[j][i]=hess[i][j];                      2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
         /*printf(" %lf ",hess[i][j]);*/          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
       }            llt +=ll[k]*gipmx/gsw;
     }            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
   }          }
   printf("\n");          fprintf(ficresilk," %10.6f\n", -llt);
   fprintf(ficlog,"\n");        }
       } /* end of wave */
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");    } /* end of individual */
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
       /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   a=matrix(1,npar,1,npar);    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
   y=matrix(1,npar,1,npar);    if(globpr==0){ /* First time we count the contributions and weights */
   x=vector(1,npar);      gipmx=ipmx;
   indx=ivector(1,npar);      gsw=sw;
   for (i=1;i<=npar;i++)    }
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];    return -l;
   ludcmp(a,npar,indx,&pd);  }
   
   for (j=1;j<=npar;j++) {  
     for (i=1;i<=npar;i++) x[i]=0;  /*************** function likelione ***********/
     x[j]=1;  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
     lubksb(a,npar,indx,x);  {
     for (i=1;i<=npar;i++){     /* This routine should help understanding what is done with
       matcov[i][j]=x[i];       the selection of individuals/waves and
     }       to check the exact contribution to the likelihood.
   }       Plotting could be done.
      */
   printf("\n#Hessian matrix#\n");    int k;
   fprintf(ficlog,"\n#Hessian matrix#\n");  
   for (i=1;i<=npar;i++) {     if(*globpri !=0){ /* Just counts and sums, no printings */
     for (j=1;j<=npar;j++) {       strcpy(fileresilk,"ilk");
       printf("%.3e ",hess[i][j]);      strcat(fileresilk,fileres);
       fprintf(ficlog,"%.3e ",hess[i][j]);      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
     }        printf("Problem with resultfile: %s\n", fileresilk);
     printf("\n");        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
     fprintf(ficlog,"\n");      }
   }      fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
       fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
   /* Recompute Inverse */      /*  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 (i=1;i<=npar;i++)      for(k=1; k<=nlstate; k++)
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
   ludcmp(a,npar,indx,&pd);      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
     }
   /*  printf("\n#Hessian matrix recomputed#\n");  
     *fretone=(*funcone)(p);
   for (j=1;j<=npar;j++) {    if(*globpri !=0){
     for (i=1;i<=npar;i++) x[i]=0;      fclose(ficresilk);
     x[j]=1;      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
     lubksb(a,npar,indx,x);      fflush(fichtm);
     for (i=1;i<=npar;i++){     }
       y[i][j]=x[i];    return;
       printf("%.3e ",y[i][j]);  }
       fprintf(ficlog,"%.3e ",y[i][j]);  
     }  
     printf("\n");  /*********** Maximum Likelihood Estimation ***************/
     fprintf(ficlog,"\n");  
   }  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   */  {
     int i,j, iter;
   free_matrix(a,1,npar,1,npar);    double **xi;
   free_matrix(y,1,npar,1,npar);    double fret;
   free_vector(x,1,npar);    double fretone; /* Only one call to likelihood */
   free_ivector(indx,1,npar);    /*  char filerespow[FILENAMELENGTH];*/
   free_matrix(hess,1,npar,1,npar);    xi=matrix(1,npar,1,npar);
     for (i=1;i<=npar;i++)
       for (j=1;j<=npar;j++)
 }        xi[i][j]=(i==j ? 1.0 : 0.0);
     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 /*************** hessian matrix ****************/    strcpy(filerespow,"pow");
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)    strcat(filerespow,fileres);
 {    if((ficrespow=fopen(filerespow,"w"))==NULL) {
   int i;      printf("Problem with resultfile: %s\n", filerespow);
   int l=1, lmax=20;      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
   double k1,k2;    }
   double p2[NPARMAX+1];    fprintf(ficrespow,"# Powell\n# iter -2*LL");
   double res;    for (i=1;i<=nlstate;i++)
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;      for(j=1;j<=nlstate+ndeath;j++)
   double fx;        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   int k=0,kmax=10;    fprintf(ficrespow,"\n");
   double l1;  
     powell(p,xi,npar,ftol,&iter,&fret,func);
   fx=func(x);  
   for (i=1;i<=npar;i++) p2[i]=x[i];    free_matrix(xi,1,npar,1,npar);
   for(l=0 ; l <=lmax; l++){    fclose(ficrespow);
     l1=pow(10,l);    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
     delts=delt;    fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
     for(k=1 ; k <kmax; k=k+1){    fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
       delt = delta*(l1*k);  
       p2[theta]=x[theta] +delt;  }
       k1=func(p2)-fx;  
       p2[theta]=x[theta]-delt;  /**** Computes Hessian and covariance matrix ***/
       k2=func(p2)-fx;  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
       /*res= (k1-2.0*fx+k2)/delt/delt; */  {
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */    double  **a,**y,*x,pd;
           double **hess;
 #ifdef DEBUG    int i, j,jk;
       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);    int *indx;
       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    double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){    void lubksb(double **a, int npar, int *indx, double b[]) ;
         k=kmax;    void ludcmp(double **a, int npar, int *indx, double *d) ;
       }    double gompertz(double p[]);
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */    hess=matrix(1,npar,1,npar);
         k=kmax; l=lmax*10.;  
       }    printf("\nCalculation of the hessian matrix. Wait...\n");
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){     fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
         delts=delt;    for (i=1;i<=npar;i++){
       }      printf("%d",i);fflush(stdout);
     }      fprintf(ficlog,"%d",i);fflush(ficlog);
   }     
   delti[theta]=delts;       hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
   return res;      
         /*  printf(" %f ",p[i]);
 }          printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
     }
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)   
 {    for (i=1;i<=npar;i++) {
   int i;      for (j=1;j<=npar;j++)  {
   int l=1, l1, lmax=20;        if (j>i) {
   double k1,k2,k3,k4,res,fx;          printf(".%d%d",i,j);fflush(stdout);
   double p2[NPARMAX+1];          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
   int k;          hess[i][j]=hessij(p,delti,i,j,func,npar);
          
   fx=func(x);          hess[j][i]=hess[i][j];    
   for (k=1; k<=2; k++) {          /*printf(" %lf ",hess[i][j]);*/
     for (i=1;i<=npar;i++) p2[i]=x[i];        }
     p2[thetai]=x[thetai]+delti[thetai]/k;      }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    }
     k1=func(p2)-fx;    printf("\n");
       fprintf(ficlog,"\n");
     p2[thetai]=x[thetai]+delti[thetai]/k;  
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
     k2=func(p2)-fx;    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
      
     p2[thetai]=x[thetai]-delti[thetai]/k;    a=matrix(1,npar,1,npar);
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    y=matrix(1,npar,1,npar);
     k3=func(p2)-fx;    x=vector(1,npar);
       indx=ivector(1,npar);
     p2[thetai]=x[thetai]-delti[thetai]/k;    for (i=1;i<=npar;i++)
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;      for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
     k4=func(p2)-fx;    ludcmp(a,npar,indx,&pd);
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */  
 #ifdef DEBUG    for (j=1;j<=npar;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);      for (i=1;i<=npar;i++) x[i]=0;
     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);      x[j]=1;
 #endif      lubksb(a,npar,indx,x);
   }      for (i=1;i<=npar;i++){
   return res;        matcov[i][j]=x[i];
 }      }
     }
 /************** Inverse of matrix **************/  
 void ludcmp(double **a, int n, int *indx, double *d)     printf("\n#Hessian matrix#\n");
 {     fprintf(ficlog,"\n#Hessian matrix#\n");
   int i,imax,j,k;     for (i=1;i<=npar;i++) {
   double big,dum,sum,temp;       for (j=1;j<=npar;j++) {
   double *vv;         printf("%.3e ",hess[i][j]);
          fprintf(ficlog,"%.3e ",hess[i][j]);
   vv=vector(1,n);       }
   *d=1.0;       printf("\n");
   for (i=1;i<=n;i++) {       fprintf(ficlog,"\n");
     big=0.0;     }
     for (j=1;j<=n;j++)   
       if ((temp=fabs(a[i][j])) > big) big=temp;     /* Recompute Inverse */
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");     for (i=1;i<=npar;i++)
     vv[i]=1.0/big;       for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
   }     ludcmp(a,npar,indx,&pd);
   for (j=1;j<=n;j++) {   
     for (i=1;i<j;i++) {     /*  printf("\n#Hessian matrix recomputed#\n");
       sum=a[i][j];   
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];     for (j=1;j<=npar;j++) {
       a[i][j]=sum;       for (i=1;i<=npar;i++) x[i]=0;
     }       x[j]=1;
     big=0.0;       lubksb(a,npar,indx,x);
     for (i=j;i<=n;i++) {       for (i=1;i<=npar;i++){
       sum=a[i][j];         y[i][j]=x[i];
       for (k=1;k<j;k++)         printf("%.3e ",y[i][j]);
         sum -= a[i][k]*a[k][j];         fprintf(ficlog,"%.3e ",y[i][j]);
       a[i][j]=sum;       }
       if ( (dum=vv[i]*fabs(sum)) >= big) {       printf("\n");
         big=dum;       fprintf(ficlog,"\n");
         imax=i;     }
       }     */
     }   
     if (j != imax) {     free_matrix(a,1,npar,1,npar);
       for (k=1;k<=n;k++) {     free_matrix(y,1,npar,1,npar);
         dum=a[imax][k];     free_vector(x,1,npar);
         a[imax][k]=a[j][k];     free_ivector(indx,1,npar);
         a[j][k]=dum;     free_matrix(hess,1,npar,1,npar);
       }   
       *d = -(*d);   
       vv[imax]=vv[j];   }
     }   
     indx[j]=imax;   /*************** hessian matrix ****************/
     if (a[j][j] == 0.0) a[j][j]=TINY;   double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
     if (j != n) {   {
       dum=1.0/(a[j][j]);     int i;
       for (i=j+1;i<=n;i++) a[i][j] *= dum;     int l=1, lmax=20;
     }     double k1,k2;
   }     double p2[NPARMAX+1];
   free_vector(vv,1,n);  /* Doesn't work */    double res;
 ;    double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 }     double fx;
     int k=0,kmax=10;
 void lubksb(double **a, int n, int *indx, double b[])     double l1;
 {   
   int i,ii=0,ip,j;     fx=func(x);
   double sum;     for (i=1;i<=npar;i++) p2[i]=x[i];
      for(l=0 ; l <=lmax; l++){
   for (i=1;i<=n;i++) {       l1=pow(10,l);
     ip=indx[i];       delts=delt;
     sum=b[ip];       for(k=1 ; k <kmax; k=k+1){
     b[ip]=b[i];         delt = delta*(l1*k);
     if (ii)         p2[theta]=x[theta] +delt;
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];         k1=func(p2)-fx;
     else if (sum) ii=i;         p2[theta]=x[theta]-delt;
     b[i]=sum;         k2=func(p2)-fx;
   }         /*res= (k1-2.0*fx+k2)/delt/delt; */
   for (i=n;i>=1;i--) {         res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
     sum=b[i];        
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];   #ifdef DEBUG
     b[i]=sum/a[i][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);
   }         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){ */
 /************ Frequencies ********************/        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 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[])          k=kmax;
 {  /* Some frequencies */        }
           else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;          k=kmax; l=lmax*10.;
   int first;        }
   double ***freq; /* Frequencies */        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
   double *pp, **prop;          delts=delt;
   double pos,posprop, k2, dateintsum=0,k2cpt=0;        }
   FILE *ficresp;      }
   char fileresp[FILENAMELENGTH];    }
       delti[theta]=delts;
   pp=vector(1,nlstate);    return res;
   prop=matrix(1,nlstate,iagemin,iagemax+3);   
   strcpy(fileresp,"p");  }
   strcat(fileresp,fileres);  
   if((ficresp=fopen(fileresp,"w"))==NULL) {  double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
     printf("Problem with prevalence resultfile: %s\n", fileresp);  {
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);    int i;
     exit(0);    int l=1, l1, lmax=20;
   }    double k1,k2,k3,k4,res,fx;
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);    double p2[NPARMAX+1];
   j1=0;    int k;
     
   j=cptcoveff;    fx=func(x);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    for (k=1; k<=2; k++) {
       for (i=1;i<=npar;i++) p2[i]=x[i];
   first=1;      p2[thetai]=x[thetai]+delti[thetai]/k;
       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   for(k1=1; k1<=j;k1++){      k1=func(p2)-fx;
     for(i1=1; i1<=ncodemax[k1];i1++){   
       j1++;      p2[thetai]=x[thetai]+delti[thetai]/k;
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
         scanf("%d", i);*/      k2=func(p2)-fx;
       for (i=-5; i<=nlstate+ndeath; i++)     
         for (jk=-5; jk<=nlstate+ndeath; jk++)        p2[thetai]=x[thetai]-delti[thetai]/k;
           for(m=iagemin; m <= iagemax+3; m++)      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
             freq[i][jk][m]=0;      k3=func(p2)-fx;
    
     for (i=1; i<=nlstate; i++)        p2[thetai]=x[thetai]-delti[thetai]/k;
       for(m=iagemin; m <= iagemax+3; m++)      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
         prop[i][m]=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 */
       dateintsum=0;  #ifdef DEBUG
       k2cpt=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);
       for (i=1; i<=imx; i++) {      fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
         bool=1;  #endif
         if  (cptcovn>0) {    }
           for (z1=1; z1<=cptcoveff; z1++)     return res;
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])   }
               bool=0;  
         }  /************** Inverse of matrix **************/
         if (bool==1){  void ludcmp(double **a, int n, int *indx, double *d)
           for(m=firstpass; m<=lastpass; m++){  {
             k2=anint[m][i]+(mint[m][i]/12.);    int i,imax,j,k;
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/    double big,dum,sum,temp;
               if(agev[m][i]==0) agev[m][i]=iagemax+1;    double *vv;
               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];    vv=vector(1,n);
               if (m<lastpass) {    *d=1.0;
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];    for (i=1;i<=n;i++) {
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];      big=0.0;
               }      for (j=1;j<=n;j++)
                       if ((temp=fabs(a[i][j])) > big) big=temp;
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {      if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
                 dateintsum=dateintsum+k2;      vv[i]=1.0/big;
                 k2cpt++;    }
               }    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;
              }
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/      big=0.0;
 fprintf(ficresp, "#Local time at start: %s", strstart);      for (i=j;i<=n;i++) {
       if  (cptcovn>0) {        sum=a[i][j];
         fprintf(ficresp, "\n#********** Variable ");         for (k=1;k<j;k++)
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          sum -= a[i][k]*a[k][j];
         fprintf(ficresp, "**********\n#");        a[i][j]=sum;
       }        if ( (dum=vv[i]*fabs(sum)) >= big) {
       for(i=1; i<=nlstate;i++)           big=dum;
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);          imax=i;
       fprintf(ficresp, "\n");        }
             }
       for(i=iagemin; i <= iagemax+3; i++){      if (j != imax) {
         if(i==iagemax+3){        for (k=1;k<=n;k++) {
           fprintf(ficlog,"Total");          dum=a[imax][k];
         }else{          a[imax][k]=a[j][k];
           if(first==1){          a[j][k]=dum;
             first=0;        }
             printf("See log file for details...\n");        *d = -(*d);
           }        vv[imax]=vv[j];
           fprintf(ficlog,"Age %d", i);      }
         }      indx[j]=imax;
         for(jk=1; jk <=nlstate ; jk++){      if (a[j][j] == 0.0) a[j][j]=TINY;
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)      if (j != n) {
             pp[jk] += freq[jk][m][i];         dum=1.0/(a[j][j]);
         }        for (i=j+1;i<=n;i++) a[i][j] *= dum;
         for(jk=1; jk <=nlstate ; jk++){      }
           for(m=-1, pos=0; m <=0 ; m++)    }
             pos += freq[jk][m][i];    free_vector(vv,1,n);  /* Doesn't work */
           if(pp[jk]>=1.e-10){  ;
             if(first==1){  }
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);  
             }  void lubksb(double **a, int n, int *indx, double b[])
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);  {
           }else{    int i,ii=0,ip,j;
             if(first==1)    double sum;
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);   
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);    for (i=1;i<=n;i++) {
           }      ip=indx[i];
         }      sum=b[ip];
       b[ip]=b[i];
         for(jk=1; jk <=nlstate ; jk++){      if (ii)
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
             pp[jk] += freq[jk][m][i];      else if (sum) ii=i;
         }             b[i]=sum;
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){    }
           pos += pp[jk];    for (i=n;i>=1;i--) {
           posprop += prop[jk][i];      sum=b[i];
         }      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
         for(jk=1; jk <=nlstate ; jk++){      b[i]=sum/a[i][i];
           if(pos>=1.e-5){    }
             if(first==1)  }
               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);  void pstamp(FILE *fichier)
           }else{  {
             if(first==1)    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);  }
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);  
           }  /************ Frequencies ********************/
           if( i <= iagemax){  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[])
             if(pos>=1.e-5){  {  /* Some frequencies */
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);   
               /*probs[i][jk][j1]= pp[jk]/pos;*/    int i, m, jk, k1,i1, j1, bool, z1,z2,j;
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/    int first;
             }    double ***freq; /* Frequencies */
             else    double *pp, **prop;
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);    double pos,posprop, k2, dateintsum=0,k2cpt=0;
           }    char fileresp[FILENAMELENGTH];
         }   
             pp=vector(1,nlstate);
         for(jk=-1; jk <=nlstate+ndeath; jk++)    prop=matrix(1,nlstate,iagemin,iagemax+3);
           for(m=-1; m <=nlstate+ndeath; m++)    strcpy(fileresp,"p");
             if(freq[jk][m][i] !=0 ) {    strcat(fileresp,fileres);
             if(first==1)    if((ficresp=fopen(fileresp,"w"))==NULL) {
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);      printf("Problem with prevalence resultfile: %s\n", fileresp);
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
             }      exit(0);
         if(i <= iagemax)    }
           fprintf(ficresp,"\n");    freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
         if(first==1)    j1=0;
           printf("Others in log...\n");   
         fprintf(ficlog,"\n");    j=cptcoveff;
       }    if (cptcovn<1) {j=1;ncodemax[1]=1;}
     }  
   }    first=1;
   dateintmean=dateintsum/k2cpt;   
      for(k1=1; k1<=j;k1++){
   fclose(ficresp);      for(i1=1; i1<=ncodemax[k1];i1++){
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);        j1++;
   free_vector(pp,1,nlstate);        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);          scanf("%d", i);*/
   /* End of Freq */        for (i=-5; i<=nlstate+ndeath; i++)  
 }          for (jk=-5; jk<=nlstate+ndeath; jk++)  
             for(m=iagemin; m <= iagemax+3; m++)
 /************ Prevalence ********************/              freq[i][jk][m]=0;
 void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)  
 {        for (i=1; i<=nlstate; i++)  
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people        for(m=iagemin; m <= iagemax+3; m++)
      in each health status at the date of interview (if between dateprev1 and dateprev2).          prop[i][m]=0;
      We still use firstpass and lastpass as another selection.       
   */        dateintsum=0;
          k2cpt=0;
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;        for (i=1; i<=imx; i++) {
   double ***freq; /* Frequencies */          bool=1;
   double *pp, **prop;          if  (cptcovn>0) {
   double pos,posprop;             for (z1=1; z1<=cptcoveff; z1++)
   double  y2; /* in fractional years */              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
   int iagemin, iagemax;                bool=0;
           }
   iagemin= (int) agemin;          if (bool==1){
   iagemax= (int) agemax;            for(m=firstpass; m<=lastpass; m++){
   /*pp=vector(1,nlstate);*/              k2=anint[m][i]+(mint[m][i]/12.);
   prop=matrix(1,nlstate,iagemin,iagemax+3);               /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/                if(agev[m][i]==0) agev[m][i]=iagemax+1;
   j1=0;                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];
   j=cptcoveff;                if (m<lastpass) {
   if (cptcovn<1) {j=1;ncodemax[1]=1;}                  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];
   for(k1=1; k1<=j;k1++){                }
     for(i1=1; i1<=ncodemax[k1];i1++){               
       j1++;                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                         dateintsum=dateintsum+k2;
       for (i=1; i<=nlstate; i++)                    k2cpt++;
         for(m=iagemin; m <= iagemax+3; m++)                }
           prop[i][m]=0.0;                /*}*/
                  }
       for (i=1; i<=imx; i++) { /* Each individual */          }
         bool=1;        }
         if  (cptcovn>0) {         
           for (z1=1; z1<=cptcoveff; z1++)         /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])         pstamp(ficresp);
               bool=0;        if  (cptcovn>0) {
         }           fprintf(ficresp, "\n#********** Variable ");
         if (bool==1) {           for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/          fprintf(ficresp, "**********\n#");
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */        }
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */        for(i=1; i<=nlstate;i++)
               if(agev[m][i]==0) agev[m][i]=iagemax+1;          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
               if(agev[m][i]==1) agev[m][i]=iagemax+2;        fprintf(ficresp, "\n");
               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) {         for(i=iagemin; i <= iagemax+3; i++){
                 /*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(i==iagemax+3){
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];            fprintf(ficlog,"Total");
                 prop[s[m][i]][iagemax+3] += weight[i];           }else{
               }             if(first==1){
             }              first=0;
           } /* end selection of waves */              printf("See log file for details...\n");
         }            }
       }            fprintf(ficlog,"Age %d", i);
       for(i=iagemin; i <= iagemax+3; i++){            }
                   for(jk=1; jk <=nlstate ; jk++){
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {             for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
           posprop += prop[jk][i];               pp[jk] += freq[jk][m][i];
         }           }
           for(jk=1; jk <=nlstate ; jk++){
         for(jk=1; jk <=nlstate ; jk++){                 for(m=-1, pos=0; m <=0 ; m++)
           if( i <=  iagemax){               pos += freq[jk][m][i];
             if(posprop>=1.e-5){             if(pp[jk]>=1.e-10){
               probs[i][jk][j1]= prop[jk][i]/posprop;              if(first==1){
             }               printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
           }               }
         }/* end jk */               fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
       }/* end i */             }else{
     } /* end i1 */              if(first==1)
   } /* end k1 */                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                 fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/            }
   /*free_vector(pp,1,nlstate);*/          }
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);  
 }  /* End of prevalence */          for(jk=1; jk <=nlstate ; jk++){
             for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 /************* Waves Concatenation ***************/              pp[jk] += freq[jk][m][i];
           }      
 void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 {            pos += pp[jk];
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.            posprop += prop[jk][i];
      Death is a valid wave (if date is known).          }
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i          for(jk=1; jk <=nlstate ; jk++){
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]            if(pos>=1.e-5){
      and mw[mi+1][i]. dh depends on stepm.              if(first==1)
      */                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);
   int i, mi, m;            }else{
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;              if(first==1)
      double sum=0., jmean=0.;*/                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
   int first;              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
   int j, k=0,jk, ju, jl;            }
   double sum=0.;            if( i <= iagemax){
   first=0;              if(pos>=1.e-5){
   jmin=1e+5;                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
   jmax=-1;                /*probs[i][jk][j1]= pp[jk]/pos;*/
   jmean=0.;                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
   for(i=1; i<=imx; i++){              }
     mi=0;              else
     m=firstpass;                fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
     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;         
       if(m >=lastpass)          for(jk=-1; jk <=nlstate+ndeath; jk++)
         break;            for(m=-1; m <=nlstate+ndeath; m++)
       else              if(freq[jk][m][i] !=0 ) {
         m++;              if(first==1)
     }/* end while */                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
     if (s[m][i] > nlstate){                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
       mi++;     /* Death is another wave */              }
       /* if(mi==0)  never been interviewed correctly before death */          if(i <= iagemax)
          /* Only death is a correct wave */            fprintf(ficresp,"\n");
       mw[mi][i]=m;          if(first==1)
     }            printf("Others in log...\n");
           fprintf(ficlog,"\n");
     wav[i]=mi;        }
     if(mi==0){      }
       nbwarn++;    }
       if(first==0){    dateintmean=dateintsum/k2cpt;
         printf("Warning! None valid information for:%ld line=%d (skipped) and may be others, see log file\n",num[i],i);   
         first=1;    fclose(ficresp);
       }    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
       if(first==1){    free_vector(pp,1,nlstate);
         fprintf(ficlog,"Warning! None valid information for:%ld line=%d (skipped)\n",num[i],i);    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
       }    /* End of Freq */
     } /* end mi==0 */  }
   } /* End individuals */  
   /************ Prevalence ********************/
   for(i=1; i<=imx; i++){  void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)
     for(mi=1; mi<wav[i];mi++){  {  
       if (stepm <=0)    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
         dh[mi][i]=1;       in each health status at the date of interview (if between dateprev1 and dateprev2).
       else{       We still use firstpass and lastpass as another selection.
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */    */
           if (agedc[i] < 2*AGESUP) {   
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);     int i, m, jk, k1, i1, j1, bool, z1,z2,j;
             if(j==0) j=1;  /* Survives at least one month after exam */    double ***freq; /* Frequencies */
             else if(j<0){    double *pp, **prop;
               nberr++;    double pos,posprop;
               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]);    double  y2; /* in fractional years */
               j=1; /* Temporary Dangerous patch */    int iagemin, iagemax;
               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);  
               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]);    iagemin= (int) agemin;
               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);    iagemax= (int) agemax;
             }    /*pp=vector(1,nlstate);*/
             k=k+1;    prop=matrix(1,nlstate,iagemin,iagemax+3);
             if (j >= jmax) jmax=j;    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
             if (j <= jmin) jmin=j;    j1=0;
             sum=sum+j;   
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/    j=cptcoveff;
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/    if (cptcovn<1) {j=1;ncodemax[1]=1;}
           }   
         }    for(k1=1; k1<=j;k1++){
         else{      for(i1=1; i1<=ncodemax[k1];i1++){
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));        j1++;
 /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */       
         for (i=1; i<=nlstate; i++)  
           k=k+1;          for(m=iagemin; m <= iagemax+3; m++)
           if (j >= jmax) jmax=j;            prop[i][m]=0.0;
           else if (j <= jmin)jmin=j;       
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */        for (i=1; i<=imx; i++) { /* Each individual */
           /*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]);*/          bool=1;
           if(j<0){          if  (cptcovn>0) {
             nberr++;            for (z1=1; z1<=cptcoveff; z1++)
             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]);              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
             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]);                bool=0;
           }          }
           sum=sum+j;          if (bool==1) {
         }            for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
         jk= j/stepm;              y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
         jl= j -jk*stepm;              if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
         ju= j -(jk+1)*stepm;                if(agev[m][i]==0) agev[m][i]=iagemax+1;
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */                if(agev[m][i]==1) agev[m][i]=iagemax+2;
           if(jl==0){                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);
             dh[mi][i]=jk;                if (s[m][i]>0 && s[m][i]<=nlstate) {
             bh[mi][i]=0;                  /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
           }else{ /* We want a negative bias in order to only have interpolation ie                  prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   * at the price of an extra matrix product in likelihood */                  prop[s[m][i]][iagemax+3] += weight[i];
             dh[mi][i]=jk+1;                }
             bh[mi][i]=ju;              }
           }            } /* end selection of waves */
         }else{          }
           if(jl <= -ju){        }
             dh[mi][i]=jk;        for(i=iagemin; i <= iagemax+3; i++){  
             bh[mi][i]=jl;       /* bias is positive if real duration         
                                  * is higher than the multiple of stepm and negative otherwise.          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
                                  */            posprop += prop[jk][i];
           }          }
           else{  
             dh[mi][i]=jk+1;          for(jk=1; jk <=nlstate ; jk++){    
             bh[mi][i]=ju;            if( i <=  iagemax){
           }              if(posprop>=1.e-5){
           if(dh[mi][i]==0){                probs[i][jk][j1]= prop[jk][i]/posprop;
             dh[mi][i]=1; /* At least one step */              }
             bh[mi][i]=ju; /* At least one step */            }
             /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/          }/* end jk */
           }        }/* end i */
         } /* end if mle */      } /* end i1 */
       }    } /* end k1 */
     } /* end wave */   
   }    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
   jmean=sum/k;    /*free_vector(pp,1,nlstate);*/
   printf("Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
   fprintf(ficlog,"Delay (in months) between two waves Min=%d Max=%d Mean=%f\n\n ",jmin, jmax,jmean);  }  /* End of prevalence */
  }  
   /************* Waves Concatenation ***************/
 /*********** Tricode ****************************/  
 void tricode(int *Tvar, int **nbcode, int imx)  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.
   int Ndum[20],ij=1, k, j, i, maxncov=19;       Death is a valid wave (if date is known).
   int cptcode=0;       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
   cptcoveff=0;        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.
   for (k=0; k<maxncov; k++) Ndum[k]=0;       */
   for (k=1; k<=7; k++) ncodemax[k]=0;  
     int i, mi, m;
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum        double sum=0., jmean=0.;*/
                                modality*/     int first;
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/    int j, k=0,jk, ju, jl;
       Ndum[ij]++; /*store the modality */    double sum=0.;
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/    first=0;
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable     jmin=1e+5;
                                        Tvar[j]. If V=sex and male is 0 and     jmax=-1;
                                        female is 1, then  cptcode=1.*/    jmean=0.;
     }    for(i=1; i<=imx; i++){
       mi=0;
     for (i=0; i<=cptcode; i++) {      m=firstpass;
       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 */      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;
     ij=1;         if(m >=lastpass)
     for (i=1; i<=ncodemax[j]; i++) {          break;
       for (k=0; k<= maxncov; k++) {        else
         if (Ndum[k] != 0) {          m++;
           nbcode[Tvar[j]][ij]=k;       }/* end while */
           /* 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 (s[m][i] > nlstate){
                   mi++;     /* Death is another wave */
           ij++;        /* if(mi==0)  never been interviewed correctly before death */
         }           /* Only death is a correct wave */
         if (ij > ncodemax[j]) break;         mw[mi][i]=m;
       }        }
     }   
   }        wav[i]=mi;
       if(mi==0){
  for (k=0; k< maxncov; k++) Ndum[k]=0;        nbwarn++;
         if(first==0){
  for (i=1; i<=ncovmodel-2; i++) {           printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/          first=1;
    ij=Tvar[i];        }
    Ndum[ij]++;        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<= maxncov; i++) {    } /* End individuals */
    if((Ndum[i]!=0) && (i<=ncovcol)){  
      Tvaraff[ij]=i; /*For printing */    for(i=1; i<=imx; i++){
      ij++;      for(mi=1; mi<wav[i];mi++){
    }        if (stepm <=0)
  }          dh[mi][i]=1;
          else{
  cptcoveff=ij-1; /*Number of simple covariates*/          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 }            if (agedc[i] < 2*AGESUP) {
               j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
 /*********** Health Expectancies ****************/              if(j==0) j=1;  /* Survives at least one month after exam */
               else if(j<0){
 void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij, int estepm,double delti[],double **matcov,char strstart[] )                nberr++;
                 printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
 {                j=1; /* Temporary Dangerous patch */
   /* Health expectancies */                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);
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;                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]);
   double age, agelim, hf;                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);
   double ***p3mat,***varhe;              }
   double **dnewm,**doldm;              k=k+1;
   double *xp;              if (j >= jmax){
   double **gp, **gm;                jmax=j;
   double ***gradg, ***trgradg;                ijmax=i;
   int theta;              }
               if (j <= jmin){
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);                jmin=j;
   xp=vector(1,npar);                ijmin=i;
   dnewm=matrix(1,nlstate*nlstate,1,npar);              }
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);              sum=sum+j;
                 /*if (j<0) printf("j=%d num=%d \n",j,i);*/
   fprintf(ficreseij,"# Local time at start: %s", strstart);              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
   fprintf(ficreseij,"# Health expectancies\n");            }
   fprintf(ficreseij,"# Age");          }
   for(i=1; i<=nlstate;i++)          else{
     for(j=1; j<=nlstate;j++)            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
       fprintf(ficreseij," %1d-%1d (SE)",i,j);  /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */
   fprintf(ficreseij,"\n");  
             k=k+1;
   if(estepm < stepm){            if (j >= jmax) {
     printf ("Problem %d lower than %d\n",estepm, stepm);              jmax=j;
   }              ijmax=i;
   else  hstepm=estepm;               }
   /* We compute the life expectancy from trapezoids spaced every estepm months            else if (j <= jmin){
    * This is mainly to measure the difference between two models: for example              jmin=j;
    * if stepm=24 months pijx are given only every 2 years and by summing them              ijmin=i;
    * we are calculating an estimate of the Life Expectancy assuming a linear             }
    * progression in between and thus overestimating or underestimating according            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
    * to the curvature of the survival function. If, for the same date, we             /*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]);*/
    * estimate the model with stepm=1 month, we can keep estepm to 24 months            if(j<0){
    * to compare the new estimate of Life expectancy with the same linear               nberr++;
    * hypothesis. A more precise result, taking into account a more precise              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]);
    * curvature will be obtained if estepm is as small as stepm. */              fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
             }
   /* For example we decided to compute the life expectancy with the smallest unit */            sum=sum+j;
   /* 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           jk= j/stepm;
      nstepm is the number of stepm from age to agelin.           jl= j -jk*stepm;
      Look at hpijx to understand the reason of that which relies in memory size          ju= j -(jk+1)*stepm;
      and note for a fixed period like estepm months */          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the            if(jl==0){
      survival function given by stepm (the optimization length). Unfortunately it              dh[mi][i]=jk;
      means that if the survival funtion is printed only each two years of age and if              bh[mi][i]=0;
      you sum them up and add 1 year (area under the trapezoids) you won't get the same             }else{ /* We want a negative bias in order to only have interpolation ie
      results. So we changed our mind and took the option of the best precision.                    * at the price of an extra matrix product in likelihood */
   */              dh[mi][i]=jk+1;
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */               bh[mi][i]=ju;
             }
   agelim=AGESUP;          }else{
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */            if(jl <= -ju){
     /* nhstepm age range expressed in number of stepm */              dh[mi][i]=jk;
     nstepm=(int) rint((agelim-age)*YEARM/stepm);               bh[mi][i]=jl;       /* bias is positive if real duration
     /* Typically if 20 years nstepm = 20*12/6=40 stepm */                                    * is higher than the multiple of stepm and negative otherwise.
     /* 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);            else{
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);              dh[mi][i]=jk+1;
     gp=matrix(0,nhstepm,1,nlstate*nlstate);              bh[mi][i]=ju;
     gm=matrix(0,nhstepm,1,nlstate*nlstate);            }
             if(dh[mi][i]==0){
     /* Computed by stepm unit matrices, product of hstepm matrices, stored              dh[mi][i]=1; /* At least one step */
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */              bh[mi][i]=ju; /* At least one step */
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);                /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/
              }
           } /* end if mle */
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */        }
       } /* end wave */
     /* Computing  Variances of health expectancies */    }
     jmean=sum/k;
      for(theta=1; theta <=npar; theta++){    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);
       for(i=1; i<=npar; i++){     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);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);   }
       }  
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);    /*********** Tricode ****************************/
     void tricode(int *Tvar, int **nbcode, int imx)
       cptj=0;  {
       for(j=1; j<= nlstate; j++){   
         for(i=1; i<=nlstate; i++){    int Ndum[20],ij=1, k, j, i, maxncov=19;
           cptj=cptj+1;    int cptcode=0;
           for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){    cptcoveff=0;
             gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;   
           }    for (k=0; k<maxncov; k++) Ndum[k]=0;
         }    for (k=1; k<=7; k++) ncodemax[k]=0;
       }  
          for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
            for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
       for(i=1; i<=npar; i++)                                  modality*/
         xp[i] = x[i] - (i==theta ?delti[theta]:0);        ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);          Ndum[ij]++; /*store the modality */
               /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
       cptj=0;        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
       for(j=1; j<= nlstate; j++){                                         Tvar[j]. If V=sex and male is 0 and
         for(i=1;i<=nlstate;i++){                                         female is 1, then  cptcode=1.*/
           cptj=cptj+1;      }
           for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){  
       for (i=0; i<=cptcode; i++) {
             gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;        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 */
           }      }
         }  
       }      ij=1;
       for(j=1; j<= nlstate*nlstate; j++)      for (i=1; i<=ncodemax[j]; i++) {
         for(h=0; h<=nhstepm-1; h++){        for (k=0; k<= maxncov; k++) {
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];          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; */
               
 /* End theta */            ij++;
           }
      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);          if (ij > ncodemax[j]) break;
         }  
      for(h=0; h<=nhstepm-1; h++)      }
       for(j=1; j<=nlstate*nlstate;j++)    }  
         for(theta=1; theta <=npar; theta++)  
           trgradg[h][j][theta]=gradg[h][theta][j];   for (k=0; k< maxncov; k++) Ndum[k]=0;
        
    for (i=1; i<=ncovmodel-2; i++) {
      for(i=1;i<=nlstate*nlstate;i++)     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
       for(j=1;j<=nlstate*nlstate;j++)     ij=Tvar[i];
         varhe[i][j][(int)age] =0.;     Ndum[ij]++;
    }
      printf("%d|",(int)age);fflush(stdout);  
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);   ij=1;
      for(h=0;h<=nhstepm-1;h++){   for (i=1; i<= maxncov; i++) {
       for(k=0;k<=nhstepm-1;k++){     if((Ndum[i]!=0) && (i<=ncovcol)){
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);       Tvaraff[ij]=i; /*For printing */
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);       ij++;
         for(i=1;i<=nlstate*nlstate;i++)     }
           for(j=1;j<=nlstate*nlstate;j++)   }
             varhe[i][j][(int)age] += doldm[i][j]*hf*hf;   
       }   cptcoveff=ij-1; /*Number of simple covariates*/
     }  }
     /* Computing expectancies */  
     for(i=1; i<=nlstate;i++)  /*********** Health Expectancies ****************/
       for(j=1; j<=nlstate;j++)  
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){  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[] )
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;  
             {
 /* 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]);*/    /* Health expectancies, no variances */
     int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
         }    double age, agelim, hf;
     double ***p3mat;
     fprintf(ficreseij,"%3.0f",age );    double eip;
     cptj=0;  
     for(i=1; i<=nlstate;i++)    pstamp(ficreseij);
       for(j=1; j<=nlstate;j++){    fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
         cptj++;    fprintf(ficreseij,"# Age");
         fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );    for(i=1; i<=nlstate;i++){
       }      for(j=1; j<=nlstate;j++){
     fprintf(ficreseij,"\n");        fprintf(ficreseij," e%1d%1d ",i,j);
          }
     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);      fprintf(ficreseij," e%1d. ",i);
     free_matrix(gp,0,nhstepm,1,nlstate*nlstate);    }
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);    fprintf(ficreseij,"\n");
     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);  
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   
   }    if(estepm < stepm){
   printf("\n");      printf ("Problem %d lower than %d\n",estepm, stepm);
   fprintf(ficlog,"\n");    }
     else  hstepm=estepm;  
   free_vector(xp,1,npar);    /* We compute the life expectancy from trapezoids spaced every estepm months
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);     * This is mainly to measure the difference between two models: for example
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);     * if stepm=24 months pijx are given only every 2 years and by summing them
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);     * we are calculating an estimate of the Life Expectancy assuming a linear
 }     * progression in between and thus overestimating or underestimating according
      * to the curvature of the survival function. If, for the same date, we
 /************ Variance ******************/     * estimate the model with stepm=1 month, we can keep estepm to 24 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[])     * to compare the new estimate of Life expectancy with the same linear
 {     * hypothesis. A more precise result, taking into account a more precise
   /* Variance of health expectancies */     * curvature will be obtained if estepm is as small as stepm. */
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/  
   /* double **newm;*/    /* For example we decided to compute the life expectancy with the smallest unit */
   double **dnewm,**doldm;    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   double **dnewmp,**doldmp;       nhstepm is the number of hstepm from age to agelim
   int i, j, nhstepm, hstepm, h, nstepm ;       nstepm is the number of stepm from age to agelin.
   int k, cptcode;       Look at hpijx to understand the reason of that which relies in memory size
   double *xp;       and note for a fixed period like estepm months */
   double **gp, **gm;  /* for var eij */    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   double ***gradg, ***trgradg; /*for var eij */       survival function given by stepm (the optimization length). Unfortunately it
   double **gradgp, **trgradgp; /* for var p point j */       means that if the survival funtion is printed only each two years of age and if
   double *gpp, *gmp; /* for var p point j */       you sum them up and add 1 year (area under the trapezoids) you won't get the same
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */       results. So we changed our mind and took the option of the best precision.
   double ***p3mat;    */
   double age,agelim, hf;    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   double ***mobaverage;  
   int theta;    agelim=AGESUP;
   char digit[4];    /* If stepm=6 months */
   char digitp[25];      /* Computed by stepm unit matrices, product of hstepm matrices, stored
          in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
   char fileresprobmorprev[FILENAMELENGTH];     
   /* nhstepm age range expressed in number of stepm */
   if(popbased==1){    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
     if(mobilav!=0)    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
       strcpy(digitp,"-populbased-mobilav-");    /* if (stepm >= YEARM) hstepm=1;*/
     else strcpy(digitp,"-populbased-nomobil-");    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
   }    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   else   
     strcpy(digitp,"-stablbased-");    for (age=bage; age<=fage; age ++){
   
   if (mobilav!=0) {  
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){     
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       printf(" Error in movingaverage mobilav=%d\n",mobilav);     
     }      printf("%d|",(int)age);fflush(stdout);
   }      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
      
   strcpy(fileresprobmorprev,"prmorprev");   
   sprintf(digit,"%-d",ij);      /* Computing expectancies */
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/      for(i=1; i<=nlstate;i++)
   strcat(fileresprobmorprev,digit); /* Tvar to be done */        for(j=1; j<=nlstate;j++)
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   strcat(fileresprobmorprev,fileres);            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {           
     printf("Problem with resultfile: %s\n", fileresprobmorprev);            /*if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);  
   }          }
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);     
        fprintf(ficreseij,"%3.0f",age );
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);      for(i=1; i<=nlstate;i++){
   fprintf(ficresprobmorprev, "#Local time at start: %s", strstart);        eip=0;
   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);        for(j=1; j<=nlstate;j++){
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);          eip +=eij[i][j][(int)age];
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
     fprintf(ficresprobmorprev," p.%-d SE",j);        }
     for(i=1; i<=nlstate;i++)        fprintf(ficreseij,"%9.4f", eip );
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);      }
   }        fprintf(ficreseij,"\n");
   fprintf(ficresprobmorprev,"\n");     
   fprintf(ficgp,"\n# Routine varevsij");    }
  fprintf(fichtm, "#Local time at start: %s", strstart);    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   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");    printf("\n");
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);    fprintf(ficlog,"\n");
 /*   } */   
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);  }
  fprintf(ficresvij, "#Local time at start: %s", strstart);  
   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");  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(ficresvij,"# Age");  
   for(i=1; i<=nlstate;i++)  {
     for(j=1; j<=nlstate;j++)    /* Covariances of health expectancies eij and of total life expectancies according
       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);     to initial status i, ei. .
   fprintf(ficresvij,"\n");    */
     int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
   xp=vector(1,npar);    double age, agelim, hf;
   dnewm=matrix(1,nlstate,1,npar);    double ***p3matp, ***p3matm, ***varhe;
   doldm=matrix(1,nlstate,1,nlstate);    double **dnewm,**doldm;
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);    double *xp, *xm;
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    double **gp, **gm;
     double ***gradg, ***trgradg;
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);    int theta;
   gpp=vector(nlstate+1,nlstate+ndeath);  
   gmp=vector(nlstate+1,nlstate+ndeath);    double eip, vip;
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/  
       varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
   if(estepm < stepm){    xp=vector(1,npar);
     printf ("Problem %d lower than %d\n",estepm, stepm);    xm=vector(1,npar);
   }    dnewm=matrix(1,nlstate*nlstate,1,npar);
   else  hstepm=estepm;       doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
   /* 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.     pstamp(ficresstdeij);
      nhstepm is the number of hstepm from age to agelim     fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
      nstepm is the number of stepm from age to agelin.     fprintf(ficresstdeij,"# Age");
      Look at hpijx to understand the reason of that which relies in memory size    for(i=1; i<=nlstate;i++){
      and note for a fixed period like k years */      for(j=1; j<=nlstate;j++)
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the        fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
      survival function given by stepm (the optimization length). Unfortunately it      fprintf(ficresstdeij," e%1d. ",i);
      means that if the survival funtion is printed every two years of age and if    }
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     fprintf(ficresstdeij,"\n");
      results. So we changed our mind and took the option of the best precision.  
   */    pstamp(ficrescveij);
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
   agelim = AGESUP;    fprintf(ficrescveij,"# Age");
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    for(i=1; i<=nlstate;i++)
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */       for(j=1; j<=nlstate;j++){
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */        cptj= (j-1)*nlstate+i;
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        for(i2=1; i2<=nlstate;i2++)
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);          for(j2=1; j2<=nlstate;j2++){
     gp=matrix(0,nhstepm,1,nlstate);            cptj2= (j2-1)*nlstate+i2;
     gm=matrix(0,nhstepm,1,nlstate);            if(cptj2 <= cptj)
               fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
           }
     for(theta=1; theta <=npar; theta++){      }
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/    fprintf(ficrescveij,"\n");
         xp[i] = x[i] + (i==theta ?delti[theta]:0);   
       }    if(estepm < stepm){
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        printf ("Problem %d lower than %d\n",estepm, stepm);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    }
     else  hstepm=estepm;  
       if (popbased==1) {    /* We compute the life expectancy from trapezoids spaced every estepm months
         if(mobilav ==0){     * This is mainly to measure the difference between two models: for example
           for(i=1; i<=nlstate;i++)     * if stepm=24 months pijx are given only every 2 years and by summing them
             prlim[i][i]=probs[(int)age][i][ij];     * we are calculating an estimate of the Life Expectancy assuming a linear
         }else{ /* mobilav */      * progression in between and thus overestimating or underestimating according
           for(i=1; i<=nlstate;i++)     * to the curvature of the survival function. If, for the same date, we
             prlim[i][i]=mobaverage[(int)age][i][ij];     * estimate the model with stepm=1 month, we can keep estepm to 24 months
         }     * to compare the new estimate of Life expectancy with the same linear
       }     * hypothesis. A more precise result, taking into account a more precise
        * curvature will be obtained if estepm is as small as stepm. */
       for(j=1; j<= nlstate; j++){  
         for(h=0; h<=nhstepm; h++){    /* For example we decided to compute the life expectancy with the smallest unit */
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];       nhstepm is the number of hstepm from age to agelim
         }       nstepm is the number of stepm from age to agelin.
       }       Look at hpijx to understand the reason of that which relies in memory size
       /* This for computing probability of death (h=1 means       and note for a fixed period like estepm months */
          computed over hstepm matrices product = hstepm*stepm months)     /* We decided (b) to get a life expectancy respecting the most precise curvature of the
          as a weighted average of prlim.       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
       for(j=nlstate+1;j<=nlstate+ndeath;j++){       you sum them up and add 1 year (area under the trapezoids) you won't get the same
         for(i=1,gpp[j]=0.; i<= nlstate; i++)       results. So we changed our mind and took the option of the best precision.
           gpp[j] += prlim[i][i]*p3mat[i][j][1];    */
       }        hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
       /* end probability of death */  
     /* If stepm=6 months */
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */    /* nhstepm age range expressed in number of stepm */
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    agelim=AGESUP;
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);      nstepm=(int) rint((agelim-bage)*YEARM/stepm);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
      /* if (stepm >= YEARM) hstepm=1;*/
       if (popbased==1) {    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
         if(mobilav ==0){   
           for(i=1; i<=nlstate;i++)    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             prlim[i][i]=probs[(int)age][i][ij];    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         }else{ /* mobilav */     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
           for(i=1; i<=nlstate;i++)    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
             prlim[i][i]=mobaverage[(int)age][i][ij];    gp=matrix(0,nhstepm,1,nlstate*nlstate);
         }    gm=matrix(0,nhstepm,1,nlstate*nlstate);
       }  
     for (age=bage; age<=fage; age ++){
       for(j=1; j<= nlstate; j++){  
         for(h=0; h<=nhstepm; h++){      /* Computed by stepm unit matrices, product of hstepm matrices, stored
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];   
         }      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       }  
       /* This for computing probability of death (h=1 means      /* Computing  Variances of health expectancies */
          computed over hstepm matrices product = hstepm*stepm months)       /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
          as a weighted average of prlim.         decrease memory allocation */
       */      for(theta=1; theta <=npar; theta++){
       for(j=nlstate+1;j<=nlstate+ndeath;j++){        for(i=1; i<=npar; i++){
         for(i=1,gmp[j]=0.; i<= nlstate; i++)          xp[i] = x[i] + (i==theta ?delti[theta]:0);
          gmp[j] += prlim[i][i]*p3mat[i][j][1];          xm[i] = x[i] - (i==theta ?delti[theta]:0);
       }            }
       /* end probability of death */        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
         hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
       for(j=1; j<= nlstate; j++) /* vareij */   
         for(h=0; h<=nhstepm; h++){        for(j=1; j<= nlstate; j++){
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];          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.;
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */              gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];            }
       }          }
         }
     } /* End theta */       
         for(ij=1; ij<= nlstate*nlstate; ij++)
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */          for(h=0; h<=nhstepm-1; h++){
             gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
     for(h=0; h<=nhstepm; h++) /* veij */          }
       for(j=1; j<=nlstate;j++)      }/* End theta */
         for(theta=1; theta <=npar; theta++)     
           trgradg[h][j][theta]=gradg[h][theta][j];     
       for(h=0; h<=nhstepm-1; h++)
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */        for(j=1; j<=nlstate*nlstate;j++)
       for(theta=1; theta <=npar; theta++)          for(theta=1; theta <=npar; theta++)
         trgradgp[j][theta]=gradgp[theta][j];            trgradg[h][j][theta]=gradg[h][theta][j];
        
   
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */       for(ij=1;ij<=nlstate*nlstate;ij++)
     for(i=1;i<=nlstate;i++)        for(ji=1;ji<=nlstate*nlstate;ji++)
       for(j=1;j<=nlstate;j++)          varhe[ij][ji][(int)age] =0.;
         vareij[i][j][(int)age] =0.;  
        printf("%d|",(int)age);fflush(stdout);
     for(h=0;h<=nhstepm;h++){       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
       for(k=0;k<=nhstepm;k++){       for(h=0;h<=nhstepm-1;h++){
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);        for(k=0;k<=nhstepm-1;k++){
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);          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(ij=1;ij<=nlstate*nlstate;ij++)
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;            for(ji=1;ji<=nlstate*nlstate;ji++)
       }              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
     }        }
         }
     /* pptj */  
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);      /* Computing expectancies */
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
     for(j=nlstate+1;j<=nlstate+ndeath;j++)      for(i=1; i<=nlstate;i++)
       for(i=nlstate+1;i<=nlstate+ndeath;i++)        for(j=1; j<=nlstate;j++)
         varppt[j][i]=doldmp[j][i];          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
     /* end ppptj */            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
     /*  x centered again */           
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);              /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);  
            }
     if (popbased==1) {  
       if(mobilav ==0){      fprintf(ficresstdeij,"%3.0f",age );
         for(i=1; i<=nlstate;i++)      for(i=1; i<=nlstate;i++){
           prlim[i][i]=probs[(int)age][i][ij];        eip=0.;
       }else{ /* mobilav */         vip=0.;
         for(i=1; i<=nlstate;i++)        for(j=1; j<=nlstate;j++){
           prlim[i][i]=mobaverage[(int)age][i][ij];          eip += eij[i][j][(int)age];
       }          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]) );
     /* This for computing probability of death (h=1 means        }
        computed over hstepm (estepm) matrices product = hstepm*stepm months)         fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
        as a weighted average of prlim.      }
     */      fprintf(ficresstdeij,"\n");
     for(j=nlstate+1;j<=nlstate+ndeath;j++){  
       for(i=1,gmp[j]=0.;i<= nlstate; i++)       fprintf(ficrescveij,"%3.0f",age );
         gmp[j] += prlim[i][i]*p3mat[i][j][1];       for(i=1; i<=nlstate;i++)
     }            for(j=1; j<=nlstate;j++){
     /* end probability of death */          cptj= (j-1)*nlstate+i;
           for(i2=1; i2<=nlstate;i2++)
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);            for(j2=1; j2<=nlstate;j2++){
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){              cptj2= (j2-1)*nlstate+i2;
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));              if(cptj2 <= cptj)
       for(i=1; i<=nlstate;i++){                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);            }
       }        }
     }       fprintf(ficrescveij,"\n");
     fprintf(ficresprobmorprev,"\n");     
     }
     fprintf(ficresvij,"%.0f ",age );    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
     for(i=1; i<=nlstate;i++)    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
       for(j=1; j<=nlstate;j++){    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
       }    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     fprintf(ficresvij,"\n");    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     free_matrix(gp,0,nhstepm,1,nlstate);    printf("\n");
     free_matrix(gm,0,nhstepm,1,nlstate);    fprintf(ficlog,"\n");
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);  
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);    free_vector(xm,1,npar);
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    free_vector(xp,1,npar);
   } /* End age */    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
   free_vector(gpp,nlstate+1,nlstate+ndeath);    free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
   free_vector(gmp,nlstate+1,nlstate+ndeath);    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);  }
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/  
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");  /************ Variance ******************/
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */  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[])
   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); */    /* Variance of health expectancies */
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */    /* double **newm;*/
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));    double **dnewm,**doldm;
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));    double **dnewmp,**doldmp;
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));    int i, j, nhstepm, hstepm, h, nstepm ;
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));    int k, cptcode;
   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);    double *xp;
   /*  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);    double **gp, **gm;  /* for var eij */
 */    double ***gradg, ***trgradg; /*for var eij */
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */    double **gradgp, **trgradgp; /* for var p point j */
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);    double *gpp, *gmp; /* for var p point j */
     double **varppt; /* for var p point j nlstate to nlstate+ndeath */
   free_vector(xp,1,npar);    double ***p3mat;
   free_matrix(doldm,1,nlstate,1,nlstate);    double age,agelim, hf;
   free_matrix(dnewm,1,nlstate,1,npar);    double ***mobaverage;
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    int theta;
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);    char digit[4];
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    char digitp[25];
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  
   fclose(ficresprobmorprev);    char fileresprobmorprev[FILENAMELENGTH];
   fflush(ficgp);  
   fflush(fichtm);     if(popbased==1){
 }  /* end varevsij */      if(mobilav!=0)
         strcpy(digitp,"-populbased-mobilav-");
 /************ Variance of prevlim ******************/      else strcpy(digitp,"-populbased-nomobil-");
 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[])    }
 {    else
   /* Variance of prevalence limit */      strcpy(digitp,"-stablbased-");
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/  
   double **newm;    if (mobilav!=0) {
   double **dnewm,**doldm;      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   int i, j, nhstepm, hstepm;      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
   int k, cptcode;        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   double *xp;        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   double *gp, *gm;      }
   double **gradg, **trgradg;    }
   double age,agelim;  
   int theta;    strcpy(fileresprobmorprev,"prmorprev");
   fprintf(ficresvpl, "#Local time at start: %s", strstart);     sprintf(digit,"%-d",ij);
   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
   fprintf(ficresvpl,"# Age");    strcat(fileresprobmorprev,digit); /* Tvar to be done */
   for(i=1; i<=nlstate;i++)    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
       fprintf(ficresvpl," %1d-%1d",i,i);    strcat(fileresprobmorprev,fileres);
   fprintf(ficresvpl,"\n");    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
       printf("Problem with resultfile: %s\n", fileresprobmorprev);
   xp=vector(1,npar);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
   dnewm=matrix(1,nlstate,1,npar);    }
   doldm=matrix(1,nlstate,1,nlstate);    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
      
   hstepm=1*YEARM; /* Every year of age */    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */     pstamp(ficresprobmorprev);
   agelim = AGESUP;    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);
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
     if (stepm >= YEARM) hstepm=1;      fprintf(ficresprobmorprev," p.%-d SE",j);
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */      for(i=1; i<=nlstate;i++)
     gradg=matrix(1,npar,1,nlstate);        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
     gp=vector(1,nlstate);    }  
     gm=vector(1,nlstate);    fprintf(ficresprobmorprev,"\n");
     fprintf(ficgp,"\n# Routine varevsij");
     for(theta=1; theta <=npar; theta++){    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
       for(i=1; i<=npar; i++){ /* Computes gradient */    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");
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
       }  /*   } */
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
       for(i=1;i<=nlstate;i++)    pstamp(ficresvij);
         gp[i] = prlim[i][i];    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
         if(popbased==1)
       for(i=1; i<=npar; i++) /* Computes gradient */      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    else
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
       for(i=1;i<=nlstate;i++)    fprintf(ficresvij,"# Age");
         gm[i] = prlim[i][i];    for(i=1; i<=nlstate;i++)
       for(j=1; j<=nlstate;j++)
       for(i=1;i<=nlstate;i++)        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];    fprintf(ficresvij,"\n");
     } /* End theta */  
     xp=vector(1,npar);
     trgradg =matrix(1,nlstate,1,npar);    dnewm=matrix(1,nlstate,1,npar);
     doldm=matrix(1,nlstate,1,nlstate);
     for(j=1; j<=nlstate;j++)    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
       for(theta=1; theta <=npar; theta++)    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
         trgradg[j][theta]=gradg[theta][j];  
     gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
     for(i=1;i<=nlstate;i++)    gpp=vector(nlstate+1,nlstate+ndeath);
       varpl[i][(int)age] =0.;    gmp=vector(nlstate+1,nlstate+ndeath);
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);   
     for(i=1;i<=nlstate;i++)    if(estepm < stepm){
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */      printf ("Problem %d lower than %d\n",estepm, stepm);
     }
     fprintf(ficresvpl,"%.0f ",age );    else  hstepm=estepm;  
     for(i=1; i<=nlstate;i++)    /* For example we decided to compute the life expectancy with the smallest unit */
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
     fprintf(ficresvpl,"\n");       nhstepm is the number of hstepm from age to agelim
     free_vector(gp,1,nlstate);       nstepm is the number of stepm from age to agelin.
     free_vector(gm,1,nlstate);       Look at hpijx to understand the reason of that which relies in memory size
     free_matrix(gradg,1,npar,1,nlstate);       and note for a fixed period like k years */
     free_matrix(trgradg,1,nlstate,1,npar);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   } /* End age */       survival function given by stepm (the optimization length). Unfortunately it
        means that if the survival funtion is printed every two years of age and if
   free_vector(xp,1,npar);       you sum them up and add 1 year (area under the trapezoids) you won't get the same
   free_matrix(doldm,1,nlstate,1,npar);       results. So we changed our mind and took the option of the best precision.
   free_matrix(dnewm,1,nlstate,1,nlstate);    */
     hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
 }    agelim = AGESUP;
     for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 /************ Variance of one-step probabilities  ******************/      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 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[])      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 {      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int i, j=0,  i1, k1, l1, t, tj;      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
   int k2, l2, j1,  z1;      gp=matrix(0,nhstepm,1,nlstate);
   int k=0,l, cptcode;      gm=matrix(0,nhstepm,1,nlstate);
   int first=1, first1;  
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;  
   double **dnewm,**doldm;      for(theta=1; theta <=npar; theta++){
   double *xp;        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
   double *gp, *gm;          xp[i] = x[i] + (i==theta ?delti[theta]:0);
   double **gradg, **trgradg;        }
   double **mu;        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
   double age,agelim, cov[NCOVMAX];        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */  
   int theta;        if (popbased==1) {
   char fileresprob[FILENAMELENGTH];          if(mobilav ==0){
   char fileresprobcov[FILENAMELENGTH];            for(i=1; i<=nlstate;i++)
   char fileresprobcor[FILENAMELENGTH];              prlim[i][i]=probs[(int)age][i][ij];
           }else{ /* mobilav */
   double ***varpij;            for(i=1; i<=nlstate;i++)
               prlim[i][i]=mobaverage[(int)age][i][ij];
   strcpy(fileresprob,"prob");           }
   strcat(fileresprob,fileres);        }
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {   
     printf("Problem with resultfile: %s\n", fileresprob);        for(j=1; j<= nlstate; j++){
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);          for(h=0; h<=nhstepm; h++){
   }            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
   strcpy(fileresprobcov,"probcov");               gp[h][j] += prlim[i][i]*p3mat[i][j][h];
   strcat(fileresprobcov,fileres);          }
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {        }
     printf("Problem with resultfile: %s\n", fileresprobcov);        /* This for computing probability of death (h=1 means
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);           computed over hstepm matrices product = hstepm*stepm months)
   }           as a weighted average of prlim.
   strcpy(fileresprobcor,"probcor");         */
   strcat(fileresprobcor,fileres);        for(j=nlstate+1;j<=nlstate+ndeath;j++){
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {          for(i=1,gpp[j]=0.; i<= nlstate; i++)
     printf("Problem with resultfile: %s\n", fileresprobcor);            gpp[j] += prlim[i][i]*p3mat[i][j][1];
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);        }    
   }        /* end probability of death */
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);  
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);          xp[i] = x[i] - (i==theta ?delti[theta]:0);
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);   
   fprintf(ficresprob, "#Local time at start: %s", strstart);        if (popbased==1) {
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");          if(mobilav ==0){
   fprintf(ficresprob,"# Age");            for(i=1; i<=nlstate;i++)
   fprintf(ficresprobcov, "#Local time at start: %s", strstart);              prlim[i][i]=probs[(int)age][i][ij];
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");          }else{ /* mobilav */
   fprintf(ficresprobcov,"# Age");            for(i=1; i<=nlstate;i++)
   fprintf(ficresprobcor, "#Local time at start: %s", strstart);              prlim[i][i]=mobaverage[(int)age][i][ij];
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");          }
   fprintf(ficresprobcov,"# Age");        }
   
         for(j=1; j<= nlstate; j++){
   for(i=1; i<=nlstate;i++)          for(h=0; h<=nhstepm; h++){
     for(j=1; j<=(nlstate+ndeath);j++){            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
       fprintf(ficresprobcov," p%1d-%1d ",i,j);          }
       fprintf(ficresprobcor," p%1d-%1d ",i,j);        }
     }          /* This for computing probability of death (h=1 means
  /* fprintf(ficresprob,"\n");           computed over hstepm matrices product = hstepm*stepm months)
   fprintf(ficresprobcov,"\n");           as a weighted average of prlim.
   fprintf(ficresprobcor,"\n");        */
  */        for(j=nlstate+1;j<=nlstate+ndeath;j++){
  xp=vector(1,npar);          for(i=1,gmp[j]=0.; i<= nlstate; i++)
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);           gmp[j] += prlim[i][i]*p3mat[i][j][1];
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));        }    
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);        /* end probability of death */
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);  
   first=1;        for(j=1; j<= nlstate; j++) /* vareij */
   fprintf(ficgp,"\n# Routine varprob");          for(h=0; h<=nhstepm; h++){
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
   fprintf(fichtm,"\n");          }
   
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
   file %s<br>\n",optionfilehtmcov);        }
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\  
 and drawn. It helps understanding how is the covariance between two incidences.\      } /* End theta */
  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. \      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \  
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \      for(h=0; h<=nhstepm; h++) /* veij */
 standard deviations wide on each axis. <br>\        for(j=1; j<=nlstate;j++)
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\          for(theta=1; theta <=npar; theta++)
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\            trgradg[h][j][theta]=gradg[h][theta][j];
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");  
       for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
   cov[1]=1;        for(theta=1; theta <=npar; theta++)
   tj=cptcoveff;          trgradgp[j][theta]=gradgp[theta][j];
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}   
   j1=0;  
   for(t=1; t<=tj;t++){      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     for(i1=1; i1<=ncodemax[t];i1++){       for(i=1;i<=nlstate;i++)
       j1++;        for(j=1;j<=nlstate;j++)
       if  (cptcovn>0) {          vareij[i][j][(int)age] =0.;
         fprintf(ficresprob, "\n#********** Variable ");   
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      for(h=0;h<=nhstepm;h++){
         fprintf(ficresprob, "**********\n#\n");        for(k=0;k<=nhstepm;k++){
         fprintf(ficresprobcov, "\n#********** Variable ");           matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
         fprintf(ficresprobcov, "**********\n#\n");          for(i=1;i<=nlstate;i++)
                     for(j=1;j<=nlstate;j++)
         fprintf(ficgp, "\n#********** Variable ");               vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);        }
         fprintf(ficgp, "**********\n#\n");      }
            
               /* pptj */
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");       matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                 for(i=nlstate+1;i<=nlstate+ndeath;i++)
         fprintf(ficresprobcor, "\n#********** Variable ");              varppt[j][i]=doldmp[j][i];
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      /* end ppptj */
         fprintf(ficresprobcor, "**********\n#");          /*  x centered again */
       }      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
             prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
       for (age=bage; age<=fage; age ++){    
         cov[2]=age;      if (popbased==1) {
         for (k=1; k<=cptcovn;k++) {        if(mobilav ==0){
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];          for(i=1; i<=nlstate;i++)
         }            prlim[i][i]=probs[(int)age][i][ij];
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];        }else{ /* mobilav */
         for (k=1; k<=cptcovprod;k++)          for(i=1; i<=nlstate;i++)
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];            prlim[i][i]=mobaverage[(int)age][i][ij];
                 }
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));      }
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);               
         gp=vector(1,(nlstate)*(nlstate+ndeath));      /* This for computing probability of death (h=1 means
         gm=vector(1,(nlstate)*(nlstate+ndeath));         computed over hstepm (estepm) matrices product = hstepm*stepm months)
              as a weighted average of prlim.
         for(theta=1; theta <=npar; theta++){      */
           for(i=1; i<=npar; i++)      for(j=nlstate+1;j<=nlstate+ndeath;j++){
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);        for(i=1,gmp[j]=0.;i<= nlstate; i++)
                     gmp[j] += prlim[i][i]*p3mat[i][j][1];
           pmij(pmmij,cov,ncovmodel,xp,nlstate);      }    
                 /* end probability of death */
           k=0;  
           for(i=1; i<= (nlstate); i++){      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
             for(j=1; j<=(nlstate+ndeath);j++){      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
               k=k+1;        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
               gp[k]=pmmij[i][j];        for(i=1; i<=nlstate;i++){
             }          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
           }        }
                 }
           for(i=1; i<=npar; i++)      fprintf(ficresprobmorprev,"\n");
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);  
           fprintf(ficresvij,"%.0f ",age );
           pmij(pmmij,cov,ncovmodel,xp,nlstate);      for(i=1; i<=nlstate;i++)
           k=0;        for(j=1; j<=nlstate;j++){
           for(i=1; i<=(nlstate); i++){          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
             for(j=1; j<=(nlstate+ndeath);j++){        }
               k=k+1;      fprintf(ficresvij,"\n");
               gm[k]=pmmij[i][j];      free_matrix(gp,0,nhstepm,1,nlstate);
             }      free_matrix(gm,0,nhstepm,1,nlstate);
           }      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
            free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];      } /* End age */
         }    free_vector(gpp,nlstate+1,nlstate+ndeath);
     free_vector(gmp,nlstate+1,nlstate+ndeath);
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
           for(theta=1; theta <=npar; theta++)    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
             trgradg[j][theta]=gradg[theta][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 */
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);     fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);  /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);    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));
         pmij(pmmij,cov,ncovmodel,x,nlstate);    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
             fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
         k=0;    /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);
         for(i=1; i<=(nlstate); i++){  */
           for(j=1; j<=(nlstate+ndeath);j++){  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
             k=k+1;    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
             mu[k][(int) age]=pmmij[i][j];  
           }    free_vector(xp,1,npar);
         }    free_matrix(doldm,1,nlstate,1,nlstate);
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)    free_matrix(dnewm,1,nlstate,1,npar);
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
             varpij[i][j][(int)age] = doldm[i][j];    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
     free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
         /*printf("\n%d ",(int)age);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){    fclose(ficresprobmorprev);
           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));    fflush(ficgp);
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));    fflush(fichtm);
           }*/  }  /* end varevsij */
   
         fprintf(ficresprob,"\n%d ",(int)age);  /************ Variance of prevlim ******************/
         fprintf(ficresprobcov,"\n%d ",(int)age);  void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])
         fprintf(ficresprobcor,"\n%d ",(int)age);  {
     /* Variance of prevalence limit */
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));    double **newm;
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){    double **dnewm,**doldm;
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);    int i, j, nhstepm, hstepm;
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);    int k, cptcode;
         }    double *xp;
         i=0;    double *gp, *gm;
         for (k=1; k<=(nlstate);k++){    double **gradg, **trgradg;
           for (l=1; l<=(nlstate+ndeath);l++){     double age,agelim;
             i=i++;    int theta;
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);   
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);    pstamp(ficresvpl);
             for (j=1; j<=i;j++){    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);    fprintf(ficresvpl,"# Age");
               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++)
             }        fprintf(ficresvpl," %1d-%1d",i,i);
           }    fprintf(ficresvpl,"\n");
         }/* end of loop for state */  
       } /* end of loop for age */    xp=vector(1,npar);
     dnewm=matrix(1,nlstate,1,npar);
       /* Confidence intervalle of pij  */    doldm=matrix(1,nlstate,1,nlstate);
       /*   
         fprintf(ficgp,"\nset noparametric;unset label");    hstepm=1*YEARM; /* Every year of age */
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");    agelim = AGESUP;
         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 (age=bage; age<=fage; age ++){ /* If stepm=6 months */
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);      if (stepm >= YEARM) hstepm=1;
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
       */      gradg=matrix(1,npar,1,nlstate);
       gp=vector(1,nlstate);
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/      gm=vector(1,nlstate);
       first1=1;  
       for (k2=1; k2<=(nlstate);k2++){      for(theta=1; theta <=npar; theta++){
         for (l2=1; l2<=(nlstate+ndeath);l2++){         for(i=1; i<=npar; i++){ /* Computes gradient */
           if(l2==k2) continue;          xp[i] = x[i] + (i==theta ?delti[theta]:0);
           j=(k2-1)*(nlstate+ndeath)+l2;        }
           for (k1=1; k1<=(nlstate);k1++){        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
             for (l1=1; l1<=(nlstate+ndeath);l1++){         for(i=1;i<=nlstate;i++)
               if(l1==k1) continue;          gp[i] = prlim[i][i];
               i=(k1-1)*(nlstate+ndeath)+l1;     
               if(i<=j) continue;        for(i=1; i<=npar; i++) /* Computes gradient */
               for (age=bage; age<=fage; age ++){           xp[i] = x[i] - (i==theta ?delti[theta]:0);
                 if ((int)age %5==0){        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;        for(i=1;i<=nlstate;i++)
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;          gm[i] = prlim[i][i];
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;  
                   mu1=mu[i][(int) age]/stepm*YEARM ;        for(i=1;i<=nlstate;i++)
                   mu2=mu[j][(int) age]/stepm*YEARM;          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   c12=cv12/sqrt(v1*v2);      } /* End theta */
                   /* Computing eigen value of matrix of covariance */  
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;      trgradg =matrix(1,nlstate,1,npar);
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  
                   /* Eigen vectors */      for(j=1; j<=nlstate;j++)
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));        for(theta=1; theta <=npar; theta++)
                   /*v21=sqrt(1.-v11*v11); *//* error */          trgradg[j][theta]=gradg[theta][j];
                   v21=(lc1-v1)/cv12*v11;  
                   v12=-v21;      for(i=1;i<=nlstate;i++)
                   v22=v11;        varpl[i][(int)age] =0.;
                   tnalp=v21/v11;      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   if(first1==1){      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                     first1=0;      for(i=1;i<=nlstate;i++)
                     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);        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   }  
                   fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);      fprintf(ficresvpl,"%.0f ",age );
                   /*printf(fignu*/      for(i=1; i<=nlstate;i++)
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */      fprintf(ficresvpl,"\n");
                   if(first==1){      free_vector(gp,1,nlstate);
                     first=0;      free_vector(gm,1,nlstate);
                     fprintf(ficgp,"\nset parametric;unset label");      free_matrix(gradg,1,npar,1,nlstate);
                     fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);      free_matrix(trgradg,1,nlstate,1,npar);
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");    } /* End age */
                     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\">\    free_vector(xp,1,npar);
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\    free_matrix(doldm,1,nlstate,1,npar);
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\    free_matrix(dnewm,1,nlstate,1,nlstate);
                             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);  /************ Variance of one-step probabilities  ******************/
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);  void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);  {
                     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",\    int i, j=0,  i1, k1, l1, t, tj;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\    int k2, l2, j1,  z1;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    int k=0,l, cptcode;
                   }else{    int first=1, first1;
                     first=0;    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);    double **dnewm,**doldm;
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);    double *xp;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);    double *gp, *gm;
                     fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\    double **gradg, **trgradg;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\    double **mu;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    double age,agelim, cov[NCOVMAX];
                   }/* if first */    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                 } /* age mod 5 */    int theta;
               } /* end loop age */    char fileresprob[FILENAMELENGTH];
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    char fileresprobcov[FILENAMELENGTH];
               first=1;    char fileresprobcor[FILENAMELENGTH];
             } /*l12 */  
           } /* k12 */    double ***varpij;
         } /*l1 */  
       }/* k1 */    strcpy(fileresprob,"prob");
     } /* loop covariates */    strcat(fileresprob,fileres);
   }    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);      printf("Problem with resultfile: %s\n", fileresprob);
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
   free_vector(xp,1,npar);    }
   fclose(ficresprob);    strcpy(fileresprobcov,"probcov");
   fclose(ficresprobcov);    strcat(fileresprobcov,fileres);
   fclose(ficresprobcor);    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
   fflush(ficgp);      printf("Problem with resultfile: %s\n", fileresprobcov);
   fflush(fichtmcov);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 }    }
     strcpy(fileresprobcor,"probcor");
     strcat(fileresprobcor,fileres);
 /******************* Printing html file ***********/    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \      printf("Problem with resultfile: %s\n", fileresprobcor);
                   int lastpass, int stepm, int weightopt, char model[],\      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\    }
                   int popforecast, int estepm ,\    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   double jprev1, double mprev1,double anprev1, \    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   double jprev2, double mprev2,double anprev2){    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
   int jj1, k1, i1, cpt;    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
     printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
    fprintf(fichtm,"<ul><li><h4>Result files (first order: no variance)</h4>\n \    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",    pstamp(ficresprob);
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
    fprintf(fichtm,"\    fprintf(ficresprob,"# Age");
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",    pstamp(ficresprobcov);
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
    fprintf(fichtm,"\    fprintf(ficresprobcov,"# Age");
  - Stable prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",    pstamp(ficresprobcor);
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
    fprintf(fichtm,"\    fprintf(ficresprobcor,"# Age");
  - Life expectancies by age and initial health status (estepm=%2d months): \  
    <a href=\"%s\">%s</a> <br>\n</li>",  
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));    for(i=1; i<=nlstate;i++)
       for(j=1; j<=(nlstate+ndeath);j++){
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
         fprintf(ficresprobcov," p%1d-%1d ",i,j);
  m=cptcoveff;        fprintf(ficresprobcor," p%1d-%1d ",i,j);
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}      }  
    /* fprintf(ficresprob,"\n");
  jj1=0;    fprintf(ficresprobcov,"\n");
  for(k1=1; k1<=m;k1++){    fprintf(ficresprobcor,"\n");
    for(i1=1; i1<=ncodemax[k1];i1++){   */
      jj1++;   xp=vector(1,npar);
      if (cptcovn > 0) {    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
        for (cpt=1; cpt<=cptcoveff;cpt++)     mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");    first=1;
      }    fprintf(ficgp,"\n# Routine varprob");
      /* Pij */    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
      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> \    fprintf(fichtm,"\n");
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);       
      /* Quasi-incidences */    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: %s%d2.png<br> \    file %s<br>\n",optionfilehtmcov);
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
        /* Stable prevalence in each health state */  and drawn. It helps understanding how is the covariance between two incidences.\
        for(cpt=1; cpt<nlstate;cpt++){   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
          fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br> \    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. \
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
        }  would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
      for(cpt=1; cpt<=nlstate;cpt++) {  standard deviations wide on each axis. <br>\
         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): %s%d%d.png <br> \   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
      }  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
    } /* end i1 */  
  }/* End k1 */    cov[1]=1;
  fprintf(fichtm,"</ul>");    tj=cptcoveff;
     if (cptcovn<1) {tj=1;ncodemax[1]=1;}
     j1=0;
  fprintf(fichtm,"\    for(t=1; t<=tj;t++){
 \n<br><li><h4> Result files (second order: variances)</h4>\n\      for(i1=1; i1<=ncodemax[t];i1++){
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);        j1++;
         if  (cptcovn>0) {
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",          fprintf(ficresprob, "\n#********** Variable ");
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
  fprintf(fichtm,"\          fprintf(ficresprob, "**********\n#\n");
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",          fprintf(ficresprobcov, "\n#********** Variable ");
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           fprintf(ficresprobcov, "**********\n#\n");
  fprintf(fichtm,"\         
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",          fprintf(ficgp, "\n#********** Variable ");
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
  fprintf(fichtm,"\          fprintf(ficgp, "**********\n#\n");
  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"%s\">%s</a><br>\n",         
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));         
  fprintf(fichtm,"\          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
  - Health expectancies with their variances (no covariance): <a href=\"%s\">%s</a> <br>\n",          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
  fprintf(fichtm,"\         
  - Standard deviation of stable prevalences: <a href=\"%s\">%s</a> <br>\n",\          fprintf(ficresprobcor, "\n#********** Variable ");    
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           fprintf(ficresprobcor, "**********\n#");    
 /*  if(popforecast==1) fprintf(fichtm,"\n */        }
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */       
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */        for (age=bage; age<=fage; age ++){
 /*      <br>",fileres,fileres,fileres,fileres); */          cov[2]=age;
 /*  else  */          for (k=1; k<=cptcovn;k++) {
 /*    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); */            cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
  fflush(fichtm);          }
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           for (k=1; k<=cptcovprod;k++)
  m=cptcoveff;            cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}         
           gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
  jj1=0;          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
  for(k1=1; k1<=m;k1++){          gp=vector(1,(nlstate)*(nlstate+ndeath));
    for(i1=1; i1<=ncodemax[k1];i1++){          gm=vector(1,(nlstate)*(nlstate+ndeath));
      jj1++;     
      if (cptcovn > 0) {          for(theta=1; theta <=npar; theta++){
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");            for(i=1; i<=npar; i++)
        for (cpt=1; cpt<=cptcoveff;cpt++)               xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);           
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");            pmij(pmmij,cov,ncovmodel,xp,nlstate);
      }           
      for(cpt=1; cpt<=nlstate;cpt++) {            k=0;
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \            for(i=1; i<= (nlstate); i++){
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\              for(j=1; j<=(nlstate+ndeath);j++){
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);                  k=k+1;
      }                gp[k]=pmmij[i][j];
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \              }
 health expectancies in states (1) and (2): %s%d.png<br>\            }
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);           
    } /* end i1 */            for(i=1; i<=npar; i++)
  }/* End k1 */              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
  fprintf(fichtm,"</ul>");     
  fflush(fichtm);            pmij(pmmij,cov,ncovmodel,xp,nlstate);
 }            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;
                 gm[k]=pmmij[i][j];
   char dirfileres[132],optfileres[132];              }
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;            }
   int ng;       
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
 /*     printf("Problem with file %s",optionfilegnuplot); */              gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */          }
 /*   } */  
           for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
   /*#ifdef windows */            for(theta=1; theta <=npar; theta++)
   fprintf(ficgp,"cd \"%s\" \n",pathc);              trgradg[j][theta]=gradg[theta][j];
     /*#endif */         
   m=pow(2,cptcoveff);          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);
   strcpy(dirfileres,optionfilefiname);          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
   strcpy(optfileres,"vpl");          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
  /* 1eme*/          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
   for (cpt=1; cpt<= nlstate ; cpt ++) {          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
    for (k1=1; k1<= m ; k1 ++) {  
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);          pmij(pmmij,cov,ncovmodel,x,nlstate);
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);         
      fprintf(ficgp,"set xlabel \"Age\" \n\          k=0;
 set ylabel \"Probability\" \n\          for(i=1; i<=(nlstate); i++){
 set ter png small\n\            for(j=1; j<=(nlstate+ndeath);j++){
 set size 0.65,0.65\n\              k=k+1;
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);              mu[k][(int) age]=pmmij[i][j];
             }
      for (i=1; i<= nlstate ; i ++) {          }
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
        else fprintf(ficgp," \%%*lf (\%%*lf)");            for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
      }              varpij[i][j][(int)age] = doldm[i][j];
      fprintf(ficgp,"\" t\"Stable prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);  
      for (i=1; i<= nlstate ; i ++) {          /*printf("\n%d ",(int)age);
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");            for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
        else fprintf(ficgp," \%%*lf (\%%*lf)");            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
      }             fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][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);             }*/
      for (i=1; i<= nlstate ; i ++) {  
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");          fprintf(ficresprob,"\n%d ",(int)age);
        else fprintf(ficgp," \%%*lf (\%%*lf)");          fprintf(ficresprobcov,"\n%d ",(int)age);
      }            fprintf(ficresprobcor,"\n%d ",(int)age);
      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));  
    }          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
   }            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
   /*2 eme*/          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
               fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
   for (k1=1; k1<= m ; k1 ++) {             fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
     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);          i=0;
               for (k=1; k<=(nlstate);k++){
     for (i=1; i<= nlstate+1 ; i ++) {            for (l=1; l<=(nlstate+ndeath);l++){
       k=2*i;              i=i++;
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
       for (j=1; j<= nlstate+1 ; j ++) {              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");              for (j=1; j<=i;j++){
         else fprintf(ficgp," \%%*lf (\%%*lf)");                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
       }                   fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");              }
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);            }
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);          }/* end of loop for state */
       for (j=1; j<= nlstate+1 ; j ++) {        } /* end of loop for age */
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");  
         else fprintf(ficgp," \%%*lf (\%%*lf)");        /* Confidence intervalle of pij  */
       }           /*
       fprintf(ficgp,"\" t\"\" w l 0,");          fprintf(ficgp,"\nset noparametric;unset label");
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
       for (j=1; j<= nlstate+1 ; j ++) {          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");          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);
         else fprintf(ficgp," \%%*lf (\%%*lf)");          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
       }             fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
       else fprintf(ficgp,"\" t\"\" w l 0,");        */
     }  
   }        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
           first1=1;
   /*3eme*/        for (k2=1; k2<=(nlstate);k2++){
             for (l2=1; l2<=(nlstate+ndeath);l2++){
   for (k1=1; k1<= m ; k1 ++) {             if(l2==k2) continue;
     for (cpt=1; cpt<= nlstate ; cpt ++) {            j=(k2-1)*(nlstate+ndeath)+l2;
       k=2+nlstate*(2*cpt-2);            for (k1=1; k1<=(nlstate);k1++){
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);              for (l1=1; l1<=(nlstate+ndeath);l1++){
       fprintf(ficgp,"set ter png small\n\                if(l1==k1) continue;
 set size 0.65,0.65\n\                i=(k1-1)*(nlstate+ndeath)+l1;
 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);                if(i<=j) continue;
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);                for (age=bage; age<=fage; age ++){
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");                  if ((int)age %5==0){
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
         fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);                    mu1=mu[i][(int) age]/stepm*YEARM ;
                             mu2=mu[j][(int) age]/stepm*YEARM;
       */                    c12=cv12/sqrt(v1*v2);
       for (i=1; i< nlstate ; i ++) {                    /* Computing eigen value of matrix of covariance */
         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);                    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.;
       }                     /* Eigen vectors */
     }                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
   }                    /*v21=sqrt(1.-v11*v11); *//* error */
                       v21=(lc1-v1)/cv12*v11;
   /* CV preval stable (period) */                    v12=-v21;
   for (k1=1; k1<= m ; k1 ++) {                     v22=v11;
     for (cpt=1; cpt<=nlstate ; cpt ++) {                    tnalp=v21/v11;
       k=3;                    if(first1==1){
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);                      first1=0;
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\                      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);
 set ter png small\nset size 0.65,0.65\n\                    }
 unset log y\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);
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);                    /*printf(fignu*/
                           /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
       for (i=1; i< nlstate ; i ++)                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
         fprintf(ficgp,"+$%d",k+i+1);                    if(first==1){
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);                      first=0;
                             fprintf(ficgp,"\nset parametric;unset label");
       l=3+(nlstate+ndeath)*cpt;                      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,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
       for (i=1; i< nlstate ; i ++) {                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
         l=3+(nlstate+ndeath)*cpt;   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
         fprintf(ficgp,"+$%d",l+i+1);  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
       }                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);                                 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);
   /* proba elementaires */                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
   for(i=1,jk=1; i <=nlstate; i++){                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
     for(k=1; k <=(nlstate+ndeath); k++){                      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",\
       if (k != i) {                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
         for(j=1; j <=ncovmodel; j++){                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);                    }else{
           jk++;                       first=0;
           fprintf(ficgp,"\n");                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
         }                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
       }                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
     }                      fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
    }                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                               mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/                    }/* if first */
      for(jk=1; jk <=m; jk++) {                  } /* age mod 5 */
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);                 } /* end loop age */
        if (ng==2)                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");                first=1;
        else              } /*l12 */
          fprintf(ficgp,"\nset title \"Probability\"\n");            } /* k12 */
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);          } /*l1 */
        i=1;        }/* k1 */
        for(k2=1; k2<=nlstate; k2++) {      } /* loop covariates */
          k3=i;    }
          for(k=1; k<=(nlstate+ndeath); k++) {    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
            if (k != k2){    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
              if(ng==2)    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
              else    free_vector(xp,1,npar);
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);    fclose(ficresprob);
              ij=1;    fclose(ficresprobcov);
              for(j=3; j <=ncovmodel; j++) {    fclose(ficresprobcor);
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {    fflush(ficgp);
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);    fflush(fichtmcov);
                  ij++;  }
                }  
                else  
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);  /******************* Printing html file ***********/
              }  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
              fprintf(ficgp,")/(1");                    int lastpass, int stepm, int weightopt, char model[],\
                                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
              for(k1=1; k1 <=nlstate; k1++){                       int popforecast, int estepm ,\
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);                    double jprev1, double mprev1,double anprev1, \
                ij=1;                    double jprev2, double mprev2,double anprev2){
                for(j=3; j <=ncovmodel; j++){    int jj1, k1, i1, cpt;
                  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]]]);     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                    ij++;     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                  }  </ul>");
                  else     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                }             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                fprintf(ficgp,")");     fprintf(fichtm,"\
              }   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");     fprintf(fichtm,"\
              i=i+ncovmodel;   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
            }             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
          } /* end k */     fprintf(fichtm,"\
        } /* end k2 */   - (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): \
      } /* end jk */     <a href=\"%s\">%s</a> <br>\n",
    } /* end ng */             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
    fflush(ficgp);      fprintf(fichtm,"\
 }  /* end gnuplot */   - Population projections by age and states: \
      <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
   
 /*************** Moving average **************/  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){  
    m=cptcoveff;
   int i, cpt, cptcod;   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   int modcovmax =1;  
   int mobilavrange, mob;   jj1=0;
   double age;   for(k1=1; k1<=m;k1++){
      for(i1=1; i1<=ncodemax[k1];i1++){
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose        jj1++;
                            a covariate has 2 modalities */       if (cptcovn > 0) {
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
          for (cpt=1; cpt<=cptcoveff;cpt++)
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
     if(mobilav==1) mobilavrange=5; /* default */         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
     else mobilavrange=mobilav;       }
     for (age=bage; age<=fage; age++)       /* Pij */
       for (i=1; i<=nlstate;i++)       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \
         for (cptcod=1;cptcod<=modcovmax;cptcod++)  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];       /* Quasi-incidences */
     /* We keep the original values on the extreme ages bage, fage and for        fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2   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> \
        we use a 5 terms etc. until the borders are no more concerned.   <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
     */          /* Period (stable) prevalence in each health state */
     for (mob=3;mob <=mobilavrange;mob=mob+2){         for(cpt=1; cpt<nlstate;cpt++){
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
         for (i=1; i<=nlstate;i++){  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
           for (cptcod=1;cptcod<=modcovmax;cptcod++){         }
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];       for(cpt=1; cpt<=nlstate;cpt++) {
               for (cpt=1;cpt<=(mob-1)/2;cpt++){          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> \
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];       }
               }     } /* end i1 */
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;   }/* End k1 */
           }   fprintf(fichtm,"</ul>");
         }  
       }/* end age */  
     }/* end mob */   fprintf(fichtm,"\
   }else return -1;  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
   return 0;   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 }/* End movingaverage */  
    fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
            subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 /************** Forecasting ******************/   fprintf(fichtm,"\
 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){   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
   /* proj1, year, month, day of starting projection            subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
      agemin, agemax range of age  
      dateprev1 dateprev2 range of dates during which prevalence is computed   fprintf(fichtm,"\
      anproj2 year of en of projection (same day and month as proj1).   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
   */           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;   fprintf(fichtm,"\
   int *popage;   - 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): \
   double agec; /* generic age */     <a href=\"%s\">%s</a> <br>\n</li>",
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
   double *popeffectif,*popcount;   fprintf(fichtm,"\
   double ***p3mat;   - (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): \
   double ***mobaverage;     <a href=\"%s\">%s</a> <br>\n</li>",
   char fileresf[FILENAMELENGTH];             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
    fprintf(fichtm,"\
   agelim=AGESUP;   - 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",
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);           estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
     fprintf(fichtm,"\
   strcpy(fileresf,"f");    - 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",
   strcat(fileresf,fileres);           subdirf2(fileres,"t"),subdirf2(fileres,"t"));
   if((ficresf=fopen(fileresf,"w"))==NULL) {   fprintf(fichtm,"\
     printf("Problem with forecast resultfile: %s\n", fileresf);   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
   }  
   printf("Computing forecasting: result on file '%s' \n", fileresf);  /*  if(popforecast==1) fprintf(fichtm,"\n */
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
   /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
   if (cptcoveff==0) ncodemax[cptcoveff]=1;  /*      <br>",fileres,fileres,fileres,fileres); */
   /*  else  */
   if (mobilav!=0) {  /*    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); */
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);   fflush(fichtm);
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);  
       printf(" Error in movingaverage mobilav=%d\n",mobilav);   m=cptcoveff;
     }   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
   }  
    jj1=0;
   stepsize=(int) (stepm+YEARM-1)/YEARM;   for(k1=1; k1<=m;k1++){
   if (stepm<=12) stepsize=1;     for(i1=1; i1<=ncodemax[k1];i1++){
   if(estepm < stepm){       jj1++;
     printf ("Problem %d lower than %d\n",estepm, stepm);       if (cptcovn > 0) {
   }         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
   else  hstepm=estepm;            for (cpt=1; cpt<=cptcoveff;cpt++)
            fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
   hstepm=hstepm/stepm;          fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and       }
                                fractional in yp1 */       for(cpt=1; cpt<=nlstate;cpt++) {
   anprojmean=yp;         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
   yp2=modf((yp1*12),&yp);  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
   mprojmean=yp;  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
   yp1=modf((yp2*30.5),&yp);       }
   jprojmean=yp;       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
   if(jprojmean==0) jprojmean=1;  health expectancies in states (1) and (2): %s%d.png<br>\
   if(mprojmean==0) jprojmean=1;  <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
      } /* end i1 */
   i1=cptcoveff;   }/* End k1 */
   if (cptcovn < 1){i1=1;}   fprintf(fichtm,"</ul>");
      fflush(fichtm);
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);   }
     
   fprintf(ficresf,"#****** Routine prevforecast **\n");  /******************* Gnuplot file **************/
   void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 /*            if (h==(int)(YEARM*yearp)){ */  
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){    char dirfileres[132],optfileres[132];
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
       k=k+1;    int ng;
       fprintf(ficresf,"\n#******");  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
       for(j=1;j<=cptcoveff;j++) {  /*     printf("Problem with file %s",optionfilegnuplot); */
         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(ficlog,"Problem with file %s",optionfilegnuplot); */
       }  /*   } */
       fprintf(ficresf,"******\n");  
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");    /*#ifdef windows */
       for(j=1; j<=nlstate+ndeath;j++){     fprintf(ficgp,"cd \"%s\" \n",pathc);
         for(i=1; i<=nlstate;i++)                    /*#endif */
           fprintf(ficresf," p%d%d",i,j);    m=pow(2,cptcoveff);
         fprintf(ficresf," p.%d",j);  
       }    strcpy(dirfileres,optionfilefiname);
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {     strcpy(optfileres,"vpl");
         fprintf(ficresf,"\n");   /* 1eme*/
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);       for (cpt=1; cpt<= nlstate ; cpt ++) {
      for (k1=1; k1<= m ; k1 ++) {
         for (agec=fage; agec>=(ageminpar-1); agec--){        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);        fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
           nhstepm = nhstepm/hstepm;        fprintf(ficgp,"set xlabel \"Age\" \n\
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  set ylabel \"Probability\" \n\
           oldm=oldms;savm=savms;  set ter png small\n\
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);    set size 0.65,0.65\n\
           plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
           for (h=0; h<=nhstepm; h++){  
             if (h*hstepm/YEARM*stepm ==yearp) {       for (i=1; i<= nlstate ; i ++) {
               fprintf(ficresf,"\n");         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
               for(j=1;j<=cptcoveff;j++)          else fprintf(ficgp," \%%*lf (\%%*lf)");
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);       }
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);       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 ++) {
             for(j=1; j<=nlstate+ndeath;j++) {         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
               ppij=0.;         else fprintf(ficgp," \%%*lf (\%%*lf)");
               for(i=1; i<=nlstate;i++) {       }
                 if (mobilav==1)        fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];       for (i=1; i<= nlstate ; i ++) {
                 else {         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];         else fprintf(ficgp," \%%*lf (\%%*lf)");
                 }       }  
                 if (h*hstepm/YEARM*stepm== yearp) {       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," %.3f", p3mat[i][j][h]);     }
                 }    }
               } /* end i */    /*2 eme*/
               if (h*hstepm/YEARM*stepm==yearp) {   
                 fprintf(ficresf," %.3f", ppij);    for (k1=1; k1<= m ; k1 ++) {
               }      fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
             }/* end j */      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
           } /* end h */     
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      for (i=1; i<= nlstate+1 ; i ++) {
         } /* end agec */        k=2*i;
       } /* end yearp */        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
     } /* end cptcod */        for (j=1; j<= nlstate+1 ; j ++) {
   } /* end  cptcov */          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                  else fprintf(ficgp," \%%*lf (\%%*lf)");
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        }  
         if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
   fclose(ficresf);        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 }        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
         for (j=1; j<= nlstate+1 ; j ++) {
 /************** Forecasting *****not tested NB*************/          if (j==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){          else fprintf(ficgp," \%%*lf (\%%*lf)");
           }  
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;        fprintf(ficgp,"\" t\"\" w l 0,");
   int *popage;        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
   double calagedatem, agelim, kk1, kk2;        for (j=1; j<= nlstate+1 ; j ++) {
   double *popeffectif,*popcount;          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
   double ***p3mat,***tabpop,***tabpopprev;          else fprintf(ficgp," \%%*lf (\%%*lf)");
   double ***mobaverage;        }  
   char filerespop[FILENAMELENGTH];        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
         else fprintf(ficgp,"\" t\"\" w l 0,");
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      }
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    }
   agelim=AGESUP;   
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;    /*3eme*/
      
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);    for (k1=1; k1<= m ; k1 ++) {
         for (cpt=1; cpt<= nlstate ; cpt ++) {
           /*       k=2+nlstate*(2*cpt-2); */
   strcpy(filerespop,"pop");         k=2+(nlstate+1)*(cpt-1);
   strcat(filerespop,fileres);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
   if((ficrespop=fopen(filerespop,"w"))==NULL) {        fprintf(ficgp,"set ter png small\n\
     printf("Problem with forecast resultfile: %s\n", filerespop);  set size 0.65,0.65\n\
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);  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);
   printf("Computing forecasting: result on file '%s' \n", filerespop);          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);          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);
   if (cptcoveff==0) ncodemax[cptcoveff]=1;          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
           fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
   if (mobilav!=0) {         
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        */
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){        for (i=1; i< nlstate ; i ++) {
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);          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);
       printf(" Error in movingaverage mobilav=%d\n",mobilav);          /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/
     }         
   }        }
         fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
   stepsize=(int) (stepm+YEARM-1)/YEARM;      }
   if (stepm<=12) stepsize=1;    }
      
   agelim=AGESUP;    /* CV preval stable (period) */
       for (k1=1; k1<= m ; k1 ++) {
   hstepm=1;      for (cpt=1; cpt<=nlstate ; cpt ++) {
   hstepm=hstepm/stepm;         k=3;
           fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
   if (popforecast==1) {        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
     if((ficpop=fopen(popfile,"r"))==NULL) {  set ter png small\nset size 0.65,0.65\n\
       printf("Problem with population file : %s\n",popfile);exit(0);  unset log y\n\
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
     }        
     popage=ivector(0,AGESUP);        for (i=1; i< nlstate ; i ++)
     popeffectif=vector(0,AGESUP);          fprintf(ficgp,"+$%d",k+i+1);
     popcount=vector(0,AGESUP);        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
            
     i=1;           l=3+(nlstate+ndeath)*cpt;
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
            for (i=1; i< nlstate ; i ++) {
     imx=i;          l=3+(nlstate+ndeath)*cpt;
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];          fprintf(ficgp,"+$%d",l+i+1);
   }        }
         fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){      }
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    }  
       k=k+1;   
       fprintf(ficrespop,"\n#******");    /* proba elementaires */
       for(j=1;j<=cptcoveff;j++) {    for(i=1,jk=1; i <=nlstate; i++){
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      for(k=1; k <=(nlstate+ndeath); k++){
       }        if (k != i) {
       fprintf(ficrespop,"******\n");          for(j=1; j <=ncovmodel; j++){
       fprintf(ficrespop,"# Age");            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);            jk++;
       if (popforecast==1)  fprintf(ficrespop," [Population]");            fprintf(ficgp,"\n");
                 }
       for (cpt=0; cpt<=0;cpt++) {         }
         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--){   
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);      for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
           nhstepm = nhstepm/hstepm;        for(jk=1; jk <=m; jk++) {
                    fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);         if (ng==2)
           oldm=oldms;savm=savms;           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);           else
                    fprintf(ficgp,"\nset title \"Probability\"\n");
           for (h=0; h<=nhstepm; h++){         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
             if (h==(int) (calagedatem+YEARM*cpt)) {         i=1;
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);         for(k2=1; k2<=nlstate; k2++) {
             }            k3=i;
             for(j=1; j<=nlstate+ndeath;j++) {           for(k=1; k<=(nlstate+ndeath); k++) {
               kk1=0.;kk2=0;             if (k != k2){
               for(i=1; i<=nlstate;i++) {                             if(ng==2)
                 if (mobilav==1)                  fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];               else
                 else {                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];               ij=1;
                 }               for(j=3; j <=ncovmodel; j++) {
               }                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
               if (h==(int)(calagedatem+12*cpt)){                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;                   ij++;
                   /*fprintf(ficrespop," %.3f", kk1);                 }
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/                 else
               }                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
             }               }
             for(i=1; i<=nlstate;i++){               fprintf(ficgp,")/(1");
               kk1=0.;               
                 for(j=1; j<=nlstate;j++){               for(k1=1; k1 <=nlstate; k1++){  
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];                  fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                 }                 ij=1;
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];                 for(j=3; j <=ncovmodel; j++){
             }                   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]]]);
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)                      ij++;
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);                   }
           }                   else
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
         }                 }
       }                 fprintf(ficgp,")");
                 }
   /******/               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {                i=i+ncovmodel;
         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--){            } /* end k */
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);          } /* end k2 */
           nhstepm = nhstepm/hstepm;        } /* end jk */
                } /* end ng */
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);     fflush(ficgp);
           oldm=oldms;savm=savms;  }  /* end gnuplot */
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);    
           for (h=0; h<=nhstepm; h++){  
             if (h==(int) (calagedatem+YEARM*cpt)) {  /*************** Moving average **************/
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
             }   
             for(j=1; j<=nlstate+ndeath;j++) {    int i, cpt, cptcod;
               kk1=0.;kk2=0;    int modcovmax =1;
               for(i=1; i<=nlstate;i++) {                  int mobilavrange, mob;
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];        double age;
               }  
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);            modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
             }                             a covariate has 2 modalities */
           }    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  
         }    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
       }      if(mobilav==1) mobilavrange=5; /* default */
    }       else mobilavrange=mobilav;
   }      for (age=bage; age<=fage; age++)
          for (i=1; i<=nlstate;i++)
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          for (cptcod=1;cptcod<=modcovmax;cptcod++)
             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
   if (popforecast==1) {      /* We keep the original values on the extreme ages bage, fage and for
     free_ivector(popage,0,AGESUP);         fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
     free_vector(popeffectif,0,AGESUP);         we use a 5 terms etc. until the borders are no more concerned.
     free_vector(popcount,0,AGESUP);      */
   }      for (mob=3;mob <=mobilavrange;mob=mob+2){
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          for (i=1; i<=nlstate;i++){
   fclose(ficrespop);            for (cptcod=1;cptcod<=modcovmax;cptcod++){
 } /* End of popforecast */              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                 for (cpt=1;cpt<=(mob-1)/2;cpt++){
 int fileappend(FILE *fichier, char *optionfich)                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 {                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
   if((fichier=fopen(optionfich,"a"))==NULL) {                }
     printf("Problem with file: %s\n", optionfich);              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
     fprintf(ficlog,"Problem with file: %s\n", optionfich);            }
     return (0);          }
   }        }/* end age */
   fflush(fichier);      }/* end mob */
   return (1);    }else return -1;
 }    return 0;
   }/* End movingaverage */
   
 /**************** function prwizard **********************/  
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)  /************** Forecasting ******************/
 {  prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
     /* proj1, year, month, day of starting projection
   /* Wizard to print covariance matrix template */       agemin, agemax range of age
        dateprev1 dateprev2 range of dates during which prevalence is computed
   char ca[32], cb[32], cc[32];       anproj2 year of en of projection (same day and month as proj1).
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;    */
   int numlinepar;    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
     int *popage;
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    double agec; /* generic age */
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
   for(i=1; i <=nlstate; i++){    double *popeffectif,*popcount;
     jj=0;    double ***p3mat;
     for(j=1; j <=nlstate+ndeath; j++){    double ***mobaverage;
       if(j==i) continue;    char fileresf[FILENAMELENGTH];
       jj++;  
       /*ca[0]= k+'a'-1;ca[1]='\0';*/    agelim=AGESUP;
       printf("%1d%1d",i,j);    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
       fprintf(ficparo,"%1d%1d",i,j);   
       for(k=1; k<=ncovmodel;k++){    strcpy(fileresf,"f");
         /*        printf(" %lf",param[i][j][k]); */    strcat(fileresf,fileres);
         /*        fprintf(ficparo," %lf",param[i][j][k]); */    if((ficresf=fopen(fileresf,"w"))==NULL) {
         printf(" 0.");      printf("Problem with forecast resultfile: %s\n", fileresf);
         fprintf(ficparo," 0.");      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
       }    }
       printf("\n");    printf("Computing forecasting: result on file '%s' \n", fileresf);
       fprintf(ficparo,"\n");    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
     }  
   }    if (cptcoveff==0) ncodemax[cptcoveff]=1;
   printf("# Scales (for hessian or gradient estimation)\n");  
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");    if (mobilav!=0) {
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   for(i=1; i <=nlstate; i++){      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
     jj=0;        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
     for(j=1; j <=nlstate+ndeath; j++){        printf(" Error in movingaverage mobilav=%d\n",mobilav);
       if(j==i) continue;      }
       jj++;    }
       fprintf(ficparo,"%1d%1d",i,j);  
       printf("%1d%1d",i,j);    stepsize=(int) (stepm+YEARM-1)/YEARM;
       fflush(stdout);    if (stepm<=12) stepsize=1;
       for(k=1; k<=ncovmodel;k++){    if(estepm < stepm){
         /*      printf(" %le",delti3[i][j][k]); */      printf ("Problem %d lower than %d\n",estepm, stepm);
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */    }
         printf(" 0.");    else  hstepm=estepm;  
         fprintf(ficparo," 0.");  
       }    hstepm=hstepm/stepm;
       numlinepar++;    yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
       printf("\n");                                 fractional in yp1 */
       fprintf(ficparo,"\n");    anprojmean=yp;
     }    yp2=modf((yp1*12),&yp);
   }    mprojmean=yp;
   printf("# Covariance matrix\n");    yp1=modf((yp2*30.5),&yp);
 /* # 121 Var(a12)\n\ */    jprojmean=yp;
 /* # 122 Cov(b12,a12) Var(b12)\n\ */    if(jprojmean==0) jprojmean=1;
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */    if(mprojmean==0) jprojmean=1;
 /* # 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\ */    i1=cptcoveff;
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */    if (cptcovn < 1){i1=1;}
 /* # 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" */    fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
   fflush(stdout);   
   fprintf(ficparo,"# Covariance matrix\n");    fprintf(ficresf,"#****** Routine prevforecast **\n");
   /* # 121 Var(a12)\n\ */  
   /* # 122 Cov(b12,a12) Var(b12)\n\ */  /*            if (h==(int)(YEARM*yearp)){ */
   /* #   ...\n\ */    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
           k=k+1;
   for(itimes=1;itimes<=2;itimes++){        fprintf(ficresf,"\n#******");
     jj=0;        for(j=1;j<=cptcoveff;j++) {
     for(i=1; i <=nlstate; i++){          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]]);
       for(j=1; j <=nlstate+ndeath; j++){        }
         if(j==i) continue;        fprintf(ficresf,"******\n");
         for(k=1; k<=ncovmodel;k++){        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
           jj++;        for(j=1; j<=nlstate+ndeath;j++){
           ca[0]= k+'a'-1;ca[1]='\0';          for(i=1; i<=nlstate;i++)              
           if(itimes==1){            fprintf(ficresf," p%d%d",i,j);
             printf("#%1d%1d%d",i,j,k);          fprintf(ficresf," p.%d",j);
             fprintf(ficparo,"#%1d%1d%d",i,j,k);        }
           }else{        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
             printf("%1d%1d%d",i,j,k);          fprintf(ficresf,"\n");
             fprintf(ficparo,"%1d%1d%d",i,j,k);          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
             /*  printf(" %.5le",matcov[i][j]); */  
           }          for (agec=fage; agec>=(ageminpar-1); agec--){
           ll=0;            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
           for(li=1;li <=nlstate; li++){            nhstepm = nhstepm/hstepm;
             for(lj=1;lj <=nlstate+ndeath; lj++){            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
               if(lj==li) continue;            oldm=oldms;savm=savms;
               for(lk=1;lk<=ncovmodel;lk++){            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                 ll++;         
                 if(ll<=jj){            for (h=0; h<=nhstepm; h++){
                   cb[0]= lk +'a'-1;cb[1]='\0';              if (h*hstepm/YEARM*stepm ==yearp) {
                   if(ll<jj){                fprintf(ficresf,"\n");
                     if(itimes==1){                for(j=1;j<=cptcoveff;j++)
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                     }else{              }
                       printf(" 0.");              for(j=1; j<=nlstate+ndeath;j++) {
                       fprintf(ficparo," 0.");                ppij=0.;
                     }                for(i=1; i<=nlstate;i++) {
                   }else{                  if (mobilav==1)
                     if(itimes==1){                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                       printf(" Var(%s%1d%1d)",ca,i,j);                  else {
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                     }else{                  }
                       printf(" 0.");                  if (h*hstepm/YEARM*stepm== yearp) {
                       fprintf(ficparo," 0.");                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
                     }                  }
                   }                } /* end i */
                 }                if (h*hstepm/YEARM*stepm==yearp) {
               } /* end lk */                  fprintf(ficresf," %.3f", ppij);
             } /* end lj */                }
           } /* end li */              }/* end j */
           printf("\n");            } /* end h */
           fprintf(ficparo,"\n");            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           numlinepar++;          } /* end agec */
         } /* end k*/        } /* end yearp */
       } /*end j */      } /* end cptcod */
     } /* end i */    } /* end  cptcov */
   } /* end itimes */         
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 } /* end of prwizard */  
 /******************* Gompertz Likelihood ******************************/    fclose(ficresf);
 double gompertz(double x[])  }
 {   
   double A,B,L=0.0,sump=0.,num=0.;  /************** Forecasting *****not tested NB*************/
   int i,n=0; /* n is the size of the sample */  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){
   for (i=0;i<=imx-1 ; i++) {   
     sump=sump+weight[i];    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
     /*    sump=sump+1;*/    int *popage;
     num=num+1;    double calagedatem, agelim, kk1, kk2;
   }    double *popeffectif,*popcount;
      double ***p3mat,***tabpop,***tabpopprev;
      double ***mobaverage;
   /* for (i=0; i<=imx; i++)     char filerespop[FILENAMELENGTH];
      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]);*/  
     tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   for (i=1;i<=imx ; i++)    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     {    agelim=AGESUP;
       if (cens[i]==1 & wav[i]>1)    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));   
           prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
       if (cens[i]==0 & wav[i]>1)   
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))   
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);      strcpy(filerespop,"pop");
           strcat(filerespop,fileres);
       if (wav[i]>1 & agecens[i]>15) {    if((ficrespop=fopen(filerespop,"w"))==NULL) {
         L=L+A*weight[i];      printf("Problem with forecast resultfile: %s\n", filerespop);
         /*      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]);*/      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
       }    }
     }    printf("Computing forecasting: result on file '%s' \n", filerespop);
     fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/  
      if (cptcoveff==0) ncodemax[cptcoveff]=1;
   return -2*L*num/sump;  
 }    if (mobilav!=0) {
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 /******************* Printing html file ***********/      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   int lastpass, int stepm, int weightopt, char model[],\        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   int imx,  double p[],double **matcov,double agemortsup){      }
   int i,k;    }
   
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");    stepsize=(int) (stepm+YEARM-1)/YEARM;
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);    if (stepm<=12) stepsize=1;
   for (i=1;i<=2;i++)    
     fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));    agelim=AGESUP;
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");   
   fprintf(fichtm,"</ul>");    hstepm=1;
     hstepm=hstepm/stepm;
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");   
     if (popforecast==1) {
  fprintf(fichtm,"\nAge   lx     qx    dx    Lx     Tx     e(x)<br>");      if((ficpop=fopen(popfile,"r"))==NULL) {
         printf("Problem with population file : %s\n",popfile);exit(0);
  for (k=agegomp;k<(agemortsup-2);k++)         fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
    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]);      }
       popage=ivector(0,AGESUP);
        popeffectif=vector(0,AGESUP);
   fflush(fichtm);      popcount=vector(0,AGESUP);
 }     
       i=1;  
 /******************* Gnuplot file **************/      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){     
       imx=i;
   char dirfileres[132],optfileres[132];      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;    }
   int ng;  
     for(cptcov=1,k=0;cptcov<=i2;cptcov++){
      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   /*#ifdef windows */        k=k+1;
   fprintf(ficgp,"cd \"%s\" \n",pathc);        fprintf(ficrespop,"\n#******");
     /*#endif */        for(j=1;j<=cptcoveff;j++) {
           fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         }
   strcpy(dirfileres,optionfilefiname);        fprintf(ficrespop,"******\n");
   strcpy(optfileres,"vpl");        fprintf(ficrespop,"# Age");
   fprintf(ficgp,"set out \"graphmort.png\"\n ");         for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");         if (popforecast==1)  fprintf(ficrespop," [Population]");
   fprintf(ficgp, "set ter png small\n set log y\n");        
   fprintf(ficgp, "set size 0.65,0.65\n");        for (cpt=0; cpt<=0;cpt++) {
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);          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--){
             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
             nhstepm = nhstepm/hstepm;
            
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 /***********************************************/            oldm=oldms;savm=savms;
 /**************** Main Program *****************/            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 /***********************************************/         
             for (h=0; h<=nhstepm; h++){
 int main(int argc, char *argv[])              if (h==(int) (calagedatem+YEARM*cpt)) {
 {                fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);              }
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;              for(j=1; j<=nlstate+ndeath;j++) {
   int jj, ll, li, lj, lk, imk;                kk1=0.;kk2=0;
   int numlinepar=0; /* Current linenumber of parameter file */                for(i=1; i<=nlstate;i++) {              
   int itimes;                  if (mobilav==1)
   int NDIM=2;                    kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   else {
   char ca[32], cb[32], cc[32];                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
   /*  FILE *fichtm; *//* Html File */                  }
   /* FILE *ficgp;*/ /*Gnuplot File */                }
   double agedeb, agefin,hf;                if (h==(int)(calagedatem+12*cpt)){
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;                  tabpop[(int)(agedeb)][j][cptcod]=kk1;
                     /*fprintf(ficrespop," %.3f", kk1);
   double fret;                      if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
   double **xi,tmp,delta;                }
               }
   double dum; /* Dummy variable */              for(i=1; i<=nlstate;i++){
   double ***p3mat;                kk1=0.;
   double ***mobaverage;                  for(j=1; j<=nlstate;j++){
   int *indx;                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
   char line[MAXLINE], linepar[MAXLINE];                  }
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
   char pathr[MAXLINE], pathimach[MAXLINE];               }
   int firstobs=1, lastobs=10;  
   int sdeb, sfin; /* Status at beginning and end */              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
   int c,  h , cpt,l;                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
   int ju,jl, mi;            }
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;           }
   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.;        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
   double bage, fage, age, agelim, agebase;            nhstepm = nhstepm/hstepm;
   double ftolpl=FTOL;           
   double **prlim;            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double *severity;            oldm=oldms;savm=savms;
   double ***param; /* Matrix of parameters */            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   double  *p;            for (h=0; h<=nhstepm; h++){
   double **matcov; /* Matrix of covariance */              if (h==(int) (calagedatem+YEARM*cpt)) {
   double ***delti3; /* Scale */                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   double *delti; /* Scale */              }
   double ***eij, ***vareij;              for(j=1; j<=nlstate+ndeath;j++) {
   double **varpl; /* Variances of prevalence limits by age */                kk1=0.;kk2=0;
   double *epj, vepp;                for(i=1; i<=nlstate;i++) {              
   double kk1, kk2;                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;                }
   double **ximort;                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
   char *alph[]={"a","a","b","c","d","e"}, str[4];              }
   int *dcwave;            }
             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   char z[1]="c", occ;          }
         }
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];     }
   char strstart[80], *strt, strtend[80];    }
   char *stratrunc;   
   int lstra;    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   
   long total_usecs;    if (popforecast==1) {
        free_ivector(popage,0,AGESUP);
 /*   setlocale (LC_ALL, ""); */      free_vector(popeffectif,0,AGESUP);
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */      free_vector(popcount,0,AGESUP);
 /*   textdomain (PACKAGE); */    }
 /*   setlocale (LC_CTYPE, ""); */    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 /*   setlocale (LC_MESSAGES, ""); */    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     fclose(ficrespop);
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */  } /* End of popforecast */
   (void) gettimeofday(&start_time,&tzp);  
   curr_time=start_time;  int fileappend(FILE *fichier, char *optionfich)
   tm = *localtime(&start_time.tv_sec);  {
   tmg = *gmtime(&start_time.tv_sec);    if((fichier=fopen(optionfich,"a"))==NULL) {
   strcpy(strstart,asctime(&tm));      printf("Problem with file: %s\n", optionfich);
       fprintf(ficlog,"Problem with file: %s\n", optionfich);
 /*  printf("Localtime (at start)=%s",strstart); */      return (0);
 /*  tp.tv_sec = tp.tv_sec +86400; */    }
 /*  tm = *localtime(&start_time.tv_sec); */    fflush(fichier);
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */    return (1);
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */  }
 /*   tmg.tm_hour=tmg.tm_hour + 1; */  
 /*   tp.tv_sec = mktime(&tmg); */  
 /*   strt=asctime(&tmg); */  /**************** function prwizard **********************/
 /*   printf("Time(after) =%s",strstart);  */  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 /*  (void) time (&time_value);  {
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);  
 *  tm = *localtime(&time_value);    /* Wizard to print covariance matrix template */
 *  strstart=asctime(&tm);  
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);     char ca[32], cb[32], cc[32];
 */    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
     int numlinepar;
   nberr=0; /* Number of errors and warnings */  
   nbwarn=0;    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
   getcwd(pathcd, size);    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     for(i=1; i <=nlstate; i++){
   printf("\n%s\n%s",version,fullversion);      jj=0;
   if(argc <=1){      for(j=1; j <=nlstate+ndeath; j++){
     printf("\nEnter the parameter file name: ");        if(j==i) continue;
     scanf("%s",pathtot);        jj++;
   }        /*ca[0]= k+'a'-1;ca[1]='\0';*/
   else{        printf("%1d%1d",i,j);
     strcpy(pathtot,argv[1]);        fprintf(ficparo,"%1d%1d",i,j);
   }        for(k=1; k<=ncovmodel;k++){
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/          /*        printf(" %lf",param[i][j][k]); */
   /*cygwin_split_path(pathtot,path,optionfile);          /*        fprintf(ficparo," %lf",param[i][j][k]); */
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/          printf(" 0.");
   /* cutv(path,optionfile,pathtot,'\\');*/          fprintf(ficparo," 0.");
         }
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);        printf("\n");
  /*   strcpy(pathimach,argv[0]); */        fprintf(ficparo,"\n");
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);      }
   printf("pathimach=%s, pathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);    }
   chdir(path);    printf("# Scales (for hessian or gradient estimation)\n");
   strcpy(command,"mkdir ");    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
   strcat(command,optionfilefiname);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
   if((outcmd=system(command)) != 0){    for(i=1; i <=nlstate; i++){
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);      jj=0;
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */      for(j=1; j <=nlstate+ndeath; j++){
     /* fclose(ficlog); */        if(j==i) continue;
 /*     exit(1); */        jj++;
   }        fprintf(ficparo,"%1d%1d",i,j);
 /*   if((imk=mkdir(optionfilefiname))<0){ */        printf("%1d%1d",i,j);
 /*     perror("mkdir"); */        fflush(stdout);
 /*   } */        for(k=1; k<=ncovmodel;k++){
           /*      printf(" %le",delti3[i][j][k]); */
   /*-------- arguments in the command line --------*/          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
           printf(" 0.");
   /* Log file */          fprintf(ficparo," 0.");
   strcat(filelog, optionfilefiname);        }
   strcat(filelog,".log");    /* */        numlinepar++;
   if((ficlog=fopen(filelog,"w"))==NULL)    {        printf("\n");
     printf("Problem with logfile %s\n",filelog);        fprintf(ficparo,"\n");
     goto end;      }
   }    }
   fprintf(ficlog,"Log filename:%s\n",filelog);    printf("# Covariance matrix\n");
   fprintf(ficlog,"\n%s\n%s",version,fullversion);  /* # 121 Var(a12)\n\ */
   fprintf(ficlog,"\nEnter the parameter file name: \n");  /* # 122 Cov(b12,a12) Var(b12)\n\ */
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
  path=%s \n\  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
  optionfile=%s\n\  /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
  optionfilext=%s\n\  /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
  optionfilefiname=%s\n",pathimach,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\ */
   /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
   printf("Local time (at start):%s",strstart);    fflush(stdout);
   fprintf(ficlog,"Local time (at start): %s",strstart);    fprintf(ficparo,"# Covariance matrix\n");
   fflush(ficlog);    /* # 121 Var(a12)\n\ */
 /*   (void) gettimeofday(&curr_time,&tzp); */    /* # 122 Cov(b12,a12) Var(b12)\n\ */
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */    /* #   ...\n\ */
     /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
   /* */   
   strcpy(fileres,"r");    for(itimes=1;itimes<=2;itimes++){
   strcat(fileres, optionfilefiname);      jj=0;
   strcat(fileres,".txt");    /* Other files have txt extension */      for(i=1; i <=nlstate; i++){
         for(j=1; j <=nlstate+ndeath; j++){
   /*---------arguments file --------*/          if(j==i) continue;
           for(k=1; k<=ncovmodel;k++){
   if((ficpar=fopen(optionfile,"r"))==NULL)    {            jj++;
     printf("Problem with optionfile %s\n",optionfile);            ca[0]= k+'a'-1;ca[1]='\0';
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);            if(itimes==1){
     fflush(ficlog);              printf("#%1d%1d%d",i,j,k);
     goto end;              fprintf(ficparo,"#%1d%1d%d",i,j,k);
   }            }else{
               printf("%1d%1d%d",i,j,k);
               fprintf(ficparo,"%1d%1d%d",i,j,k);
               /*  printf(" %.5le",matcov[i][j]); */
   strcpy(filereso,"o");            }
   strcat(filereso,fileres);            ll=0;
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */            for(li=1;li <=nlstate; li++){
     printf("Problem with Output resultfile: %s\n", filereso);              for(lj=1;lj <=nlstate+ndeath; lj++){
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);                if(lj==li) continue;
     fflush(ficlog);                for(lk=1;lk<=ncovmodel;lk++){
     goto end;                  ll++;
   }                  if(ll<=jj){
                     cb[0]= lk +'a'-1;cb[1]='\0';
   /* Reads comments: lines beginning with '#' */                    if(ll<jj){
   numlinepar=0;                      if(itimes==1){
   while((c=getc(ficpar))=='#' && c!= EOF){                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     ungetc(c,ficpar);                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     fgets(line, MAXLINE, ficpar);                      }else{
     numlinepar++;                        printf(" 0.");
     puts(line);                        fprintf(ficparo," 0.");
     fputs(line,ficparo);                      }
     fputs(line,ficlog);                    }else{
   }                      if(itimes==1){
   ungetc(c,ficpar);                        printf(" Var(%s%1d%1d)",ca,i,j);
                         fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
   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);                      }else{
   numlinepar++;                        printf(" 0.");
   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," 0.");
   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);                    }
   fflush(ficlog);                  }
   while((c=getc(ficpar))=='#' && c!= EOF){                } /* end lk */
     ungetc(c,ficpar);              } /* end lj */
     fgets(line, MAXLINE, ficpar);            } /* end li */
     numlinepar++;            printf("\n");
     puts(line);            fprintf(ficparo,"\n");
     fputs(line,ficparo);            numlinepar++;
     fputs(line,ficlog);          } /* end k*/
   }        } /*end j */
   ungetc(c,ficpar);      } /* end i */
     } /* end itimes */
      
   covar=matrix(0,NCOVMAX,1,n);   } /* end of prwizard */
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/  /******************* Gompertz Likelihood ******************************/
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;  double gompertz(double x[])
   {
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */    double A,B,L=0.0,sump=0.,num=0.;
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */    int i,n=0; /* n is the size of the sample */
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/  
     for (i=0;i<=imx-1 ; i++) {
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      sump=sump+weight[i];
   delti=delti3[1][1];      /*    sump=sump+1;*/
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/      num=num+1;
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */    }
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);   
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);   
     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);    /* for (i=0; i<=imx; i++)
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);        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]);*/
     fclose (ficparo);  
     fclose (ficlog);    for (i=1;i<=imx ; i++)
     exit(0);      {
   }        if (cens[i] == 1 && wav[i]>1)
   else if(mle==-3) {          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);       
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);        if (cens[i] == 0 && wav[i]>1)
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);          A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);               +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
     matcov=matrix(1,npar,1,npar);       
   }        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
   else{        if (wav[i] > 1 ) { /* ??? */
     /* Read guess parameters */          L=L+A*weight[i];
     /* Reads comments: lines beginning with '#' */          /*      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]);*/
     while((c=getc(ficpar))=='#' && c!= EOF){        }
       ungetc(c,ficpar);      }
       fgets(line, MAXLINE, ficpar);  
       numlinepar++;   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
       puts(line);   
       fputs(line,ficparo);    return -2*L*num/sump;
       fputs(line,ficlog);  }
     }  
     ungetc(c,ficpar);  /******************* Printing html file ***********/
       void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);                    int lastpass, int stepm, int weightopt, char model[],\
     for(i=1; i <=nlstate; i++){                    int imx,  double p[],double **matcov,double agemortsup){
       j=0;    int i,k;
       for(jj=1; jj <=nlstate+ndeath; jj++){  
         if(jj==i) continue;    fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
         j++;    fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
         fscanf(ficpar,"%1d%1d",&i1,&j1);    for (i=1;i<=2;i++)
         if ((i1 != i) && (j1 != j)){      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]));
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);    fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
           exit(1);    fprintf(fichtm,"</ul>");
         }  
         fprintf(ficparo,"%1d%1d",i1,j1);  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
         if(mle==1)  
           printf("%1d%1d",i,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>");
         fprintf(ficlog,"%1d%1d",i,j);  
         for(k=1; k<=ncovmodel;k++){   for (k=agegomp;k<(agemortsup-2);k++)
           fscanf(ficpar," %lf",&param[i][j][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]);
           if(mle==1){  
             printf(" %lf",param[i][j][k]);   
             fprintf(ficlog," %lf",param[i][j][k]);    fflush(fichtm);
           }  }
           else  
             fprintf(ficlog," %lf",param[i][j][k]);  /******************* Gnuplot file **************/
           fprintf(ficparo," %lf",param[i][j][k]);  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
         }  
         fscanf(ficpar,"\n");    char dirfileres[132],optfileres[132];
         numlinepar++;    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
         if(mle==1)    int ng;
           printf("\n");  
         fprintf(ficlog,"\n");  
         fprintf(ficparo,"\n");    /*#ifdef windows */
       }    fprintf(ficgp,"cd \"%s\" \n",pathc);
     }        /*#endif */
     fflush(ficlog);  
   
     strcpy(dirfileres,optionfilefiname);
     p=param[1][1];    strcpy(optfileres,"vpl");
         fprintf(ficgp,"set out \"graphmort.png\"\n ");
     /* Reads comments: lines beginning with '#' */    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
     while((c=getc(ficpar))=='#' && c!= EOF){    fprintf(ficgp, "set ter png small\n set log y\n");
       ungetc(c,ficpar);    fprintf(ficgp, "set size 0.65,0.65\n");
       fgets(line, MAXLINE, ficpar);    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
       numlinepar++;  
       puts(line);  }
       fputs(line,ficparo);  
       fputs(line,ficlog);  
     }  
     ungetc(c,ficpar);  
   
     for(i=1; i <=nlstate; i++){  /***********************************************/
       for(j=1; j <=nlstate+ndeath-1; j++){  /**************** Main Program *****************/
         fscanf(ficpar,"%1d%1d",&i1,&j1);  /***********************************************/
         if ((i1-i)*(j1-j)!=0){  
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);  int main(int argc, char *argv[])
           exit(1);  {
         }    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
         printf("%1d%1d",i,j);    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
         fprintf(ficparo,"%1d%1d",i1,j1);    int linei, month, year,iout;
         fprintf(ficlog,"%1d%1d",i1,j1);    int jj, ll, li, lj, lk, imk;
         for(k=1; k<=ncovmodel;k++){    int numlinepar=0; /* Current linenumber of parameter file */
           fscanf(ficpar,"%le",&delti3[i][j][k]);    int itimes;
           printf(" %le",delti3[i][j][k]);    int NDIM=2;
           fprintf(ficparo," %le",delti3[i][j][k]);  
           fprintf(ficlog," %le",delti3[i][j][k]);    char ca[32], cb[32], cc[32];
         }    char dummy[]="                         ";
         fscanf(ficpar,"\n");    /*  FILE *fichtm; *//* Html File */
         numlinepar++;    /* FILE *ficgp;*/ /*Gnuplot File */
         printf("\n");    struct stat info;
         fprintf(ficparo,"\n");    double agedeb, agefin,hf;
         fprintf(ficlog,"\n");    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
       }  
     }    double fret;
     fflush(ficlog);    double **xi,tmp,delta;
   
     delti=delti3[1][1];    double dum; /* Dummy variable */
     double ***p3mat;
     double ***mobaverage;
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */    int *indx;
       char line[MAXLINE], linepar[MAXLINE];
     /* Reads comments: lines beginning with '#' */    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
     while((c=getc(ficpar))=='#' && c!= EOF){    char pathr[MAXLINE], pathimach[MAXLINE];
       ungetc(c,ficpar);    char **bp, *tok, *val; /* pathtot */
       fgets(line, MAXLINE, ficpar);    int firstobs=1, lastobs=10;
       numlinepar++;    int sdeb, sfin; /* Status at beginning and end */
       puts(line);    int c,  h , cpt,l;
       fputs(line,ficparo);    int ju,jl, mi;
       fputs(line,ficlog);    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
     }    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
     ungetc(c,ficpar);    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
       int mobilav=0,popforecast=0;
     matcov=matrix(1,npar,1,npar);    int hstepm, nhstepm;
     for(i=1; i <=npar; i++){    int agemortsup;
       fscanf(ficpar,"%s",&str);    float  sumlpop=0.;
       if(mle==1)    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
         printf("%s",str);    double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
       fprintf(ficlog,"%s",str);  
       fprintf(ficparo,"%s",str);    double bage, fage, age, agelim, agebase;
       for(j=1; j <=i; j++){    double ftolpl=FTOL;
         fscanf(ficpar," %le",&matcov[i][j]);    double **prlim;
         if(mle==1){    double *severity;
           printf(" %.5le",matcov[i][j]);    double ***param; /* Matrix of parameters */
         }    double  *p;
         fprintf(ficlog," %.5le",matcov[i][j]);    double **matcov; /* Matrix of covariance */
         fprintf(ficparo," %.5le",matcov[i][j]);    double ***delti3; /* Scale */
       }    double *delti; /* Scale */
       fscanf(ficpar,"\n");    double ***eij, ***vareij;
       numlinepar++;    double **varpl; /* Variances of prevalence limits by age */
       if(mle==1)    double *epj, vepp;
         printf("\n");    double kk1, kk2;
       fprintf(ficlog,"\n");    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
       fprintf(ficparo,"\n");    double **ximort;
     }    char *alph[]={"a","a","b","c","d","e"}, str[4];
     for(i=1; i <=npar; i++)    int *dcwave;
       for(j=i+1;j<=npar;j++)  
         matcov[i][j]=matcov[j][i];    char z[1]="c", occ;
       
     if(mle==1)    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
       printf("\n");    char  *strt, strtend[80];
     fprintf(ficlog,"\n");    char *stratrunc;
         int lstra;
     fflush(ficlog);  
         long total_usecs;
     /*-------- Rewriting parameter file ----------*/   
     strcpy(rfileres,"r");    /* "Rparameterfile */  /*   setlocale (LC_ALL, ""); */
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
     strcat(rfileres,".");    /* */  /*   textdomain (PACKAGE); */
     strcat(rfileres,optionfilext);    /* Other files have txt extension */  /*   setlocale (LC_CTYPE, ""); */
     if((ficres =fopen(rfileres,"w"))==NULL) {  /*   setlocale (LC_MESSAGES, ""); */
       printf("Problem writing new parameter file: %s\n", fileres);goto end;  
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
     }    (void) gettimeofday(&start_time,&tzp);
     fprintf(ficres,"#%s\n",version);    curr_time=start_time;
   }    /* End of mle != -3 */    tm = *localtime(&start_time.tv_sec);
     tmg = *gmtime(&start_time.tv_sec);
   /*-------- data file ----------*/    strcpy(strstart,asctime(&tm));
   if((fic=fopen(datafile,"r"))==NULL)    {  
     printf("Problem with datafile: %s\n", datafile);goto end;  /*  printf("Localtime (at start)=%s",strstart); */
     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;  /*  tp.tv_sec = tp.tv_sec +86400; */
   }  /*  tm = *localtime(&start_time.tv_sec); */
   /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
   n= lastobs;  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
   severity = vector(1,maxwav);  /*   tmg.tm_hour=tmg.tm_hour + 1; */
   outcome=imatrix(1,maxwav+1,1,n);  /*   tp.tv_sec = mktime(&tmg); */
   num=lvector(1,n);  /*   strt=asctime(&tmg); */
   moisnais=vector(1,n);  /*   printf("Time(after) =%s",strstart);  */
   annais=vector(1,n);  /*  (void) time (&time_value);
   moisdc=vector(1,n);  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
   andc=vector(1,n);  *  tm = *localtime(&time_value);
   agedc=vector(1,n);  *  strstart=asctime(&tm);
   cod=ivector(1,n);  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
   weight=vector(1,n);  */
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */  
   mint=matrix(1,maxwav,1,n);    nberr=0; /* Number of errors and warnings */
   anint=matrix(1,maxwav,1,n);    nbwarn=0;
   s=imatrix(1,maxwav+1,1,n);    getcwd(pathcd, size);
   tab=ivector(1,NCOVMAX);  
   ncodemax=ivector(1,8);    printf("\n%s\n%s",version,fullversion);
     if(argc <=1){
   i=1;      printf("\nEnter the parameter file name: ");
   while (fgets(line, MAXLINE, fic) != NULL)    {      fgets(pathr,FILENAMELENGTH,stdin);
     if ((i >= firstobs) && (i <=lastobs)) {      i=strlen(pathr);
       for(j=0; line[j] != '\n';j++){  /* Untabifies line */      if(pathr[i-1]=='\n')
         if(line[j] == '\t')        pathr[i-1]='\0';
           line[j] = ' ';     for (tok = pathr; tok != NULL; ){
       }        printf("Pathr |%s|\n",pathr);
       for (j=maxwav;j>=1;j--){        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
         cutv(stra, strb,line,' '); s[j][i]=atoi(strb);         printf("val= |%s| pathr=%s\n",val,pathr);
         strcpy(line,stra);        strcpy (pathtot, val);
         cutv(stra, strb,line,'/'); anint[j][i]=(double)(atoi(strb)); strcpy(line,stra);        if(pathr[0] == '\0') break; /* Dirty */
         cutv(stra, strb,line,' '); mint[j][i]=(double)(atoi(strb)); strcpy(line,stra);      }
       }    }
             else{
       cutv(stra, strb,line,'/'); andc[i]=(double)(atoi(strb)); strcpy(line,stra);      strcpy(pathtot,argv[1]);
       cutv(stra, strb,line,' '); moisdc[i]=(double)(atoi(strb)); strcpy(line,stra);    }
     /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
       cutv(stra, strb,line,'/'); annais[i]=(double)(atoi(strb)); strcpy(line,stra);    /*cygwin_split_path(pathtot,path,optionfile);
       cutv(stra, strb,line,' '); moisnais[i]=(double)(atoi(strb)); strcpy(line,stra);      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
     /* cutv(path,optionfile,pathtot,'\\');*/
       cutv(stra, strb,line,' '); weight[i]=(double)(atoi(strb)); strcpy(line,stra);  
       for (j=ncovcol;j>=1;j--){    /* Split argv[0], imach program to get pathimach */
         cutv(stra, strb,line,' '); covar[j][i]=(double)(atoi(strb)); strcpy(line,stra);    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
       }     split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
       lstra=strlen(stra);    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
       if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */   /*   strcpy(pathimach,argv[0]); */
         stratrunc = &(stra[lstra-9]);    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
         num[i]=atol(stratrunc);    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
       }    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
       else    chdir(path); /* Can be a relative path */
         num[i]=atol(stra);    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
               printf("Current directory %s!\n",pathcd);
       /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){    strcpy(command,"mkdir ");
         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;}*/    strcat(command,optionfilefiname);
     if((outcmd=system(command)) != 0){
       i=i+1;      printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
     }      /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
   }      /* fclose(ficlog); */
   /* printf("ii=%d", ij);  /*     exit(1); */
      scanf("%d",i);*/    }
   imx=i-1; /* Number of individuals */  /*   if((imk=mkdir(optionfilefiname))<0){ */
   /*     perror("mkdir"); */
   /* for (i=1; i<=imx; i++){  /*   } */
     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;    /*-------- arguments in the command line --------*/
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;  
     }*/    /* Log file */
    /*  for (i=1; i<=imx; i++){    strcat(filelog, optionfilefiname);
      if (s[4][i]==9)  s[4][i]=-1;     strcat(filelog,".log");    /* */
      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]));}*/    if((ficlog=fopen(filelog,"w"))==NULL)    {
         printf("Problem with logfile %s\n",filelog);
  for (i=1; i<=imx; i++)      goto end;
      }
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;    fprintf(ficlog,"Log filename:%s\n",filelog);
      else weight[i]=1;*/    fprintf(ficlog,"\n%s\n%s",version,fullversion);
     fprintf(ficlog,"\nEnter the parameter file name: \n");
   /* Calculation of the number of parameter from char model*/    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */   path=%s \n\
   Tprod=ivector(1,15);    optionfile=%s\n\
   Tvaraff=ivector(1,15);    optionfilext=%s\n\
   Tvard=imatrix(1,15,1,2);   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
   Tage=ivector(1,15);        
        printf("Local time (at start):%s",strstart);
   if (strlen(model) >1){ /* If there is at least 1 covariate */    fprintf(ficlog,"Local time (at start): %s",strstart);
     j=0, j1=0, k1=1, k2=1;    fflush(ficlog);
     j=nbocc(model,'+'); /* j=Number of '+' */  /*   (void) gettimeofday(&curr_time,&tzp); */
     j1=nbocc(model,'*'); /* j1=Number of '*' */  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
     cptcovn=j+1;   
     cptcovprod=j1; /*Number of products */    /* */
         strcpy(fileres,"r");
     strcpy(modelsav,model);     strcat(fileres, optionfilefiname);
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){    strcat(fileres,".txt");    /* Other files have txt extension */
       printf("Error. Non available option model=%s ",model);  
       fprintf(ficlog,"Error. Non available option model=%s ",model);    /*---------arguments file --------*/
       goto end;  
     }    if((ficpar=fopen(optionfile,"r"))==NULL)    {
           printf("Problem with optionfile %s\n",optionfile);
     /* This loop fills the array Tvar from the string 'model'.*/      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
       fflush(ficlog);
     for(i=(j+1); i>=1;i--){      goto end;
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */     }
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */  
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/  
       /*scanf("%d",i);*/  
       if (strchr(strb,'*')) {  /* Model includes a product */    strcpy(filereso,"o");
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/    strcat(filereso,fileres);
         if (strcmp(strc,"age")==0) { /* Vn*age */    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
           cptcovprod--;      printf("Problem with Output resultfile: %s\n", filereso);
           cutv(strb,stre,strd,'V');      fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/      fflush(ficlog);
           cptcovage++;      goto end;
             Tage[cptcovage]=i;    }
             /*printf("stre=%s ", stre);*/  
         }    /* Reads comments: lines beginning with '#' */
         else if (strcmp(strd,"age")==0) { /* or age*Vn */    numlinepar=0;
           cptcovprod--;    while((c=getc(ficpar))=='#' && c!= EOF){
           cutv(strb,stre,strc,'V');      ungetc(c,ficpar);
           Tvar[i]=atoi(stre);      fgets(line, MAXLINE, ficpar);
           cptcovage++;      numlinepar++;
           Tage[cptcovage]=i;      puts(line);
         }      fputs(line,ficparo);
         else {  /* Age is not in the model */      fputs(line,ficlog);
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/    }
           Tvar[i]=ncovcol+k1;    ungetc(c,ficpar);
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */  
           Tprod[k1]=i;    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);
           Tvard[k1][1]=atoi(strc); /* m*/    numlinepar++;
           Tvard[k1][2]=atoi(stre); /* n */    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);
           Tvar[cptcovn+k2]=Tvard[k1][1];    fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
           Tvar[cptcovn+k2+1]=Tvard[k1][2];     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 (k=1; k<=lastobs;k++)     fflush(ficlog);
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];    while((c=getc(ficpar))=='#' && c!= EOF){
           k1++;      ungetc(c,ficpar);
           k2=k2+2;      fgets(line, MAXLINE, ficpar);
         }      numlinepar++;
       }      puts(line);
       else { /* no more sum */      fputs(line,ficparo);
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/      fputs(line,ficlog);
        /*  scanf("%d",i);*/    }
       cutv(strd,strc,strb,'V');    ungetc(c,ficpar);
       Tvar[i]=atoi(strc);  
       }     
       strcpy(modelsav,stra);      covar=matrix(0,NCOVMAX,1,n);
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
         scanf("%d",i);*/    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
     } /* end of loop + */  
   } /* end model */    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
       nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/  
     delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);    delti=delti3[1][1];
   printf("cptcovprod=%d ", cptcovprod);    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
       prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
   scanf("%d ",i);      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
   fclose(fic);*/      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
       free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
     /*  if(mle==1){*/      fclose (ficparo);
   if (weightopt != 1) { /* Maximisation without weights*/      fclose (ficlog);
     for(i=1;i<=n;i++) weight[i]=1.0;      goto end;
   }      exit(0);
     /*-calculation of age at interview from date of interview and age at death -*/    }
   agev=matrix(1,maxwav,1,imx);    else if(mle==-3) {
       prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
   for (i=1; i<=imx; i++) {      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     for(m=2; (m<= maxwav); m++) {      fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         anint[m][i]=9999;      matcov=matrix(1,npar,1,npar);
         s[m][i]=-1;    }
       }    else{
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){      /* Read guess parameters */
         nberr++;      /* Reads comments: lines beginning with '#' */
         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);      while((c=getc(ficpar))=='#' && c!= EOF){
         fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);        ungetc(c,ficpar);
         s[m][i]=-1;        fgets(line, MAXLINE, ficpar);
       }        numlinepar++;
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){        puts(line);
         nberr++;        fputs(line,ficparo);
         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]);         fputs(line,ficlog);
         fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]);       }
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */      ungetc(c,ficpar);
       }     
     }      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
   }      for(i=1; i <=nlstate; i++){
         j=0;
   for (i=1; i<=imx; i++)  {        for(jj=1; jj <=nlstate+ndeath; jj++){
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);          if(jj==i) continue;
     for(m=firstpass; (m<= lastpass); m++){          j++;
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){          fscanf(ficpar,"%1d%1d",&i1,&j1);
         if (s[m][i] >= nlstate+1) {          if ((i1 != i) && (j1 != j)){
           if(agedc[i]>0)            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)  It might be a problem of design; if ncovcol and the model are correct\n \
               agev[m][i]=agedc[i];  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/            exit(1);
             else {          }
               if ((int)andc[i]!=9999){          fprintf(ficparo,"%1d%1d",i1,j1);
                 nbwarn++;          if(mle==1)
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);            printf("%1d%1d",i,j);
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);          fprintf(ficlog,"%1d%1d",i,j);
                 agev[m][i]=-1;          for(k=1; k<=ncovmodel;k++){
               }            fscanf(ficpar," %lf",&param[i][j][k]);
             }            if(mle==1){
         }              printf(" %lf",param[i][j][k]);
         else if(s[m][i] !=9){ /* Standard case, age in fractional              fprintf(ficlog," %lf",param[i][j][k]);
                                  years but with the precision of a            }
                                  month */            else
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);              fprintf(ficlog," %lf",param[i][j][k]);
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)            fprintf(ficparo," %lf",param[i][j][k]);
             agev[m][i]=1;          }
           else if(agev[m][i] <agemin){           fscanf(ficpar,"\n");
             agemin=agev[m][i];          numlinepar++;
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/          if(mle==1)
           }            printf("\n");
           else if(agev[m][i] >agemax){          fprintf(ficlog,"\n");
             agemax=agev[m][i];          fprintf(ficparo,"\n");
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/        }
           }      }  
           /*agev[m][i]=anint[m][i]-annais[i];*/      fflush(ficlog);
           /*     agev[m][i] = age[i]+2*m;*/  
         }      p=param[1][1];
         else { /* =9 */     
           agev[m][i]=1;      /* Reads comments: lines beginning with '#' */
           s[m][i]=-1;      while((c=getc(ficpar))=='#' && c!= EOF){
         }        ungetc(c,ficpar);
       }        fgets(line, MAXLINE, ficpar);
       else /*= 0 Unknown */        numlinepar++;
         agev[m][i]=1;        puts(line);
     }        fputs(line,ficparo);
             fputs(line,ficlog);
   }      }
   for (i=1; i<=imx; i++)  {      ungetc(c,ficpar);
     for(m=firstpass; (m<=lastpass); m++){  
       if (s[m][i] > (nlstate+ndeath)) {      for(i=1; i <=nlstate; i++){
         nberr++;        for(j=1; j <=nlstate+ndeath-1; j++){
         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);               fscanf(ficpar,"%1d%1d",&i1,&j1);
         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);               if ((i1-i)*(j1-j)!=0){
         goto end;            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
       }            exit(1);
     }          }
   }          printf("%1d%1d",i,j);
           fprintf(ficparo,"%1d%1d",i1,j1);
   /*for (i=1; i<=imx; i++){          fprintf(ficlog,"%1d%1d",i1,j1);
   for (m=firstpass; (m<lastpass); m++){          for(k=1; k<=ncovmodel;k++){
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);            fscanf(ficpar,"%le",&delti3[i][j][k]);
 }            printf(" %le",delti3[i][j][k]);
             fprintf(ficparo," %le",delti3[i][j][k]);
 }*/            fprintf(ficlog," %le",delti3[i][j][k]);
           }
           fscanf(ficpar,"\n");
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);          numlinepar++;
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);           printf("\n");
           fprintf(ficparo,"\n");
   agegomp=(int)agemin;          fprintf(ficlog,"\n");
   free_vector(severity,1,maxwav);        }
   free_imatrix(outcome,1,maxwav+1,1,n);      }
   free_vector(moisnais,1,n);      fflush(ficlog);
   free_vector(annais,1,n);  
   /* free_matrix(mint,1,maxwav,1,n);      delti=delti3[1][1];
      free_matrix(anint,1,maxwav,1,n);*/  
   free_vector(moisdc,1,n);  
   free_vector(andc,1,n);      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
    
          /* Reads comments: lines beginning with '#' */
   wav=ivector(1,imx);      while((c=getc(ficpar))=='#' && c!= EOF){
   dh=imatrix(1,lastpass-firstpass+1,1,imx);        ungetc(c,ficpar);
   bh=imatrix(1,lastpass-firstpass+1,1,imx);        fgets(line, MAXLINE, ficpar);
   mw=imatrix(1,lastpass-firstpass+1,1,imx);        numlinepar++;
            puts(line);
   /* Concatenates waves */        fputs(line,ficparo);
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);        fputs(line,ficlog);
       }
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */      ungetc(c,ficpar);
    
   Tcode=ivector(1,100);      matcov=matrix(1,npar,1,npar);
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);       for(i=1; i <=npar; i++){
   ncodemax[1]=1;        fscanf(ficpar,"%s",&str);
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);        if(mle==1)
                 printf("%s",str);
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of         fprintf(ficlog,"%s",str);
                                  the estimations*/        fprintf(ficparo,"%s",str);
   h=0;        for(j=1; j <=i; j++){
   m=pow(2,cptcoveff);          fscanf(ficpar," %le",&matcov[i][j]);
            if(mle==1){
   for(k=1;k<=cptcoveff; k++){            printf(" %.5le",matcov[i][j]);
     for(i=1; i <=(m/pow(2,k));i++){          }
       for(j=1; j <= ncodemax[k]; j++){          fprintf(ficlog," %.5le",matcov[i][j]);
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){          fprintf(ficparo," %.5le",matcov[i][j]);
           h++;        }
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;        fscanf(ficpar,"\n");
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/        numlinepar++;
         }         if(mle==1)
       }          printf("\n");
     }        fprintf(ficlog,"\n");
   }         fprintf(ficparo,"\n");
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);       }
      codtab[1][2]=1;codtab[2][2]=2; */      for(i=1; i <=npar; i++)
   /* for(i=1; i <=m ;i++){         for(j=i+1;j<=npar;j++)
      for(k=1; k <=cptcovn; k++){          matcov[i][j]=matcov[j][i];
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);     
      }      if(mle==1)
      printf("\n");        printf("\n");
      }      fprintf(ficlog,"\n");
      scanf("%d",i);*/     
           fflush(ficlog);
   /*------------ gnuplot -------------*/     
   strcpy(optionfilegnuplot,optionfilefiname);      /*-------- Rewriting parameter file ----------*/
   if(mle==-3)      strcpy(rfileres,"r");    /* "Rparameterfile */
     strcat(optionfilegnuplot,"-mort");      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
   strcat(optionfilegnuplot,".gp");      strcat(rfileres,".");    /* */
       strcat(rfileres,optionfilext);    /* Other files have txt extension */
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {      if((ficres =fopen(rfileres,"w"))==NULL) {
     printf("Problem with file %s",optionfilegnuplot);        printf("Problem writing new parameter file: %s\n", fileres);goto end;
   }        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
   else{      }
     fprintf(ficgp,"\n# %s\n", version);       fprintf(ficres,"#%s\n",version);
     fprintf(ficgp,"# %s\n", optionfilegnuplot);     }    /* End of mle != -3 */
     fprintf(ficgp,"set missing 'NaNq'\n");  
   }    /*-------- data file ----------*/
   /*  fclose(ficgp);*/    if((fic=fopen(datafile,"r"))==NULL)    {
   /*--------- index.htm --------*/      printf("Problem while opening datafile: %s\n", datafile);goto end;
       fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */    }
   if(mle==-3)  
     strcat(optionfilehtm,"-mort");    n= lastobs;
   strcat(optionfilehtm,".htm");    severity = vector(1,maxwav);
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {    outcome=imatrix(1,maxwav+1,1,n);
     printf("Problem with %s \n",optionfilehtm), exit(0);    num=lvector(1,n);
   }    moisnais=vector(1,n);
     annais=vector(1,n);
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */    moisdc=vector(1,n);
   strcat(optionfilehtmcov,"-cov.htm");    andc=vector(1,n);
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {    agedc=vector(1,n);
     printf("Problem with %s \n",optionfilehtmcov), exit(0);    cod=ivector(1,n);
   }    weight=vector(1,n);
   else{    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \    mint=matrix(1,maxwav,1,n);
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    anint=matrix(1,maxwav,1,n);
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\    s=imatrix(1,maxwav+1,1,n);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);    tab=ivector(1,NCOVMAX);
   }    ncodemax=ivector(1,8);
   
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \    i=1;
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    linei=0;
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 \n\      linei=linei+1;
 <hr  size=\"2\" color=\"#EC5E5E\">\      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
  <ul><li><h4>Parameter files</h4>\n\        if(line[j] == '\t')
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\          line[j] = ' ';
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\      }
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
  - Date and time at start: %s</ul>\n",\        ;
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\      };
           fileres,fileres,\      line[j+1]=0;  /* Trims blanks at end of line */
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);      if(line[0]=='#'){
   fflush(fichtm);        fprintf(ficlog,"Comment line\n%s\n",line);
         printf("Comment line\n%s\n",line);
   strcpy(pathr,path);        continue;
   strcat(pathr,optionfilefiname);      }
   chdir(optionfilefiname); /* Move to directory named optionfile */  
         for (j=maxwav;j>=1;j--){
   /* Calculates basic frequencies. Computes observed prevalence at single age        cutv(stra, strb,line,' ');
      and prints on file fileres'p'. */        errno=0;
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);        lval=strtol(strb,&endptr,10);
         /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
   fprintf(fichtm,"\n");        if( strb[0]=='\0' || (*endptr != '\0')){
   fprintf(fichtm,"<br>Total number of observations=%d <br>\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);
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\          exit(1);
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\        }
           imx,agemin,agemax,jmin,jmax,jmean);        s[j][i]=lval;
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */       
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */        strcpy(line,stra);
     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 interview (mm/yyyy or .) at wave %d.  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){        anint[j][i]= (double) year;
     ximort=matrix(1,NDIM,1,NDIM);        mint[j][i]= (double)month;
     cens=ivector(1,n);        strcpy(line,stra);
     ageexmed=vector(1,n);      } /* ENd Waves */
     agecens=vector(1,n);     
     dcwave=ivector(1,n);      cutv(stra, strb,line,' ');
        if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     for (i=1; i<=imx; i++){      }
       dcwave[i]=-1;      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
       for (j=1; j<=lastpass; j++)        month=99;
         if (s[j][i]>nlstate) {        year=9999;
           dcwave[i]=j;      }else{
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/        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);
           break;        exit(1);
         }      }
     }      andc[i]=(double) year;
       moisdc[i]=(double) month;
     for (i=1; i<=imx; i++) {      strcpy(line,stra);
       if (wav[i]>0){     
         ageexmed[i]=agev[mw[1][i]][i];      cutv(stra, strb,line,' ');
         j=wav[i];agecens[i]=1.;       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
         if (ageexmed[i]>1 & wav[i]>0) agecens[i]=agev[mw[j][i]][i];      }
         cens[i]=1;      else  if(iout=sscanf(strb,"%s.") != 0){
                 month=99;
         if (ageexmed[i]<1) cens[i]=-1;        year=9999;
         if (agedc[i]< AGESUP & agedc[i]>1 & dcwave[i]>firstpass & dcwave[i]<=lastpass) cens[i]=0 ;      }else{
       }        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);
       else cens[i]=-1;        exit(1);
     }      }
           annais[i]=(double)(year);
     for (i=1;i<=NDIM;i++) {      moisnais[i]=(double)(month);
       for (j=1;j<=NDIM;j++)      strcpy(line,stra);
         ximort[i][j]=(i == j ? 1.0 : 0.0);     
     }      cutv(stra, strb,line,' ');
       errno=0;
     p[1]=0.1; p[2]=0.1;      dval=strtod(strb,&endptr);
     /*printf("%lf %lf", p[1], p[2]);*/      if( strb[0]=='\0' || (*endptr != '\0')){
             printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
             exit(1);
   printf("Powell\n");  fprintf(ficlog,"Powell\n");      }
   strcpy(filerespow,"pow-mort");       weight[i]=dval;
   strcat(filerespow,fileres);      strcpy(line,stra);
   if((ficrespow=fopen(filerespow,"w"))==NULL) {     
     printf("Problem with resultfile: %s\n", filerespow);      for (j=ncovcol;j>=1;j--){
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);        cutv(stra, strb,line,' ');
   }        errno=0;
   fprintf(ficrespow,"# Powell\n# iter -2*LL");        lval=strtol(strb,&endptr,10);
   /*  for (i=1;i<=nlstate;i++)        if( strb[0]=='\0' || (*endptr != '\0')){
     for(j=1;j<=nlstate+ndeath;j++)          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);
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);          exit(1);
   */        }
   fprintf(ficrespow,"\n");        if(lval <-1 || lval >1){
           printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
     fclose(ficrespow);   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 \
     hesscov(matcov, p, NDIM,delti, 1e-4, gompertz);    build V1=0 V2=0 for the reference value (1),\n \
           V1=1 V2=0 for (2) \n \
     for(i=1; i <=NDIM; i++)   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
       for(j=i+1;j<=NDIM;j++)   output of IMaCh is often meaningless.\n \
         matcov[i][j]=matcov[j][i];   Exiting.\n",lval,linei, i,line,j);
               exit(1);
     printf("\nCovariance matrix\n ");        }
     for(i=1; i <=NDIM; i++) {        covar[j][i]=(double)(lval);
       for(j=1;j<=NDIM;j++){         strcpy(line,stra);
         printf("%f ",matcov[i][j]);      }
       }      lstra=strlen(stra);
       printf("\n ");     
     }      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
             stratrunc = &(stra[lstra-9]);
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);        num[i]=atol(stratrunc);
     for (i=1;i<=NDIM;i++)       }
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));      else
         num[i]=atol(stra);
 lsurv=vector(1,AGESUP);      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
     lpop=vector(1,AGESUP);        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;}*/
     tpop=vector(1,AGESUP);     
     lsurv[agegomp]=100000;      i=i+1;
        } /* End loop reading  data */
      for (k=agegomp;k<=AGESUP;k++) {    fclose(fic);
       agemortsup=k;    /* printf("ii=%d", ij);
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;       scanf("%d",i);*/
     }    imx=i-1; /* Number of individuals */
      
       for (k=agegomp;k<agemortsup;k++)    /* for (i=1; i<=imx; i++){
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));      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 (k=agegomp;k<agemortsup;k++){      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;      }*/
       sumlpop=sumlpop+lpop[k];     /*  for (i=1; i<=imx; i++){
     }       if (s[4][i]==9)  s[4][i]=-1;
        printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/
  tpop[agegomp]=sumlpop;   
     for (k=agegomp;k<(agemortsup-3);k++){    /* for (i=1; i<=imx; i++) */
       /*  tpop[k+1]=2;*/   
       tpop[k+1]=tpop[k]-lpop[k];     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
        }       else weight[i]=1;*/
      
        /* Calculation of the number of parameters from char model */
        printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
     for (k=agegomp;k<(agemortsup-2);k++)     Tprod=ivector(1,15);
       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]);    Tvaraff=ivector(1,15);
     Tvard=imatrix(1,15,1,2);
     Tage=ivector(1,15);      
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */     
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);    if (strlen(model) >1){ /* If there is at least 1 covariate */
           j=0, j1=0, k1=1, k2=1;
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \      j=nbocc(model,'+'); /* j=Number of '+' */
                      stepm, weightopt,\      j1=nbocc(model,'*'); /* j1=Number of '*' */
                      model,imx,p,matcov,agemortsup);      cptcovn=j+1;
       cptcovprod=j1; /*Number of products */
     free_vector(lsurv,1,AGESUP);     
     free_vector(lpop,1,AGESUP);      strcpy(modelsav,model);
     free_vector(tpop,1,AGESUP);      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
   } /* Endof if mle==-3 */        printf("Error. Non available option model=%s ",model);
         fprintf(ficlog,"Error. Non available option model=%s ",model);
   else{ /* For mle >=1 */        goto end;
         }
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */     
     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);      /* This loop fills the array Tvar from the string 'model'.*/
     for (k=1; k<=npar;k++)  
       printf(" %d %8.5f",k,p[k]);      for(i=(j+1); i>=1;i--){
     printf("\n");        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
     globpr=1; /* to print the contributions */        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);        /*scanf("%d",i);*/
     for (k=1; k<=npar;k++)        if (strchr(strb,'*')) {  /* Model includes a product */
       printf(" %d %8.5f",k,p[k]);          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
     printf("\n");          if (strcmp(strc,"age")==0) { /* Vn*age */
     if(mle>=1){ /* Could be 1 or 2 */            cptcovprod--;
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);            cutv(strb,stre,strd,'V');
     }            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
                 cptcovage++;
     /*--------- results files --------------*/              Tage[cptcovage]=i;
     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);              /*printf("stre=%s ", stre);*/
               }
               else if (strcmp(strd,"age")==0) { /* or age*Vn */
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");            cptcovprod--;
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");            cutv(strb,stre,strc,'V');
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");            Tvar[i]=atoi(stre);
     for(i=1,jk=1; i <=nlstate; i++){            cptcovage++;
       for(k=1; k <=(nlstate+ndeath); k++){            Tage[cptcovage]=i;
         if (k != i) {          }
           printf("%d%d ",i,k);          else {  /* Age is not in the model */
           fprintf(ficlog,"%d%d ",i,k);            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
           fprintf(ficres,"%1d%1d ",i,k);            Tvar[i]=ncovcol+k1;
           for(j=1; j <=ncovmodel; j++){            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
             printf("%f ",p[jk]);            Tprod[k1]=i;
             fprintf(ficlog,"%f ",p[jk]);            Tvard[k1][1]=atoi(strc); /* m*/
             fprintf(ficres,"%f ",p[jk]);            Tvard[k1][2]=atoi(stre); /* n */
             jk++;             Tvar[cptcovn+k2]=Tvard[k1][1];
           }            Tvar[cptcovn+k2+1]=Tvard[k1][2];
           printf("\n");            for (k=1; k<=lastobs;k++)
           fprintf(ficlog,"\n");              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
           fprintf(ficres,"\n");            k1++;
         }            k2=k2+2;
       }          }
     }        }
     if(mle!=0){        else { /* no more sum */
       /* Computing hessian and covariance matrix */          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
       ftolhess=ftol; /* Usually correct */         /*  scanf("%d",i);*/
       hesscov(matcov, p, npar, delti, ftolhess, func);        cutv(strd,strc,strb,'V');
     }        Tvar[i]=atoi(strc);
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");        }
     printf("# Scales (for hessian or gradient estimation)\n");        strcpy(modelsav,stra);  
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
     for(i=1,jk=1; i <=nlstate; i++){          scanf("%d",i);*/
       for(j=1; j <=nlstate+ndeath; j++){      } /* end of loop + */
         if (j!=i) {    } /* end model */
           fprintf(ficres,"%1d%1d",i,j);   
           printf("%1d%1d",i,j);    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
           fprintf(ficlog,"%1d%1d",i,j);      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
           for(k=1; k<=ncovmodel;k++){  
             printf(" %.5e",delti[jk]);    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
             fprintf(ficlog," %.5e",delti[jk]);    printf("cptcovprod=%d ", cptcovprod);
             fprintf(ficres," %.5e",delti[jk]);    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
             jk++;  
           }    scanf("%d ",i);*/
           printf("\n");  
           fprintf(ficlog,"\n");      /*  if(mle==1){*/
           fprintf(ficres,"\n");    if (weightopt != 1) { /* Maximisation without weights*/
         }      for(i=1;i<=n;i++) weight[i]=1.0;
       }    }
     }      /*-calculation of age at interview from date of interview and age at death -*/
         agev=matrix(1,maxwav,1,imx);
     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");  
     if(mle>=1)    for (i=1; i<=imx; i++) {
       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");      for(m=2; (m<= maxwav); m++) {
     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)mint[m][i]== 99) && (s[m][i] <= nlstate)){
     /* # 121 Var(a12)\n\ */          anint[m][i]=9999;
     /* # 122 Cov(b12,a12) Var(b12)\n\ */          s[m][i]=-1;
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */        }
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */          nberr++;
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\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);
     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */          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);
     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */          s[m][i]=-1;
             }
             if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
     /* Just to have a covariance matrix which will be more understandable          nberr++;
        even is we still don't want to manage dictionary of variables          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]);
     for(itimes=1;itimes<=2;itimes++){          s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
       jj=0;        }
       for(i=1; i <=nlstate; i++){      }
         for(j=1; j <=nlstate+ndeath; j++){    }
           if(j==i) continue;  
           for(k=1; k<=ncovmodel;k++){    for (i=1; i<=imx; i++)  {
             jj++;      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
             ca[0]= k+'a'-1;ca[1]='\0';      for(m=firstpass; (m<= lastpass); m++){
             if(itimes==1){        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
               if(mle>=1)          if (s[m][i] >= nlstate+1) {
                 printf("#%1d%1d%d",i,j,k);            if(agedc[i]>0)
               fprintf(ficlog,"#%1d%1d%d",i,j,k);              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
               fprintf(ficres,"#%1d%1d%d",i,j,k);                agev[m][i]=agedc[i];
             }else{            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
               if(mle>=1)              else {
                 printf("%1d%1d%d",i,j,k);                if ((int)andc[i]!=9999){
               fprintf(ficlog,"%1d%1d%d",i,j,k);                  nbwarn++;
               fprintf(ficres,"%1d%1d%d",i,j,k);                  printf("Warning negative age at death: %ld line:%d\n",num[i],i);
             }                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
             ll=0;                  agev[m][i]=-1;
             for(li=1;li <=nlstate; li++){                }
               for(lj=1;lj <=nlstate+ndeath; lj++){              }
                 if(lj==li) continue;          }
                 for(lk=1;lk<=ncovmodel;lk++){          else if(s[m][i] !=9){ /* Standard case, age in fractional
                   ll++;                                   years but with the precision of a month */
                   if(ll<=jj){            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                     cb[0]= lk +'a'-1;cb[1]='\0';            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                     if(ll<jj){              agev[m][i]=1;
                       if(itimes==1){            else if(agev[m][i] <agemin){
                         if(mle>=1)              agemin=agev[m][i];
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);            }
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);            else if(agev[m][i] >agemax){
                       }else{              agemax=agev[m][i];
                         if(mle>=1)              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
                           printf(" %.5e",matcov[jj][ll]);             }
                         fprintf(ficlog," %.5e",matcov[jj][ll]);             /*agev[m][i]=anint[m][i]-annais[i];*/
                         fprintf(ficres," %.5e",matcov[jj][ll]);             /*     agev[m][i] = age[i]+2*m;*/
                       }          }
                     }else{          else { /* =9 */
                       if(itimes==1){            agev[m][i]=1;
                         if(mle>=1)            s[m][i]=-1;
                           printf(" Var(%s%1d%1d)",ca,i,j);          }
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);        }
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);        else /*= 0 Unknown */
                       }else{          agev[m][i]=1;
                         if(mle>=1)      }
                           printf(" %.5e",matcov[jj][ll]);      
                         fprintf(ficlog," %.5e",matcov[jj][ll]);     }
                         fprintf(ficres," %.5e",matcov[jj][ll]);     for (i=1; i<=imx; i++)  {
                       }      for(m=firstpass; (m<=lastpass); m++){
                     }        if (s[m][i] > (nlstate+ndeath)) {
                   }          nberr++;
                 } /* end lk */          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);    
               } /* end lj */          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);    
             } /* end li */          goto end;
             if(mle>=1)        }
               printf("\n");      }
             fprintf(ficlog,"\n");    }
             fprintf(ficres,"\n");  
             numlinepar++;    /*for (i=1; i<=imx; i++){
           } /* end k*/    for (m=firstpass; (m<lastpass); m++){
         } /*end j */       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
       } /* end i */  }
     } /* end itimes */  
       }*/
     fflush(ficlog);  
     fflush(ficres);  
         printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
     while((c=getc(ficpar))=='#' && c!= EOF){    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
       ungetc(c,ficpar);  
       fgets(line, MAXLINE, ficpar);    agegomp=(int)agemin;
       puts(line);    free_vector(severity,1,maxwav);
       fputs(line,ficparo);    free_imatrix(outcome,1,maxwav+1,1,n);
     }    free_vector(moisnais,1,n);
     ungetc(c,ficpar);    free_vector(annais,1,n);
         /* free_matrix(mint,1,maxwav,1,n);
     estepm=0;       free_matrix(anint,1,maxwav,1,n);*/
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);    free_vector(moisdc,1,n);
     if (estepm==0 || estepm < stepm) estepm=stepm;    free_vector(andc,1,n);
     if (fage <= 2) {  
       bage = ageminpar;     
       fage = agemaxpar;    wav=ivector(1,imx);
     }    dh=imatrix(1,lastpass-firstpass+1,1,imx);
         bh=imatrix(1,lastpass-firstpass+1,1,imx);
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");    mw=imatrix(1,lastpass-firstpass+1,1,imx);
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);     
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);    /* Concatenates waves */
         concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
     while((c=getc(ficpar))=='#' && c!= EOF){  
       ungetc(c,ficpar);    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
       fgets(line, MAXLINE, ficpar);  
       puts(line);    Tcode=ivector(1,100);
       fputs(line,ficparo);    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
     }    ncodemax[1]=1;
     ungetc(c,ficpar);    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
            
     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);    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
     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);                                   the estimations*/
     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);    h=0;
     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);    m=pow(2,cptcoveff);
     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);   
         for(k=1;k<=cptcoveff; k++){
     while((c=getc(ficpar))=='#' && c!= EOF){      for(i=1; i <=(m/pow(2,k));i++){
       ungetc(c,ficpar);        for(j=1; j <= ncodemax[k]; j++){
       fgets(line, MAXLINE, ficpar);          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
       puts(line);            h++;
       fputs(line,ficparo);            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
     }            /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
     ungetc(c,ficpar);          }
             }
           }
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;    }
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
            codtab[1][2]=1;codtab[2][2]=2; */
     fscanf(ficpar,"pop_based=%d\n",&popbased);    /* for(i=1; i <=m ;i++){
     fprintf(ficparo,"pop_based=%d\n",popbased);          for(k=1; k <=cptcovn; k++){
     fprintf(ficres,"pop_based=%d\n",popbased);          printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
            }
     while((c=getc(ficpar))=='#' && c!= EOF){       printf("\n");
       ungetc(c,ficpar);       }
       fgets(line, MAXLINE, ficpar);       scanf("%d",i);*/
       puts(line);     
       fputs(line,ficparo);    /*------------ gnuplot -------------*/
     }    strcpy(optionfilegnuplot,optionfilefiname);
     ungetc(c,ficpar);    if(mle==-3)
           strcat(optionfilegnuplot,"-mort");
     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);    strcat(optionfilegnuplot,".gp");
     fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);  
     printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
     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);      printf("Problem with file %s",optionfilegnuplot);
     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);    }
     /* day and month of proj2 are not used but only year anproj2.*/    else{
           fprintf(ficgp,"\n# %s\n", version);
           fprintf(ficgp,"# %s\n", optionfilegnuplot);
           fprintf(ficgp,"set missing 'NaNq'\n");
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/    }
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/    /*  fclose(ficgp);*/
         /*--------- index.htm --------*/
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */  
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
         if(mle==-3)
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\      strcat(optionfilehtm,"-mort");
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\    strcat(optionfilehtm,".htm");
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
             printf("Problem with %s \n",optionfilehtm), exit(0);
    /*------------ free_vector  -------------*/    }
    /*  chdir(path); */  
      strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
     free_ivector(wav,1,imx);    strcat(optionfilehtmcov,"-cov.htm");
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);      printf("Problem with %s \n",optionfilehtmcov), exit(0);
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);       }
     free_lvector(num,1,n);    else{
     free_vector(agedc,1,n);    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
     /*free_matrix(covar,0,NCOVMAX,1,n);*/  <hr size=\"2\" color=\"#EC5E5E\"> \n\
     /*free_matrix(covar,1,NCOVMAX,1,n);*/  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
     fclose(ficparo);            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
     fclose(ficres);    }
   
     fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
     /*--------------- Prevalence limit  (stable prevalence) --------------*/  <hr size=\"2\" color=\"#EC5E5E\"> \n\
     Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
     strcpy(filerespl,"pl");  \n\
     strcat(filerespl,fileres);  <hr  size=\"2\" color=\"#EC5E5E\">\
     if((ficrespl=fopen(filerespl,"w"))==NULL) {   <ul><li><h4>Parameter files</h4>\n\
       printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;   - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
       fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;   - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
     }   - Log file of the run: <a href=\"%s\">%s</a><br>\n\
     printf("Computing stable prevalence: result on file '%s' \n", filerespl);   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
     fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);   - Date and time at start: %s</ul>\n",\
     fprintf(ficrespl, "#Local time at start: %s", strstart);            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
     fprintf(ficrespl,"#Stable prevalence \n");            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
     fprintf(ficrespl,"#Age ");            fileres,fileres,\
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);            filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
     fprintf(ficrespl,"\n");    fflush(fichtm);
     
     prlim=matrix(1,nlstate,1,nlstate);    strcpy(pathr,path);
     strcat(pathr,optionfilefiname);
     agebase=ageminpar;    chdir(optionfilefiname); /* Move to directory named optionfile */
     agelim=agemaxpar;   
     ftolpl=1.e-10;    /* Calculates basic frequencies. Computes observed prevalence at single age
     i1=cptcoveff;       and prints on file fileres'p'. */
     if (cptcovn < 1){i1=1;}    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
   
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){    fprintf(fichtm,"\n");
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
         k=k+1;  Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/  Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
         fprintf(ficrespl,"\n#******");            imx,agemin,agemax,jmin,jmax,jmean);
         printf("\n#******");    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
         fprintf(ficlog,"\n#******");      oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
         for(j=1;j<=cptcoveff;j++) {      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);     
         }     
         fprintf(ficrespl,"******\n");    /* For Powell, parameters are in a vector p[] starting at p[1]
         printf("******\n");       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
         fprintf(ficlog,"******\n");    p=param[1][1]; /* *(*(*(param +1)+1)+0) */
           
         for (age=agebase; age<=agelim; age++){    globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);  
           fprintf(ficrespl,"%.0f ",age );    if (mle==-3){
           for(j=1;j<=cptcoveff;j++)      ximort=matrix(1,NDIM,1,NDIM);
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      cens=ivector(1,n);
           for(i=1; i<=nlstate;i++)      ageexmed=vector(1,n);
             fprintf(ficrespl," %.5f", prlim[i][i]);      agecens=vector(1,n);
           fprintf(ficrespl,"\n");      dcwave=ivector(1,n);
         }   
       }      for (i=1; i<=imx; i++){
     }        dcwave[i]=-1;
     fclose(ficrespl);        for (m=firstpass; m<=lastpass; m++)
           if (s[m][i]>nlstate) {
     /*------------- h Pij x at various ages ------------*/            dcwave[i]=m;
               /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);            break;
     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;  
     }      for (i=1; i<=imx; i++) {
     printf("Computing pij: result on file '%s' \n", filerespij);        if (wav[i]>0){
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);          ageexmed[i]=agev[mw[1][i]][i];
             j=wav[i];
     stepsize=(int) (stepm+YEARM-1)/YEARM;          agecens[i]=1.;
     /*if (stepm<=24) stepsize=2;*/  
           if (ageexmed[i]> 1 && wav[i] > 0){
     agelim=AGESUP;            agecens[i]=agev[mw[j][i]][i];
     hstepm=stepsize*YEARM; /* Every year of age */            cens[i]= 1;
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */           }else if (ageexmed[i]< 1)
             cens[i]= -1;
     /* hstepm=1;   aff par mois*/          if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
     fprintf(ficrespij, "#Local time at start: %s", strstart);            cens[i]=0 ;
     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");        }
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){        else cens[i]=-1;
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      }
         k=k+1;     
         fprintf(ficrespij,"\n#****** ");      for (i=1;i<=NDIM;i++) {
         for(j=1;j<=cptcoveff;j++)         for (j=1;j<=NDIM;j++)
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          ximort[i][j]=(i == j ? 1.0 : 0.0);
         fprintf(ficrespij,"******\n");      }
              
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */      p[1]=0.0268; p[NDIM]=0.083;
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */       /*printf("%lf %lf", p[1], p[2]);*/
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */     
      
           /*      nhstepm=nhstepm*YEARM; aff par mois*/      printf("Powell\n");  fprintf(ficlog,"Powell\n");
       strcpy(filerespow,"pow-mort");
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      strcat(filerespow,fileres);
           oldm=oldms;savm=savms;      if((ficrespow=fopen(filerespow,"w"))==NULL) {
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);          printf("Problem with resultfile: %s\n", filerespow);
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
           for(i=1; i<=nlstate;i++)      }
             for(j=1; j<=nlstate+ndeath;j++)      fprintf(ficrespow,"# Powell\n# iter -2*LL");
               fprintf(ficrespij," %1d-%1d",i,j);      /*  for (i=1;i<=nlstate;i++)
           fprintf(ficrespij,"\n");          for(j=1;j<=nlstate+ndeath;j++)
           for (h=0; h<=nhstepm; h++){          if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );      */
             for(i=1; i<=nlstate;i++)      fprintf(ficrespow,"\n");
               for(j=1; j<=nlstate+ndeath;j++)     
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
             fprintf(ficrespij,"\n");      fclose(ficrespow);
           }     
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
           fprintf(ficrespij,"\n");  
         }      for(i=1; i <=NDIM; i++)
       }        for(j=i+1;j<=NDIM;j++)
     }          matcov[i][j]=matcov[j][i];
      
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);      printf("\nCovariance matrix\n ");
       for(i=1; i <=NDIM; i++) {
     fclose(ficrespij);        for(j=1;j<=NDIM;j++){
           printf("%f ",matcov[i][j]);
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);        }
     for(i=1;i<=AGESUP;i++)        printf("\n ");
       for(j=1;j<=NCOVMAX;j++)      }
         for(k=1;k<=NCOVMAX;k++)     
           probs[i][j][k]=0.;      printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
       for (i=1;i<=NDIM;i++)
     /*---------- Forecasting ------------------*/        printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/  
     if(prevfcast==1){      lsurv=vector(1,AGESUP);
       /*    if(stepm ==1){*/      lpop=vector(1,AGESUP);
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);      tpop=vector(1,AGESUP);
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/      lsurv[agegomp]=100000;
       /*      }  */     
       /*      else{ */      for (k=agegomp;k<=AGESUP;k++) {
       /*        erreur=108; */        agemortsup=k;
       /*        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); */        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
       /*        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); */      }
       /*      } */     
     }      for (k=agegomp;k<agemortsup;k++)
           lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
      
     /*---------- Health expectancies and variances ------------*/      for (k=agegomp;k<agemortsup;k++){
         lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
     strcpy(filerest,"t");        sumlpop=sumlpop+lpop[k];
     strcat(filerest,fileres);      }
     if((ficrest=fopen(filerest,"w"))==NULL) {     
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;      tpop[agegomp]=sumlpop;
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;      for (k=agegomp;k<(agemortsup-3);k++){
     }        /*  tpop[k+1]=2;*/
     printf("Computing Total LEs with variances: file '%s' \n", filerest);         tpop[k+1]=tpop[k]-lpop[k];
     fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest);       }
      
      
     strcpy(filerese,"e");      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
     strcat(filerese,fileres);      for (k=agegomp;k<(agemortsup-2);k++)
     if((ficreseij=fopen(filerese,"w"))==NULL) {        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]);
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);     
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);     
     }      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);     
       printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
     strcpy(fileresv,"v");                       stepm, weightopt,\
     strcat(fileresv,fileres);                       model,imx,p,matcov,agemortsup);
     if((ficresvij=fopen(fileresv,"w"))==NULL) {     
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);      free_vector(lsurv,1,AGESUP);
       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);      free_vector(lpop,1,AGESUP);
     }      free_vector(tpop,1,AGESUP);
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);    } /* Endof if mle==-3 */
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);   
     else{ /* For mle >=1 */
     /* 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);      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\      printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);      for (k=1; k<=npar;k++)
     */        printf(" %d %8.5f",k,p[k]);
       printf("\n");
     if (mobilav!=0) {      globpr=1; /* to print the contributions */
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){      printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);      for (k=1; k<=npar;k++)
         printf(" Error in movingaverage mobilav=%d\n",mobilav);        printf(" %d %8.5f",k,p[k]);
       }      printf("\n");
     }      if(mle>=1){ /* Could be 1 or 2 */
         mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      }
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){     
         k=k+1;       /*--------- results files --------------*/
         fprintf(ficrest,"\n#****** ");      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);
         for(j=1;j<=cptcoveff;j++)      
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);     
         fprintf(ficrest,"******\n");      fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         fprintf(ficreseij,"\n#****** ");      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         for(j=1;j<=cptcoveff;j++)       for(i=1,jk=1; i <=nlstate; i++){
           fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        for(k=1; k <=(nlstate+ndeath); k++){
         fprintf(ficreseij,"******\n");          if (k != i) {
             printf("%d%d ",i,k);
         fprintf(ficresvij,"\n#****** ");            fprintf(ficlog,"%d%d ",i,k);
         for(j=1;j<=cptcoveff;j++)             fprintf(ficres,"%1d%1d ",i,k);
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            for(j=1; j <=ncovmodel; j++){
         fprintf(ficresvij,"******\n");              printf("%lf ",p[jk]);
               fprintf(ficlog,"%lf ",p[jk]);
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);              fprintf(ficres,"%lf ",p[jk]);
         oldm=oldms;savm=savms;              jk++;
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);              }
              printf("\n");
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);            fprintf(ficlog,"\n");
         oldm=oldms;savm=savms;            fprintf(ficres,"\n");
         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);      }
         }      if(mle!=0){
         /* Computing hessian and covariance matrix */
         fprintf(ficrest, "#Local time at start: %s", strstart);        ftolhess=ftol; /* Usually correct */
         fprintf(ficrest,"#Total LEs with variances: e.. (std) ");        hesscov(matcov, p, npar, delti, ftolhess, func);
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);      }
         fprintf(ficrest,"\n");      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
       printf("# Scales (for hessian or gradient estimation)\n");
         epj=vector(1,nlstate+1);      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
         for(age=bage; age <=fage ;age++){      for(i=1,jk=1; i <=nlstate; i++){
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);        for(j=1; j <=nlstate+ndeath; j++){
           if (popbased==1) {          if (j!=i) {
             if(mobilav ==0){            fprintf(ficres,"%1d%1d",i,j);
               for(i=1; i<=nlstate;i++)            printf("%1d%1d",i,j);
                 prlim[i][i]=probs[(int)age][i][k];            fprintf(ficlog,"%1d%1d",i,j);
             }else{ /* mobilav */             for(k=1; k<=ncovmodel;k++){
               for(i=1; i<=nlstate;i++)              printf(" %.5e",delti[jk]);
                 prlim[i][i]=mobaverage[(int)age][i][k];              fprintf(ficlog," %.5e",delti[jk]);
             }              fprintf(ficres," %.5e",delti[jk]);
           }              jk++;
                     }
           fprintf(ficrest," %4.0f",age);            printf("\n");
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){            fprintf(ficlog,"\n");
             for(i=1, epj[j]=0.;i <=nlstate;i++) {            fprintf(ficres,"\n");
               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];     
           }      fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
       if(mle>=1)
           for(i=1, vepp=0.;i <=nlstate;i++)        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");
             for(j=1;j <=nlstate;j++)      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");
               vepp += vareij[i][j][(int)age];      /* # 121 Var(a12)\n\ */
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));      /* # 122 Cov(b12,a12) Var(b12)\n\ */
           for(j=1;j <=nlstate;j++){      /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));      /* # 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\ */
           fprintf(ficrest,"\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\ */
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);     
         free_vector(epj,1,nlstate+1);     
       }      /* Just to have a covariance matrix which will be more understandable
     }         even is we still don't want to manage dictionary of variables
     free_vector(weight,1,n);      */
     free_imatrix(Tvard,1,15,1,2);      for(itimes=1;itimes<=2;itimes++){
     free_imatrix(s,1,maxwav+1,1,n);        jj=0;
     free_matrix(anint,1,maxwav,1,n);         for(i=1; i <=nlstate; i++){
     free_matrix(mint,1,maxwav,1,n);          for(j=1; j <=nlstate+ndeath; j++){
     free_ivector(cod,1,n);            if(j==i) continue;
     free_ivector(tab,1,NCOVMAX);            for(k=1; k<=ncovmodel;k++){
     fclose(ficreseij);              jj++;
     fclose(ficresvij);              ca[0]= k+'a'-1;ca[1]='\0';
     fclose(ficrest);              if(itimes==1){
     fclose(ficpar);                if(mle>=1)
                     printf("#%1d%1d%d",i,j,k);
     /*------- Variance of stable prevalence------*/                   fprintf(ficlog,"#%1d%1d%d",i,j,k);
                 fprintf(ficres,"#%1d%1d%d",i,j,k);
     strcpy(fileresvpl,"vpl");              }else{
     strcat(fileresvpl,fileres);                if(mle>=1)
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {                  printf("%1d%1d%d",i,j,k);
       printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);                fprintf(ficlog,"%1d%1d%d",i,j,k);
       exit(0);                fprintf(ficres,"%1d%1d%d",i,j,k);
     }              }
     printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);              ll=0;
               for(li=1;li <=nlstate; li++){
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){                for(lj=1;lj <=nlstate+ndeath; lj++){
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){                  if(lj==li) continue;
         k=k+1;                  for(lk=1;lk<=ncovmodel;lk++){
         fprintf(ficresvpl,"\n#****** ");                    ll++;
         for(j=1;j<=cptcoveff;j++)                     if(ll<=jj){
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);                      cb[0]= lk +'a'-1;cb[1]='\0';
         fprintf(ficresvpl,"******\n");                      if(ll<jj){
                               if(itimes==1){
         varpl=matrix(1,nlstate,(int) bage, (int) fage);                          if(mle>=1)
         oldm=oldms;savm=savms;                            printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);                          fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);                          fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
       }                        }else{
     }                          if(mle>=1)
                             printf(" %.5e",matcov[jj][ll]);
     fclose(ficresvpl);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
                           fprintf(ficres," %.5e",matcov[jj][ll]);
     /*---------- End : free ----------------*/                        }
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                      }else{
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);                        if(itimes==1){
                           if(mle>=1)
   }  /* mle==-3 arrives here for freeing */                            printf(" Var(%s%1d%1d)",ca,i,j);
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);                          fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);                          fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);                        }else{
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);                          if(mle>=1)
                               printf(" %.5e",matcov[jj][ll]);
     free_matrix(covar,0,NCOVMAX,1,n);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
     free_matrix(matcov,1,npar,1,npar);                          fprintf(ficres," %.5e",matcov[jj][ll]);
     /*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);                  } /* end lk */
                 } /* end lj */
     free_ivector(ncodemax,1,8);              } /* end li */
     free_ivector(Tvar,1,15);              if(mle>=1)
     free_ivector(Tprod,1,15);                printf("\n");
     free_ivector(Tvaraff,1,15);              fprintf(ficlog,"\n");
     free_ivector(Tage,1,15);              fprintf(ficres,"\n");
     free_ivector(Tcode,1,100);              numlinepar++;
             } /* end k*/
           } /*end j */
   fflush(fichtm);        } /* end i */
   fflush(ficgp);      } /* end itimes */
        
       fflush(ficlog);
   if((nberr >0) || (nbwarn>0)){      fflush(ficres);
     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);      while((c=getc(ficpar))=='#' && c!= EOF){
   }else{        ungetc(c,ficpar);
     printf("End of Imach\n");        fgets(line, MAXLINE, ficpar);
     fprintf(ficlog,"End of Imach\n");        puts(line);
   }        fputs(line,ficparo);
   printf("See log file on %s\n",filelog);      }
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */      ungetc(c,ficpar);
   (void) gettimeofday(&end_time,&tzp);     
   tm = *localtime(&end_time.tv_sec);      estepm=0;
   tmg = *gmtime(&end_time.tv_sec);      fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
   strcpy(strtend,asctime(&tm));      if (estepm==0 || estepm < stepm) estepm=stepm;
   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);       if (fage <= 2) {
   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);         bage = ageminpar;
   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));        fage = agemaxpar;
       }
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);     
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
   /*  printf("Total time was %d uSec.\n", total_usecs);*/      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 /*   if(fileappend(fichtm,optionfilehtm)){ */     
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);      while((c=getc(ficpar))=='#' && c!= EOF){
   fclose(fichtm);        ungetc(c,ficpar);
   fclose(fichtmcov);        fgets(line, MAXLINE, ficpar);
   fclose(ficgp);        puts(line);
   fclose(ficlog);        fputs(line,ficparo);
   /*------ End -----------*/      }
       ungetc(c,ficpar);
   chdir(path);     
   strcpy(plotcmd,"\"");      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(plotcmd,pathimach);      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(plotcmd,GNUPLOTPROGRAM);      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);
   strcat(plotcmd,"\"");      printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
   strcat(plotcmd," ");      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);
   strcat(plotcmd,optionfilegnuplot);     
   printf("Starting graphs with: %s",plotcmd);fflush(stdout);      while((c=getc(ficpar))=='#' && c!= EOF){
   if((outcmd=system(plotcmd)) != 0){        ungetc(c,ficpar);
     printf(" Problem with gnuplot\n");        fgets(line, MAXLINE, ficpar);
   }        puts(line);
   printf(" Wait...");        fputs(line,ficparo);
   while (z[0] != 'q') {      }
     /* chdir(path); */      ungetc(c,ficpar);
     printf("\nType e to edit output files, g to graph again and q for exiting: ");     
     scanf("%s",z);     
 /*     if (z[0] == 'c') system("./imach"); */      dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
     if (z[0] == 'e') {      dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);     
       system(optionfilehtm);      fscanf(ficpar,"pop_based=%d\n",&popbased);
     }      fprintf(ficparo,"pop_based=%d\n",popbased);  
     else if (z[0] == 'g') system(plotcmd);      fprintf(ficres,"pop_based=%d\n",popbased);  
     else if (z[0] == 'q') exit(0);     
   }      while((c=getc(ficpar))=='#' && c!= EOF){
   end:        ungetc(c,ficpar);
   while (z[0] != 'q') {        fgets(line, MAXLINE, ficpar);
     printf("\nType  q for exiting: ");        puts(line);
     scanf("%s",z);        fputs(line,ficparo);
   }      }
 }      ungetc(c,ficpar);
      
       fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);
       fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
       printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
       fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
       fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
       /* day and month of proj2 are not used but only year anproj2.*/
      
      
      
       /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
       /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
      
       replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
       printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
      
       printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                    model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                    jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
        
      /*------------ free_vector  -------------*/
      /*  chdir(path); */
    
       free_ivector(wav,1,imx);
       free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
       free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
       free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
       free_lvector(num,1,n);
       free_vector(agedc,1,n);
       /*free_matrix(covar,0,NCOVMAX,1,n);*/
       /*free_matrix(covar,1,NCOVMAX,1,n);*/
       fclose(ficparo);
       fclose(ficres);
   
   
       /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
    
       strcpy(filerespl,"pl");
       strcat(filerespl,fileres);
       if((ficrespl=fopen(filerespl,"w"))==NULL) {
         printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
         fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
       }
       printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
       fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
       pstamp(ficrespl);
       fprintf(ficrespl,"# Period (stable) prevalence \n");
       fprintf(ficrespl,"#Age ");
       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
       fprintf(ficrespl,"\n");
    
       prlim=matrix(1,nlstate,1,nlstate);
   
       agebase=ageminpar;
       agelim=agemaxpar;
       ftolpl=1.e-10;
       i1=cptcoveff;
       if (cptcovn < 1){i1=1;}
   
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
           fprintf(ficrespl,"\n#******");
           printf("\n#******");
           fprintf(ficlog,"\n#******");
           for(j=1;j<=cptcoveff;j++) {
             fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           }
           fprintf(ficrespl,"******\n");
           printf("******\n");
           fprintf(ficlog,"******\n");
          
           for (age=agebase; age<=agelim; age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
             fprintf(ficrespl,"%.0f ",age );
             for(j=1;j<=cptcoveff;j++)
               fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             for(i=1; i<=nlstate;i++)
               fprintf(ficrespl," %.5f", prlim[i][i]);
             fprintf(ficrespl,"\n");
           }
         }
       }
       fclose(ficrespl);
   
       /*------------- h Pij x at various ages ------------*/
    
       strcpy(filerespij,"pij");  strcat(filerespij,fileres);
       if((ficrespij=fopen(filerespij,"w"))==NULL) {
         printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
         fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
       }
       printf("Computing pij: result on file '%s' \n", filerespij);
       fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
    
       stepsize=(int) (stepm+YEARM-1)/YEARM;
       /*if (stepm<=24) stepsize=2;*/
   
       agelim=AGESUP;
       hstepm=stepsize*YEARM; /* Every year of age */
       hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
   
       /* hstepm=1;   aff par mois*/
       pstamp(ficrespij);
       fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           fprintf(ficrespij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrespij,"******\n");
          
           for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
             nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
   
             /*      nhstepm=nhstepm*YEARM; aff par mois*/
   
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             oldm=oldms;savm=savms;
             hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
             fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
             for(i=1; i<=nlstate;i++)
               for(j=1; j<=nlstate+ndeath;j++)
                 fprintf(ficrespij," %1d-%1d",i,j);
             fprintf(ficrespij,"\n");
             for (h=0; h<=nhstepm; h++){
               fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
               for(i=1; i<=nlstate;i++)
                 for(j=1; j<=nlstate+ndeath;j++)
                   fprintf(ficrespij," %.5f", p3mat[i][j][h]);
               fprintf(ficrespij,"\n");
             }
             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             fprintf(ficrespij,"\n");
           }
         }
       }
   
       varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
   
       fclose(ficrespij);
   
       probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
       for(i=1;i<=AGESUP;i++)
         for(j=1;j<=NCOVMAX;j++)
           for(k=1;k<=NCOVMAX;k++)
             probs[i][j][k]=0.;
   
       /*---------- Forecasting ------------------*/
       /*if((stepm == 1) && (strcmp(model,".")==0)){*/
       if(prevfcast==1){
         /*    if(stepm ==1){*/
         prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
         /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
         /*      }  */
         /*      else{ */
         /*        erreur=108; */
         /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
         /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
         /*      } */
       }
    
   
       /*---------- Health expectancies and variances ------------*/
   
       strcpy(filerest,"t");
       strcat(filerest,fileres);
       if((ficrest=fopen(filerest,"w"))==NULL) {
         printf("Problem with total LE resultfile: %s\n", filerest);goto end;
         fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
       }
       printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
       fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
   
   
       strcpy(filerese,"e");
       strcat(filerese,fileres);
       if((ficreseij=fopen(filerese,"w"))==NULL) {
         printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
         fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
       }
       printf("Computing Health Expectancies: result on file '%s' \n", filerese);
       fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
   
       strcpy(fileresstde,"stde");
       strcat(fileresstde,fileres);
       if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
         printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
         fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
       }
       printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
       fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
   
       strcpy(filerescve,"cve");
       strcat(filerescve,fileres);
       if((ficrescveij=fopen(filerescve,"w"))==NULL) {
         printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
         fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
       }
       printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
       fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
   
       strcpy(fileresv,"v");
       strcat(fileresv,fileres);
       if((ficresvij=fopen(fileresv,"w"))==NULL) {
         printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
         fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
       }
       printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
       fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
   
       /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
       prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
       /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
           ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
       */
   
       if (mobilav!=0) {
         mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
           fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
           printf(" Error in movingaverage mobilav=%d\n",mobilav);
         }
       }
   
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           fprintf(ficrest,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrest,"******\n");
   
           fprintf(ficreseij,"\n#****** ");
           fprintf(ficresstdeij,"\n#****** ");
           fprintf(ficrescveij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++) {
             fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           }
           fprintf(ficreseij,"******\n");
           fprintf(ficresstdeij,"******\n");
           fprintf(ficrescveij,"******\n");
   
           fprintf(ficresvij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficresvij,"******\n");
   
           eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
           evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
           cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
    
           vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);
           if(popbased==1){
             varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);
           }
   
           pstamp(ficrest);
           fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");
           for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
           fprintf(ficrest,"\n");
   
           epj=vector(1,nlstate+1);
           for(age=bage; age <=fage ;age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
             if (popbased==1) {
               if(mobilav ==0){
                 for(i=1; i<=nlstate;i++)
                   prlim[i][i]=probs[(int)age][i][k];
               }else{ /* mobilav */
                 for(i=1; i<=nlstate;i++)
                   prlim[i][i]=mobaverage[(int)age][i][k];
               }
             }
          
             fprintf(ficrest," %4.0f",age);
             for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
               for(i=1, epj[j]=0.;i <=nlstate;i++) {
                 epj[j] += prlim[i][i]*eij[i][j][(int)age];
                 /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
               }
               epj[nlstate+1] +=epj[j];
             }
   
             for(i=1, vepp=0.;i <=nlstate;i++)
               for(j=1;j <=nlstate;j++)
                 vepp += vareij[i][j][(int)age];
             fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
             for(j=1;j <=nlstate;j++){
               fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
             }
             fprintf(ficrest,"\n");
           }
           free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
           free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
           free_vector(epj,1,nlstate+1);
         }
       }
       free_vector(weight,1,n);
       free_imatrix(Tvard,1,15,1,2);
       free_imatrix(s,1,maxwav+1,1,n);
       free_matrix(anint,1,maxwav,1,n);
       free_matrix(mint,1,maxwav,1,n);
       free_ivector(cod,1,n);
       free_ivector(tab,1,NCOVMAX);
       fclose(ficreseij);
       fclose(ficresstdeij);
       fclose(ficrescveij);
       fclose(ficresvij);
       fclose(ficrest);
       fclose(ficpar);
    
       /*------- Variance of period (stable) prevalence------*/  
   
       strcpy(fileresvpl,"vpl");
       strcat(fileresvpl,fileres);
       if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
         printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
         exit(0);
       }
       printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
   
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
           fprintf(ficresvpl,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
             fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficresvpl,"******\n");
        
           varpl=matrix(1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
           varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
           free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
         }
       }
   
       fclose(ficresvpl);
   
       /*---------- End : free ----------------*/
       if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
   
     }  /* mle==-3 arrives here for freeing */
     free_matrix(prlim,1,nlstate,1,nlstate);
       free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(covar,0,NCOVMAX,1,n);
       free_matrix(matcov,1,npar,1,npar);
       /*free_vector(delti,1,npar);*/
       free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
       free_matrix(agev,1,maxwav,1,imx);
       free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
   
       free_ivector(ncodemax,1,8);
       free_ivector(Tvar,1,15);
       free_ivector(Tprod,1,15);
       free_ivector(Tvaraff,1,15);
       free_ivector(Tage,1,15);
       free_ivector(Tcode,1,100);
   
       free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
       free_imatrix(codtab,1,100,1,10);
     fflush(fichtm);
     fflush(ficgp);
    
   
     if((nberr >0) || (nbwarn>0)){
       printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
       fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
     }else{
       printf("End of Imach\n");
       fprintf(ficlog,"End of Imach\n");
     }
     printf("See log file on %s\n",filelog);
     /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
     (void) gettimeofday(&end_time,&tzp);
     tm = *localtime(&end_time.tv_sec);
     tmg = *gmtime(&end_time.tv_sec);
     strcpy(strtend,asctime(&tm));
     printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);
     fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);
     printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
   
     printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     /*  printf("Total time was %d uSec.\n", total_usecs);*/
   /*   if(fileappend(fichtm,optionfilehtm)){ */
     fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     fclose(fichtm);
     fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     fclose(fichtmcov);
     fclose(ficgp);
     fclose(ficlog);
     /*------ End -----------*/
   
   
      printf("Before Current directory %s!\n",pathcd);
      if(chdir(pathcd) != 0)
       printf("Can't move to directory %s!\n",path);
     if(getcwd(pathcd,MAXLINE) > 0)
       printf("Current directory %s!\n",pathcd);
     /*strcat(plotcmd,CHARSEPARATOR);*/
     sprintf(plotcmd,"gnuplot");
   #ifndef UNIX
     sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
   #endif
     if(!stat(plotcmd,&info)){
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       if(!stat(getenv("GNUPLOTBIN"),&info)){
         printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #ifdef UNIX
       strcpy(plotcmd,GNUPLOTPROGRAM);
       if(!stat(plotcmd,&info)){
         printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #endif
     }else
       strcpy(pplotcmd,plotcmd);
    
     sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
     printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
   
     if((outcmd=system(plotcmd)) != 0){
       printf("\n Problem with gnuplot\n");
     }
     printf(" Wait...");
     while (z[0] != 'q') {
       /* chdir(path); */
       printf("\nType e to edit output files, g to graph again and q for exiting: ");
       scanf("%s",z);
   /*     if (z[0] == 'c') system("./imach"); */
       if (z[0] == 'e') {
         printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
         system(optionfilehtm);
       }
       else if (z[0] == 'g') system(plotcmd);
       else if (z[0] == 'q') exit(0);
     }
     end:
     while (z[0] != 'q') {
       printf("\nType  q for exiting: ");
       scanf("%s",z);
     }
   }
   
   
   

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


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