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

version 1.113, 2006/02/24 14:20:24 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.113  2006/02/24 14:20:24  brouard    Revision 1.125  2006/04/04 15:20:31  lievre
   (Module): Memory leaks checks with valgrind and:    Errors in calculation of health expectancies. Age was not initialized.
   datafile was not closed, some imatrix were not freed and on matrix    Forecasting file added.
   allocation too.  
     Revision 1.124  2006/03/22 17:13:53  lievre
   Revision 1.112  2006/01/30 09:55:26  brouard    Parameters are printed with %lf instead of %f (more numbers after the comma).
   (Module): Back to gnuplot.exe instead of wgnuplot.exe    The log-likelihood is printed in the log file
   
   Revision 1.111  2006/01/25 20:38:18  brouard    Revision 1.123  2006/03/20 10:52:43  brouard
   (Module): Lots of cleaning and bugs added (Gompertz)    * imach.c (Module): <title> changed, corresponds to .htm file
   (Module): Comments can be added in data file. Missing date values    name. <head> headers where missing.
   can be a simple dot '.'.  
     * imach.c (Module): Weights can have a decimal point as for
   Revision 1.110  2006/01/25 00:51:50  brouard    English (a comma might work with a correct LC_NUMERIC environment,
   (Module): Lots of cleaning and bugs added (Gompertz)    otherwise the weight is truncated).
     Modification of warning when the covariates values are not 0 or
   Revision 1.109  2006/01/24 19:37:15  brouard    1.
   (Module): Comments (lines starting with a #) are allowed in data.    Version 0.98g
   
   Revision 1.108  2006/01/19 18:05:42  lievre    Revision 1.122  2006/03/20 09:45:41  brouard
   Gnuplot problem appeared...    (Module): Weights can have a decimal point as for
   To be fixed    English (a comma might work with a correct LC_NUMERIC environment,
     otherwise the weight is truncated).
   Revision 1.107  2006/01/19 16:20:37  brouard    Modification of warning when the covariates values are not 0 or
   Test existence of gnuplot in imach path    1.
     Version 0.98g
   Revision 1.106  2006/01/19 13:24:36  brouard  
   Some cleaning and links added in html output    Revision 1.121  2006/03/16 17:45:01  lievre
     * imach.c (Module): Comments concerning covariates added
   Revision 1.105  2006/01/05 20:23:19  lievre  
   *** empty log message ***    * imach.c (Module): refinements in the computation of lli if
     status=-2 in order to have more reliable computation if stepm is
   Revision 1.104  2005/09/30 16:11:43  lievre    not 1 month. Version 0.98f
   (Module): sump fixed, loop imx fixed, and simplifications.  
   (Module): If the status is missing at the last wave but we know    Revision 1.120  2006/03/16 15:10:38  lievre
   that the person is alive, then we can code his/her status as -2    (Module): refinements in the computation of lli if
   (instead of missing=-1 in earlier versions) and his/her    status=-2 in order to have more reliable computation if stepm is
   contributions to the likelihood is 1 - Prob of dying from last    not 1 month. Version 0.98f
   health status (= 1-p13= p11+p12 in the easiest case of somebody in  
   the healthy state at last known wave). Version is 0.98    Revision 1.119  2006/03/15 17:42:26  brouard
     (Module): Bug if status = -2, the loglikelihood was
   Revision 1.103  2005/09/30 15:54:49  lievre    computed as likelihood omitting the logarithm. Version O.98e
   (Module): sump fixed, loop imx fixed, and simplifications.  
     Revision 1.118  2006/03/14 18:20:07  brouard
   Revision 1.102  2004/09/15 17:31:30  brouard    (Module): varevsij Comments added explaining the second
   Add the possibility to read data file including tab characters.    table of variances if popbased=1 .
     (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   Revision 1.101  2004/09/15 10:38:38  brouard    (Module): Function pstamp added
   Fix on curr_time    (Module): Version 0.98d
   
   Revision 1.100  2004/07/12 18:29:06  brouard    Revision 1.117  2006/03/14 17:16:22  brouard
   Add version for Mac OS X. Just define UNIX in Makefile    (Module): varevsij Comments added explaining the second
     table of variances if popbased=1 .
   Revision 1.99  2004/06/05 08:57:40  brouard    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   *** empty log message ***    (Module): Function pstamp added
     (Module): Version 0.98d
   Revision 1.98  2004/05/16 15:05:56  brouard  
   New version 0.97 . First attempt to estimate force of mortality    Revision 1.116  2006/03/06 10:29:27  brouard
   directly from the data i.e. without the need of knowing the health    (Module): Variance-covariance wrong links and
   state at each age, but using a Gompertz model: log u =a + b*age .    varian-covariance of ej. is needed (Saito).
   This is the basic analysis of mortality and should be done before any  
   other analysis, in order to test if the mortality estimated from the    Revision 1.115  2006/02/27 12:17:45  brouard
   cross-longitudinal survey is different from the mortality estimated    (Module): One freematrix added in mlikeli! 0.98c
   from other sources like vital statistic data.  
     Revision 1.114  2006/02/26 12:57:58  brouard
   The same imach parameter file can be used but the option for mle should be -3.    (Module): Some improvements in processing parameter
     filename with strsep.
   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.113  2006/02/24 14:20:24  brouard
     (Module): Memory leaks checks with valgrind and:
   The output is very simple: only an estimate of the intercept and of    datafile was not closed, some imatrix were not freed and on matrix
   the slope with 95% confident intervals.    allocation too.
   
   Current limitations:    Revision 1.112  2006/01/30 09:55:26  brouard
   A) Even if you enter covariates, i.e. with the    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.  
   B) There is no computation of Life Expectancy nor Life Table.    Revision 1.111  2006/01/25 20:38:18  brouard
     (Module): Lots of cleaning and bugs added (Gompertz)
   Revision 1.97  2004/02/20 13:25:42  lievre    (Module): Comments can be added in data file. Missing date values
   Version 0.96d. Population forecasting command line is (temporarily)    can be a simple dot '.'.
   suppressed.  
     Revision 1.110  2006/01/25 00:51:50  brouard
   Revision 1.96  2003/07/15 15:38:55  brouard    (Module): Lots of cleaning and bugs added (Gompertz)
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is  
   rewritten within the same printf. Workaround: many printfs.    Revision 1.109  2006/01/24 19:37:15  brouard
     (Module): Comments (lines starting with a #) are allowed in data.
   Revision 1.95  2003/07/08 07:54:34  brouard  
   * imach.c (Repository):    Revision 1.108  2006/01/19 18:05:42  lievre
   (Repository): Using imachwizard code to output a more meaningful covariance    Gnuplot problem appeared...
   matrix (cov(a12,c31) instead of numbers.    To be fixed
   
   Revision 1.94  2003/06/27 13:00:02  brouard    Revision 1.107  2006/01/19 16:20:37  brouard
   Just cleaning    Test existence of gnuplot in imach path
   
   Revision 1.93  2003/06/25 16:33:55  brouard    Revision 1.106  2006/01/19 13:24:36  brouard
   (Module): On windows (cygwin) function asctime_r doesn't    Some cleaning and links added in html output
   exist so I changed back to asctime which exists.  
   (Module): Version 0.96b    Revision 1.105  2006/01/05 20:23:19  lievre
     *** empty log message ***
   Revision 1.92  2003/06/25 16:30:45  brouard  
   (Module): On windows (cygwin) function asctime_r doesn't    Revision 1.104  2005/09/30 16:11:43  lievre
   exist so I changed back to asctime which exists.    (Module): sump fixed, loop imx fixed, and simplifications.
     (Module): If the status is missing at the last wave but we know
   Revision 1.91  2003/06/25 15:30:29  brouard    that the person is alive, then we can code his/her status as -2
   * imach.c (Repository): Duplicated warning errors corrected.    (instead of missing=-1 in earlier versions) and his/her
   (Repository): Elapsed time after each iteration is now output. It    contributions to the likelihood is 1 - Prob of dying from last
   helps to forecast when convergence will be reached. Elapsed time    health status (= 1-p13= p11+p12 in the easiest case of somebody in
   is stamped in powell.  We created a new html file for the graphs    the healthy state at last known wave). Version is 0.98
   concerning matrix of covariance. It has extension -cov.htm.  
     Revision 1.103  2005/09/30 15:54:49  lievre
   Revision 1.90  2003/06/24 12:34:15  brouard    (Module): sump fixed, loop imx fixed, and simplifications.
   (Module): Some bugs corrected for windows. Also, when  
   mle=-1 a template is output in file "or"mypar.txt with the design    Revision 1.102  2004/09/15 17:31:30  brouard
   of the covariance matrix to be input.    Add the possibility to read data file including tab characters.
   
   Revision 1.89  2003/06/24 12:30:52  brouard    Revision 1.101  2004/09/15 10:38:38  brouard
   (Module): Some bugs corrected for windows. Also, when    Fix on curr_time
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.100  2004/07/12 18:29:06  brouard
     Add version for Mac OS X. Just define UNIX in Makefile
   Revision 1.88  2003/06/23 17:54:56  brouard  
   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.    Revision 1.99  2004/06/05 08:57:40  brouard
     *** empty log message ***
   Revision 1.87  2003/06/18 12:26:01  brouard  
   Version 0.96    Revision 1.98  2004/05/16 15:05:56  brouard
     New version 0.97 . First attempt to estimate force of mortality
   Revision 1.86  2003/06/17 20:04:08  brouard    directly from the data i.e. without the need of knowing the health
   (Module): Change position of html and gnuplot routines and added    state at each age, but using a Gompertz model: log u =a + b*age .
   routine fileappend.    This is the basic analysis of mortality and should be done before any
     other analysis, in order to test if the mortality estimated from the
   Revision 1.85  2003/06/17 13:12:43  brouard    cross-longitudinal survey is different from the mortality estimated
   * imach.c (Repository): Check when date of death was earlier that    from other sources like vital statistic data.
   current date of interview. It may happen when the death was just  
   prior to the death. In this case, dh was negative and likelihood    The same imach parameter file can be used but the option for mle should be -3.
   was wrong (infinity). We still send an "Error" but patch by  
   assuming that the date of death was just one stepm after the    Agnès, who wrote this part of the code, tried to keep most of the
   interview.    former routines in order to include the new code within the former code.
   (Repository): Because some people have very long ID (first column)  
   we changed int to long in num[] and we added a new lvector for    The output is very simple: only an estimate of the intercept and of
   memory allocation. But we also truncated to 8 characters (left    the slope with 95% confident intervals.
   truncation)  
   (Repository): No more line truncation errors.    Current limitations:
     A) Even if you enter covariates, i.e. with the
   Revision 1.84  2003/06/13 21:44:43  brouard    model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   * imach.c (Repository): Replace "freqsummary" at a correct    B) There is no computation of Life Expectancy nor Life Table.
   place. It differs from routine "prevalence" which may be called  
   many times. Probs is memory consuming and must be used with    Revision 1.97  2004/02/20 13:25:42  lievre
   parcimony.    Version 0.96d. Population forecasting command line is (temporarily)
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    suppressed.
   
   Revision 1.83  2003/06/10 13:39:11  lievre    Revision 1.96  2003/07/15 15:38:55  brouard
   *** empty log message ***    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
     rewritten within the same printf. Workaround: many printfs.
   Revision 1.82  2003/06/05 15:57:20  brouard  
   Add log in  imach.c and  fullversion number is now printed.    Revision 1.95  2003/07/08 07:54:34  brouard
     * imach.c (Repository):
 */    (Repository): Using imachwizard code to output a more meaningful covariance
 /*    matrix (cov(a12,c31) instead of numbers.
    Interpolated Markov Chain  
     Revision 1.94  2003/06/27 13:00:02  brouard
   Short summary of the programme:    Just cleaning
     
   This program computes Healthy Life Expectancies from    Revision 1.93  2003/06/25 16:33:55  brouard
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    (Module): On windows (cygwin) function asctime_r doesn't
   first survey ("cross") where individuals from different ages are    exist so I changed back to asctime which exists.
   interviewed on their health status or degree of disability (in the    (Module): Version 0.96b
   case of a health survey which is our main interest) -2- at least a  
   second wave of interviews ("longitudinal") which measure each change    Revision 1.92  2003/06/25 16:30:45  brouard
   (if any) in individual health status.  Health expectancies are    (Module): On windows (cygwin) function asctime_r doesn't
   computed from the time spent in each health state according to a    exist so I changed back to asctime which exists.
   model. More health states you consider, more time is necessary to reach the  
   Maximum Likelihood of the parameters involved in the model.  The    Revision 1.91  2003/06/25 15:30:29  brouard
   simplest model is the multinomial logistic model where pij is the    * imach.c (Repository): Duplicated warning errors corrected.
   probability to be observed in state j at the second wave    (Repository): Elapsed time after each iteration is now output. It
   conditional to be observed in state i at the first wave. Therefore    helps to forecast when convergence will be reached. Elapsed time
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    is stamped in powell.  We created a new html file for the graphs
   'age' is age and 'sex' is a covariate. If you want to have a more    concerning matrix of covariance. It has extension -cov.htm.
   complex model than "constant and age", you should modify the program  
   where the markup *Covariates have to be included here again* invites    Revision 1.90  2003/06/24 12:34:15  brouard
   you to do it.  More covariates you add, slower the    (Module): Some bugs corrected for windows. Also, when
   convergence.    mle=-1 a template is output in file "or"mypar.txt with the design
     of the covariance matrix to be input.
   The advantage of this computer programme, compared to a simple  
   multinomial logistic model, is clear when the delay between waves is not    Revision 1.89  2003/06/24 12:30:52  brouard
   identical for each individual. Also, if a individual missed an    (Module): Some bugs corrected for windows. Also, when
   intermediate interview, the information is lost, but taken into    mle=-1 a template is output in file "or"mypar.txt with the design
   account using an interpolation or extrapolation.      of the covariance matrix to be input.
   
   hPijx is the probability to be observed in state i at age x+h    Revision 1.88  2003/06/23 17:54:56  brouard
   conditional to the observed state i at age x. The delay 'h' can be    * 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.
   split into an exact number (nh*stepm) of unobserved intermediate  
   states. This elementary transition (by month, quarter,    Revision 1.87  2003/06/18 12:26:01  brouard
   semester or year) is modelled as a multinomial logistic.  The hPx    Version 0.96
   matrix is simply the matrix product of nh*stepm elementary matrices  
   and the contribution of each individual to the likelihood is simply    Revision 1.86  2003/06/17 20:04:08  brouard
   hPijx.    (Module): Change position of html and gnuplot routines and added
     routine fileappend.
   Also this programme outputs the covariance matrix of the parameters but also  
   of the life expectancies. It also computes the stable prevalence.     Revision 1.85  2003/06/17 13:12:43  brouard
       * imach.c (Repository): Check when date of death was earlier that
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    current date of interview. It may happen when the death was just
            Institut national d'études démographiques, Paris.    prior to the death. In this case, dh was negative and likelihood
   This software have been partly granted by Euro-REVES, a concerted action    was wrong (infinity). We still send an "Error" but patch by
   from the European Union.    assuming that the date of death was just one stepm after the
   It is copyrighted identically to a GNU software product, ie programme and    interview.
   software can be distributed freely for non commercial use. Latest version    (Repository): Because some people have very long ID (first column)
   can be accessed at http://euroreves.ined.fr/imach .    we changed int to long in num[] and we added a new lvector for
     memory allocation. But we also truncated to 8 characters (left
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    truncation)
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    (Repository): No more line truncation errors.
     
   **********************************************************************/    Revision 1.84  2003/06/13 21:44:43  brouard
 /*    * imach.c (Repository): Replace "freqsummary" at a correct
   main    place. It differs from routine "prevalence" which may be called
   read parameterfile    many times. Probs is memory consuming and must be used with
   read datafile    parcimony.
   concatwav    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
   freqsummary  
   if (mle >= 1)    Revision 1.83  2003/06/10 13:39:11  lievre
     mlikeli    *** empty log message ***
   print results files  
   if mle==1     Revision 1.82  2003/06/05 15:57:20  brouard
      computes hessian    Add log in  imach.c and  fullversion number is now printed.
   read end of parameter file: agemin, agemax, bage, fage, estepm  
       begin-prev-date,...  */
   open gnuplot file  /*
   open html file     Interpolated Markov Chain
   stable prevalence  
    for age prevalim()    Short summary of the programme:
   h Pij x   
   variance of p varprob    This program computes Healthy Life Expectancies from
   forecasting if prevfcast==1 prevforecast call prevalence()    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
   health expectancies    first survey ("cross") where individuals from different ages are
   Variance-covariance of DFLE    interviewed on their health status or degree of disability (in the
   prevalence()    case of a health survey which is our main interest) -2- at least a
    movingaverage()    second wave of interviews ("longitudinal") which measure each change
   varevsij()     (if any) in individual health status.  Health expectancies are
   if popbased==1 varevsij(,popbased)    computed from the time spent in each health state according to a
   total life expectancies    model. More health states you consider, more time is necessary to reach the
   Variance of stable prevalence    Maximum Likelihood of the parameters involved in the model.  The
  end    simplest model is the multinomial logistic model where pij is the
 */    probability to be observed in state j at the second wave
     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
     'age' is age and 'sex' is a covariate. If you want to have a more
      complex model than "constant and age", you should modify the program
 #include <math.h>    where the markup *Covariates have to be included here again* invites
 #include <stdio.h>    you to do it.  More covariates you add, slower the
 #include <stdlib.h>    convergence.
 #include <string.h>  
 #include <unistd.h>    The advantage of this computer programme, compared to a simple
     multinomial logistic model, is clear when the delay between waves is not
 #include <limits.h>    identical for each individual. Also, if a individual missed an
 #include <sys/types.h>    intermediate interview, the information is lost, but taken into
 #include <sys/stat.h>    account using an interpolation or extrapolation.  
 #include <errno.h>  
 extern int errno;    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
 /* #include <sys/time.h> */    split into an exact number (nh*stepm) of unobserved intermediate
 #include <time.h>    states. This elementary transition (by month, quarter,
 #include "timeval.h"    semester or year) is modelled as a multinomial logistic.  The hPx
     matrix is simply the matrix product of nh*stepm elementary matrices
 /* #include <libintl.h> */    and the contribution of each individual to the likelihood is simply
 /* #define _(String) gettext (String) */    hPijx.
   
 #define MAXLINE 256    Also this programme outputs the covariance matrix of the parameters but also
     of the life expectancies. It also computes the period (stable) prevalence.
 #define GNUPLOTPROGRAM "gnuplot"   
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 #define FILENAMELENGTH 132             Institut national d'études démographiques, Paris.
     This software have been partly granted by Euro-REVES, a concerted action
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */    from the European Union.
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */    It is copyrighted identically to a GNU software product, ie programme and
     software can be distributed freely for non commercial use. Latest version
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */    can be accessed at http://euroreves.ined.fr/imach .
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  
     Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 #define NINTERVMAX 8    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */   
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */    **********************************************************************/
 #define NCOVMAX 8 /* Maximum number of covariates */  /*
 #define MAXN 20000    main
 #define YEARM 12. /* Number of months per year */    read parameterfile
 #define AGESUP 130    read datafile
 #define AGEBASE 40    concatwav
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */    freqsummary
 #ifdef UNIX    if (mle >= 1)
 #define DIRSEPARATOR '/'      mlikeli
 #define CHARSEPARATOR "/"    print results files
 #define ODIRSEPARATOR '\\'    if mle==1
 #else       computes hessian
 #define DIRSEPARATOR '\\'    read end of parameter file: agemin, agemax, bage, fage, estepm
 #define CHARSEPARATOR "\\"        begin-prev-date,...
 #define ODIRSEPARATOR '/'    open gnuplot file
 #endif    open html file
     period (stable) prevalence
 /* $Id$ */     for age prevalim()
 /* $State$ */    h Pij x
     variance of p varprob
 char version[]="Imach version 0.98b, January 2006, INED-EUROREVES ";    forecasting if prevfcast==1 prevforecast call prevalence()
 char fullversion[]="$Revision$ $Date$";     health expectancies
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */    Variance-covariance of DFLE
 int nvar;    prevalence()
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;     movingaverage()
 int npar=NPARMAX;    varevsij()
 int nlstate=2; /* Number of live states */    if popbased==1 varevsij(,popbased)
 int ndeath=1; /* Number of dead states */    total life expectancies
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */    Variance of period (stable) prevalence
 int popbased=0;   end
   */
 int *wav; /* Number of waves for this individuual 0 is possible */  
 int maxwav; /* Maxim number of waves */  
 int jmin, jmax; /* min, max spacing between 2 waves */  
 int ijmin, ijmax; /* Individuals having jmin and jmax */    
 int gipmx, gsw; /* Global variables on the number of contributions   #include <math.h>
                    to the likelihood and the sum of weights (done by funcone)*/  #include <stdio.h>
 int mle, weightopt;  #include <stdlib.h>
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */  #include <string.h>
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */  #include <unistd.h>
 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. */  #include <limits.h>
 double jmean; /* Mean space between 2 waves */  #include <sys/types.h>
 double **oldm, **newm, **savm; /* Working pointers to matrices */  #include <sys/stat.h>
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */  #include <errno.h>
 FILE *fic,*ficpar, *ficparo,*ficres,  *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;  extern int errno;
 FILE *ficlog, *ficrespow;  
 int globpr; /* Global variable for printing or not */  /* #include <sys/time.h> */
 double fretone; /* Only one call to likelihood */  #include <time.h>
 long ipmx; /* Number of contributions */  #include "timeval.h"
 double sw; /* Sum of weights */  
 char filerespow[FILENAMELENGTH];  /* #include <libintl.h> */
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */  /* #define _(String) gettext (String) */
 FILE *ficresilk;  
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;  #define MAXLINE 256
 FILE *ficresprobmorprev;  
 FILE *fichtm, *fichtmcov; /* Html File */  #define GNUPLOTPROGRAM "gnuplot"
 FILE *ficreseij;  /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 char filerese[FILENAMELENGTH];  #define FILENAMELENGTH 132
 FILE  *ficresvij;  
 char fileresv[FILENAMELENGTH];  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 FILE  *ficresvpl;  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 char fileresvpl[FILENAMELENGTH];  
 char title[MAXLINE];  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
 char optionfilext[10], optionfilefiname[FILENAMELENGTH], plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];  
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];   #define NINTERVMAX 8
 char command[FILENAMELENGTH];  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 int  outcmd=0;  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
   #define NCOVMAX 8 /* Maximum number of covariates */
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  #define MAXN 20000
   #define YEARM 12. /* Number of months per year */
 char filelog[FILENAMELENGTH]; /* Log file */  #define AGESUP 130
 char filerest[FILENAMELENGTH];  #define AGEBASE 40
 char fileregp[FILENAMELENGTH];  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 char popfile[FILENAMELENGTH];  #ifdef UNIX
   #define DIRSEPARATOR '/'
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  #define CHARSEPARATOR "/"
   #define ODIRSEPARATOR '\\'
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  #else
 struct timezone tzp;  #define DIRSEPARATOR '\\'
 extern int gettimeofday();  #define CHARSEPARATOR "\\"
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  #define ODIRSEPARATOR '/'
 long time_value;  #endif
 extern long time();  
 char strcurr[80], strfor[80];  /* $Id$ */
   /* $State$ */
 char *endptr;  
 long lval;  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
   char fullversion[]="$Revision$ $Date$";
 #define NR_END 1  char strstart[80];
 #define FREE_ARG char*  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 #define FTOL 1.0e-10  int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
   int nvar;
 #define NRANSI   int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 #define ITMAX 200   int npar=NPARMAX;
   int nlstate=2; /* Number of live states */
 #define TOL 2.0e-4   int ndeath=1; /* Number of dead states */
   int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 #define CGOLD 0.3819660   int popbased=0;
 #define ZEPS 1.0e-10   
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   int *wav; /* Number of waves for this individuual 0 is possible */
   int maxwav; /* Maxim number of waves */
 #define GOLD 1.618034   int jmin, jmax; /* min, max spacing between 2 waves */
 #define GLIMIT 100.0   int ijmin, ijmax; /* Individuals having jmin and jmax */
 #define TINY 1.0e-20   int gipmx, gsw; /* Global variables on the number of contributions
                      to the likelihood and the sum of weights (done by funcone)*/
 static double maxarg1,maxarg2;  int mle, weightopt;
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  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
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))             * wave mi and wave mi+1 is not an exact multiple of stepm. */
 #define rint(a) floor(a+0.5)  double jmean; /* Mean space between 2 waves */
   double **oldm, **newm, **savm; /* Working pointers to matrices */
 static double sqrarg;  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   FILE *ficlog, *ficrespow;
 int agegomp= AGEGOMP;  int globpr; /* Global variable for printing or not */
   double fretone; /* Only one call to likelihood */
 int imx;   long ipmx; /* Number of contributions */
 int stepm=1;  double sw; /* Sum of weights */
 /* Stepm, step in month: minimum step interpolation*/  char filerespow[FILENAMELENGTH];
   char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 int estepm;  FILE *ficresilk;
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
   FILE *ficresprobmorprev;
 int m,nb;  FILE *fichtm, *fichtmcov; /* Html File */
 long *num;  FILE *ficreseij;
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  char filerese[FILENAMELENGTH];
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  FILE *ficresstdeij;
 double **pmmij, ***probs;  char fileresstde[FILENAMELENGTH];
 double *ageexmed,*agecens;  FILE *ficrescveij;
 double dateintmean=0;  char filerescve[FILENAMELENGTH];
   FILE  *ficresvij;
 double *weight;  char fileresv[FILENAMELENGTH];
 int **s; /* Status */  FILE  *ficresvpl;
 double *agedc, **covar, idx;  char fileresvpl[FILENAMELENGTH];
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  char title[MAXLINE];
 double *lsurv, *lpop, *tpop;  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
   char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
 double ftolhess; /* Tolerance for computing hessian */  char command[FILENAMELENGTH];
   int  outcmd=0;
 /**************** split *************************/  
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
 {  
   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)  char filelog[FILENAMELENGTH]; /* Log file */
      the name of the file (name), its extension only (ext) and its first part of the name (finame)  char filerest[FILENAMELENGTH];
   */   char fileregp[FILENAMELENGTH];
   char  *ss;                            /* pointer */  char popfile[FILENAMELENGTH];
   int   l1, l2;                         /* length counters */  
   char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
   l1 = strlen(path );                   /* length of path */  
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  struct timeval start_time, end_time, curr_time, last_time, forecast_time;
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  struct timezone tzp;
   if ( ss == NULL ) {                   /* no directory, so determine current directory */  extern int gettimeofday();
     strcpy( name, path );               /* we got the fullname name because no directory */  struct tm tmg, tm, tmf, *gmtime(), *localtime();
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  long time_value;
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  extern long time();
     /* get current working directory */  char strcurr[80], strfor[80];
     /*    extern  char* getcwd ( char *buf , int len);*/  
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  char *endptr;
       return( GLOCK_ERROR_GETCWD );  long lval;
     }  double dval;
     /* got dirc from getcwd*/  
     printf(" DIRC = %s \n",dirc);  #define NR_END 1
   } else {                              /* strip direcotry from path */  #define FREE_ARG char*
     ss++;                               /* after this, the filename */  #define FTOL 1.0e-10
     l2 = strlen( ss );                  /* length of filename */  
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  #define NRANSI
     strcpy( name, ss );         /* save file name */  #define ITMAX 200
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  
     dirc[l1-l2] = 0;                    /* add zero */  #define TOL 2.0e-4
     printf(" DIRC2 = %s \n",dirc);  
   }  #define CGOLD 0.3819660
   /* We add a separator at the end of dirc if not exists */  #define ZEPS 1.0e-10
   l1 = strlen( dirc );                  /* length of directory */  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
   if( dirc[l1-1] != DIRSEPARATOR ){  
     dirc[l1] =  DIRSEPARATOR;  #define GOLD 1.618034
     dirc[l1+1] = 0;   #define GLIMIT 100.0
     printf(" DIRC3 = %s \n",dirc);  #define TINY 1.0e-20
   }  
   ss = strrchr( name, '.' );            /* find last / */  static double maxarg1,maxarg2;
   if (ss >0){  #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
     ss++;  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
     strcpy(ext,ss);                     /* save extension */   
     l1= strlen( name);  #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
     l2= strlen(ss)+1;  #define rint(a) floor(a+0.5)
     strncpy( finame, name, l1-l2);  
     finame[l1-l2]= 0;  static double sqrarg;
   }  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
   #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
   return( 0 );                          /* we're done */  int agegomp= AGEGOMP;
 }  
   int imx;
   int stepm=1;
 /******************************************/  /* Stepm, step in month: minimum step interpolation*/
   
 void replace_back_to_slash(char *s, char*t)  int estepm;
 {  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   int i;  
   int lg=0;  int m,nb;
   i=0;  long *num;
   lg=strlen(t);  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
   for(i=0; i<= lg; i++) {  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
     (s[i] = t[i]);  double **pmmij, ***probs;
     if (t[i]== '\\') s[i]='/';  double *ageexmed,*agecens;
   }  double dateintmean=0;
 }  
   double *weight;
 int nbocc(char *s, char occ)  int **s; /* Status */
 {  double *agedc, **covar, idx;
   int i,j=0;  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
   int lg=20;  double *lsurv, *lpop, *tpop;
   i=0;  
   lg=strlen(s);  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
   for(i=0; i<= lg; i++) {  double ftolhess; /* Tolerance for computing hessian */
   if  (s[i] == occ ) j++;  
   }  /**************** split *************************/
   return j;  static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
 }  {
     /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 void cutv(char *u,char *v, char*t, char occ)       the name of the file (name), its extension only (ext) and its first part of the name (finame)
 {    */
   /* cuts string t into u and v where u ends before first occurence of char 'occ'     char  *ss;                            /* pointer */
      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')    int   l1, l2;                         /* length counters */
      gives u="abcedf" and v="ghi2j" */  
   int i,lg,j,p=0;    l1 = strlen(path );                   /* length of path */
   i=0;    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
   for(j=0; j<=strlen(t)-1; j++) {    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;    if ( ss == NULL ) {                   /* no directory, so determine current directory */
   }      strcpy( name, path );               /* we got the fullname name because no directory */
       /*if(strrchr(path, ODIRSEPARATOR )==NULL)
   lg=strlen(t);        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
   for(j=0; j<p; j++) {      /* get current working directory */
     (u[j] = t[j]);      /*    extern  char* getcwd ( char *buf , int len);*/
   }      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
      u[p]='\0';        return( GLOCK_ERROR_GETCWD );
       }
    for(j=0; j<= lg; j++) {      /* got dirc from getcwd*/
     if (j>=(p+1))(v[j-p-1] = t[j]);      printf(" DIRC = %s \n",dirc);
   }    } else {                              /* strip direcotry from path */
 }      ss++;                               /* after this, the filename */
       l2 = strlen( ss );                  /* length of filename */
 /********************** nrerror ********************/      if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
       strcpy( name, ss );         /* save file name */
 void nrerror(char error_text[])      strncpy( dirc, path, l1 - l2 );     /* now the directory */
 {      dirc[l1-l2] = 0;                    /* add zero */
   fprintf(stderr,"ERREUR ...\n");      printf(" DIRC2 = %s \n",dirc);
   fprintf(stderr,"%s\n",error_text);    }
   exit(EXIT_FAILURE);    /* We add a separator at the end of dirc if not exists */
 }    l1 = strlen( dirc );                  /* length of directory */
 /*********************** vector *******************/    if( dirc[l1-1] != DIRSEPARATOR ){
 double *vector(int nl, int nh)      dirc[l1] =  DIRSEPARATOR;
 {      dirc[l1+1] = 0;
   double *v;      printf(" DIRC3 = %s \n",dirc);
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));    }
   if (!v) nrerror("allocation failure in vector");    ss = strrchr( name, '.' );            /* find last / */
   return v-nl+NR_END;    if (ss >0){
 }      ss++;
       strcpy(ext,ss);                     /* save extension */
 /************************ free vector ******************/      l1= strlen( name);
 void free_vector(double*v, int nl, int nh)      l2= strlen(ss)+1;
 {      strncpy( finame, name, l1-l2);
   free((FREE_ARG)(v+nl-NR_END));      finame[l1-l2]= 0;
 }    }
   
 /************************ivector *******************************/    return( 0 );                          /* we're done */
 int *ivector(long nl,long nh)  }
 {  
   int *v;  
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));  /******************************************/
   if (!v) nrerror("allocation failure in ivector");  
   return v-nl+NR_END;  void replace_back_to_slash(char *s, char*t)
 }  {
     int i;
 /******************free ivector **************************/    int lg=0;
 void free_ivector(int *v, long nl, long nh)    i=0;
 {    lg=strlen(t);
   free((FREE_ARG)(v+nl-NR_END));    for(i=0; i<= lg; i++) {
 }      (s[i] = t[i]);
       if (t[i]== '\\') s[i]='/';
 /************************lvector *******************************/    }
 long *lvector(long nl,long nh)  }
 {  
   long *v;  int nbocc(char *s, char occ)
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));  {
   if (!v) nrerror("allocation failure in ivector");    int i,j=0;
   return v-nl+NR_END;    int lg=20;
 }    i=0;
     lg=strlen(s);
 /******************free lvector **************************/    for(i=0; i<= lg; i++) {
 void free_lvector(long *v, long nl, long nh)    if  (s[i] == occ ) j++;
 {    }
   free((FREE_ARG)(v+nl-NR_END));    return j;
 }  }
   
 /******************* imatrix *******************************/  void cutv(char *u,char *v, char*t, char occ)
 int **imatrix(long nrl, long nrh, long ncl, long nch)   {
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */     /* cuts string t into u and v where u ends before first occurence of char 'occ'
 {        and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;        gives u="abcedf" and v="ghi2j" */
   int **m;     int i,lg,j,p=0;
       i=0;
   /* allocate pointers to rows */     for(j=0; j<=strlen(t)-1; j++) {
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));       if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
   if (!m) nrerror("allocation failure 1 in matrix()");     }
   m += NR_END;   
   m -= nrl;     lg=strlen(t);
       for(j=0; j<p; j++) {
         (u[j] = t[j]);
   /* allocate rows and set pointers to them */     }
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));        u[p]='\0';
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");   
   m[nrl] += NR_END;      for(j=0; j<= lg; j++) {
   m[nrl] -= ncl;       if (j>=(p+1))(v[j-p-1] = t[j]);
       }
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;   }
     
   /* return pointer to array of pointers to rows */   /********************** nrerror ********************/
   return m;   
 }   void nrerror(char error_text[])
   {
 /****************** free_imatrix *************************/    fprintf(stderr,"ERREUR ...\n");
 void free_imatrix(m,nrl,nrh,ncl,nch)    fprintf(stderr,"%s\n",error_text);
       int **m;    exit(EXIT_FAILURE);
       long nch,ncl,nrh,nrl;   }
      /* free an int matrix allocated by imatrix() */   /*********************** vector *******************/
 {   double *vector(int nl, int nh)
   free((FREE_ARG) (m[nrl]+ncl-NR_END));   {
   free((FREE_ARG) (m+nrl-NR_END));     double *v;
 }     v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
     if (!v) nrerror("allocation failure in vector");
 /******************* matrix *******************************/    return v-nl+NR_END;
 double **matrix(long nrl, long nrh, long ncl, long nch)  }
 {  
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;  /************************ free vector ******************/
   double **m;  void free_vector(double*v, int nl, int nh)
   {
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));    free((FREE_ARG)(v+nl-NR_END));
   if (!m) nrerror("allocation failure 1 in matrix()");  }
   m += NR_END;  
   m -= nrl;  /************************ivector *******************************/
   int *ivector(long nl,long nh)
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  {
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    int *v;
   m[nrl] += NR_END;    v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
   m[nrl] -= ncl;    if (!v) nrerror("allocation failure in ivector");
     return v-nl+NR_END;
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;  }
   return m;  
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])   /******************free ivector **************************/
    */  void free_ivector(int *v, long nl, long nh)
 }  {
     free((FREE_ARG)(v+nl-NR_END));
 /*************************free matrix ************************/  }
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)  
 {  /************************lvector *******************************/
   free((FREE_ARG)(m[nrl]+ncl-NR_END));  long *lvector(long nl,long nh)
   free((FREE_ARG)(m+nrl-NR_END));  {
 }    long *v;
     v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 /******************* ma3x *******************************/    if (!v) nrerror("allocation failure in ivector");
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)    return v-nl+NR_END;
 {  }
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;  
   double ***m;  /******************free lvector **************************/
   void free_lvector(long *v, long nl, long nh)
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  {
   if (!m) nrerror("allocation failure 1 in matrix()");    free((FREE_ARG)(v+nl-NR_END));
   m += NR_END;  }
   m -= nrl;  
   /******************* imatrix *******************************/
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  int **imatrix(long nrl, long nrh, long ncl, long nch)
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");       /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
   m[nrl] += NR_END;  {
   m[nrl] -= ncl;    long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
     int **m;
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;   
     /* allocate pointers to rows */
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));    m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");    if (!m) nrerror("allocation failure 1 in matrix()");
   m[nrl][ncl] += NR_END;    m += NR_END;
   m[nrl][ncl] -= nll;    m -= nrl;
   for (j=ncl+1; j<=nch; j++)    
     m[nrl][j]=m[nrl][j-1]+nlay;   
       /* allocate rows and set pointers to them */
   for (i=nrl+1; i<=nrh; i++) {    m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     for (j=ncl+1; j<=nch; j++)     m[nrl] += NR_END;
       m[i][j]=m[i][j-1]+nlay;    m[nrl] -= ncl;
   }   
   return m;     for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])   
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)    /* return pointer to array of pointers to rows */
   */    return m;
 }  }
   
 /*************************free ma3x ************************/  /****************** free_imatrix *************************/
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)  void free_imatrix(m,nrl,nrh,ncl,nch)
 {        int **m;
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));        long nch,ncl,nrh,nrl;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));       /* free an int matrix allocated by imatrix() */
   free((FREE_ARG)(m+nrl-NR_END));  {
 }    free((FREE_ARG) (m[nrl]+ncl-NR_END));
     free((FREE_ARG) (m+nrl-NR_END));
 /*************** function subdirf ***********/  }
 char *subdirf(char fileres[])  
 {  /******************* matrix *******************************/
   /* Caution optionfilefiname is hidden */  double **matrix(long nrl, long nrh, long ncl, long nch)
   strcpy(tmpout,optionfilefiname);  {
   strcat(tmpout,"/"); /* Add to the right */    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
   strcat(tmpout,fileres);    double **m;
   return tmpout;  
 }    m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
     if (!m) nrerror("allocation failure 1 in matrix()");
 /*************** function subdirf2 ***********/    m += NR_END;
 char *subdirf2(char fileres[], char *preop)    m -= nrl;
 {  
       m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   /* Caution optionfilefiname is hidden */    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   strcpy(tmpout,optionfilefiname);    m[nrl] += NR_END;
   strcat(tmpout,"/");    m[nrl] -= ncl;
   strcat(tmpout,preop);  
   strcat(tmpout,fileres);    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   return tmpout;    return m;
 }    /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
      */
 /*************** function subdirf3 ***********/  }
 char *subdirf3(char fileres[], char *preop, char *preop2)  
 {  /*************************free matrix ************************/
     void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   /* Caution optionfilefiname is hidden */  {
   strcpy(tmpout,optionfilefiname);    free((FREE_ARG)(m[nrl]+ncl-NR_END));
   strcat(tmpout,"/");    free((FREE_ARG)(m+nrl-NR_END));
   strcat(tmpout,preop);  }
   strcat(tmpout,preop2);  
   strcat(tmpout,fileres);  /******************* ma3x *******************************/
   return tmpout;  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;
 /***************** f1dim *************************/    double ***m;
 extern int ncom;   
 extern double *pcom,*xicom;    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 extern double (*nrfunc)(double []);     if (!m) nrerror("allocation failure 1 in matrix()");
      m += NR_END;
 double f1dim(double x)     m -= nrl;
 {   
   int j;     m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   double f;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   double *xt;     m[nrl] += NR_END;
      m[nrl] -= ncl;
   xt=vector(1,ncom);   
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   f=(*nrfunc)(xt);   
   free_vector(xt,1,ncom);     m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
   return f;     if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 }     m[nrl][ncl] += NR_END;
     m[nrl][ncl] -= nll;
 /*****************brent *************************/    for (j=ncl+1; j<=nch; j++)
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)       m[nrl][j]=m[nrl][j-1]+nlay;
 {    
   int iter;     for (i=nrl+1; i<=nrh; i++) {
   double a,b,d,etemp;      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
   double fu,fv,fw,fx;      for (j=ncl+1; j<=nch; j++)
   double ftemp;        m[i][j]=m[i][j-1]+nlay;
   double p,q,r,tol1,tol2,u,v,w,x,xm;     }
   double e=0.0;     return m;
      /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
   a=(ax < cx ? ax : cx);              &(m[i][j][k]) <=> *((*(m+i) + j)+k)
   b=(ax > cx ? ax : cx);     */
   x=w=v=bx;   }
   fw=fv=fx=(*f)(x);   
   for (iter=1;iter<=ITMAX;iter++) {   /*************************free ma3x ************************/
     xm=0.5*(a+b);   void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);   {
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/    free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
     printf(".");fflush(stdout);    free((FREE_ARG)(m[nrl]+ncl-NR_END));
     fprintf(ficlog,".");fflush(ficlog);    free((FREE_ARG)(m+nrl-NR_END));
 #ifdef DEBUG  }
     printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);  
     fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);  /*************** function subdirf ***********/
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */  char *subdirf(char fileres[])
 #endif  {
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){     /* Caution optionfilefiname is hidden */
       *xmin=x;     strcpy(tmpout,optionfilefiname);
       return fx;     strcat(tmpout,"/"); /* Add to the right */
     }     strcat(tmpout,fileres);
     ftemp=fu;    return tmpout;
     if (fabs(e) > tol1) {   }
       r=(x-w)*(fx-fv);   
       q=(x-v)*(fx-fw);   /*************** function subdirf2 ***********/
       p=(x-v)*q-(x-w)*r;   char *subdirf2(char fileres[], char *preop)
       q=2.0*(q-r);   {
       if (q > 0.0) p = -p;    
       q=fabs(q);     /* Caution optionfilefiname is hidden */
       etemp=e;     strcpy(tmpout,optionfilefiname);
       e=d;     strcat(tmpout,"/");
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))     strcat(tmpout,preop);
         d=CGOLD*(e=(x >= xm ? a-x : b-x));     strcat(tmpout,fileres);
       else {     return tmpout;
         d=p/q;   }
         u=x+d;   
         if (u-a < tol2 || b-u < tol2)   /*************** function subdirf3 ***********/
           d=SIGN(tol1,xm-x);   char *subdirf3(char fileres[], char *preop, char *preop2)
       }   {
     } else {    
       d=CGOLD*(e=(x >= xm ? a-x : b-x));     /* Caution optionfilefiname is hidden */
     }     strcpy(tmpout,optionfilefiname);
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));     strcat(tmpout,"/");
     fu=(*f)(u);     strcat(tmpout,preop);
     if (fu <= fx) {     strcat(tmpout,preop2);
       if (u >= x) a=x; else b=x;     strcat(tmpout,fileres);
       SHFT(v,w,x,u)     return tmpout;
         SHFT(fv,fw,fx,fu)   }
         } else {   
           if (u < x) a=u; else b=u;   /***************** f1dim *************************/
           if (fu <= fw || w == x) {   extern int ncom;
             v=w;   extern double *pcom,*xicom;
             w=u;   extern double (*nrfunc)(double []);
             fv=fw;    
             fw=fu;   double f1dim(double x)
           } else if (fu <= fv || v == x || v == w) {   {
             v=u;     int j;
             fv=fu;     double f;
           }     double *xt;
         }    
   }     xt=vector(1,ncom);
   nrerror("Too many iterations in brent");     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
   *xmin=x;     f=(*nrfunc)(xt);
   return fx;     free_vector(xt,1,ncom);
 }     return f;
   }
 /****************** mnbrak ***********************/  
   /*****************brent *************************/
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,   double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
             double (*func)(double))   {
 {     int iter;
   double ulim,u,r,q, dum;    double a,b,d,etemp;
   double fu;     double fu,fv,fw,fx;
      double ftemp;
   *fa=(*func)(*ax);     double p,q,r,tol1,tol2,u,v,w,x,xm;
   *fb=(*func)(*bx);     double e=0.0;
   if (*fb > *fa) {    
     SHFT(dum,*ax,*bx,dum)     a=(ax < cx ? ax : cx);
       SHFT(dum,*fb,*fa,dum)     b=(ax > cx ? ax : cx);
       }     x=w=v=bx;
   *cx=(*bx)+GOLD*(*bx-*ax);     fw=fv=fx=(*f)(x);
   *fc=(*func)(*cx);     for (iter=1;iter<=ITMAX;iter++) {
   while (*fb > *fc) {       xm=0.5*(a+b);
     r=(*bx-*ax)*(*fb-*fc);       tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
     q=(*bx-*cx)*(*fb-*fa);       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/       printf(".");fflush(stdout);
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));       fprintf(ficlog,".");fflush(ficlog);
     ulim=(*bx)+GLIMIT*(*cx-*bx);   #ifdef DEBUG
     if ((*bx-u)*(u-*cx) > 0.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);
       fu=(*func)(u);       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);
     } else if ((*cx-u)*(u-ulim) > 0.0) {       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
       fu=(*func)(u);   #endif
       if (fu < *fc) {       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))         *xmin=x;
           SHFT(*fb,*fc,fu,(*func)(u))         return fx;
           }       }
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {       ftemp=fu;
       u=ulim;       if (fabs(e) > tol1) {
       fu=(*func)(u);         r=(x-w)*(fx-fv);
     } else {         q=(x-v)*(fx-fw);
       u=(*cx)+GOLD*(*cx-*bx);         p=(x-v)*q-(x-w)*r;
       fu=(*func)(u);         q=2.0*(q-r);
     }         if (q > 0.0) p = -p;
     SHFT(*ax,*bx,*cx,u)         q=fabs(q);
       SHFT(*fa,*fb,*fc,fu)         etemp=e;
       }         e=d;
 }         if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
           d=CGOLD*(e=(x >= xm ? a-x : b-x));
 /*************** linmin ************************/        else {
           d=p/q;
 int ncom;           u=x+d;
 double *pcom,*xicom;          if (u-a < tol2 || b-u < tol2)
 double (*nrfunc)(double []);             d=SIGN(tol1,xm-x);
          }
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))       } else {
 {         d=CGOLD*(e=(x >= xm ? a-x : b-x));
   double brent(double ax, double bx, double cx,       }
                double (*f)(double), double tol, double *xmin);       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
   double f1dim(double x);       fu=(*f)(u);
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,       if (fu <= fx) {
               double *fc, double (*func)(double));         if (u >= x) a=x; else b=x;
   int j;         SHFT(v,w,x,u)
   double xx,xmin,bx,ax;           SHFT(fv,fw,fx,fu)
   double fx,fb,fa;          } else {
              if (u < x) a=u; else b=u;
   ncom=n;             if (fu <= fw || w == x) {
   pcom=vector(1,n);               v=w;
   xicom=vector(1,n);               w=u;
   nrfunc=func;               fv=fw;
   for (j=1;j<=n;j++) {               fw=fu;
     pcom[j]=p[j];             } else if (fu <= fv || v == x || v == w) {
     xicom[j]=xi[j];               v=u;
   }               fv=fu;
   ax=0.0;             }
   xx=1.0;           }
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);     }
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);     nrerror("Too many iterations in brent");
 #ifdef DEBUG    *xmin=x;
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);    return fx;
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  }
 #endif  
   for (j=1;j<=n;j++) {   /****************** mnbrak ***********************/
     xi[j] *= xmin;   
     p[j] += xi[j];   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
   }               double (*func)(double))
   free_vector(xicom,1,n);   {
   free_vector(pcom,1,n);     double ulim,u,r,q, dum;
 }     double fu;
    
 char *asc_diff_time(long time_sec, char ascdiff[])    *fa=(*func)(*ax);
 {    *fb=(*func)(*bx);
   long sec_left, days, hours, minutes;    if (*fb > *fa) {
   days = (time_sec) / (60*60*24);      SHFT(dum,*ax,*bx,dum)
   sec_left = (time_sec) % (60*60*24);        SHFT(dum,*fb,*fa,dum)
   hours = (sec_left) / (60*60) ;        }
   sec_left = (sec_left) %(60*60);    *cx=(*bx)+GOLD*(*bx-*ax);
   minutes = (sec_left) /60;    *fc=(*func)(*cx);
   sec_left = (sec_left) % (60);    while (*fb > *fc) {
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);        r=(*bx-*ax)*(*fb-*fc);
   return ascdiff;      q=(*bx-*cx)*(*fb-*fa);
 }      u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
 /*************** powell ************************/      ulim=(*bx)+GLIMIT*(*cx-*bx);
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,       if ((*bx-u)*(u-*cx) > 0.0) {
             double (*func)(double []))         fu=(*func)(u);
 {       } else if ((*cx-u)*(u-ulim) > 0.0) {
   void linmin(double p[], double xi[], int n, double *fret,         fu=(*func)(u);
               double (*func)(double []));         if (fu < *fc) {
   int i,ibig,j;           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
   double del,t,*pt,*ptt,*xit;            SHFT(*fb,*fc,fu,(*func)(u))
   double fp,fptt;            }
   double *xits;      } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
   int niterf, itmp;        u=ulim;
         fu=(*func)(u);
   pt=vector(1,n);       } else {
   ptt=vector(1,n);         u=(*cx)+GOLD*(*cx-*bx);
   xit=vector(1,n);         fu=(*func)(u);
   xits=vector(1,n);       }
   *fret=(*func)(p);       SHFT(*ax,*bx,*cx,u)
   for (j=1;j<=n;j++) pt[j]=p[j];         SHFT(*fa,*fb,*fc,fu)
   for (*iter=1;;++(*iter)) {         }
     fp=(*fret);   }
     ibig=0;   
     del=0.0;   /*************** linmin ************************/
     last_time=curr_time;  
     (void) gettimeofday(&curr_time,&tzp);  int ncom;
     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);  double *pcom,*xicom;
     /*    fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);  double (*nrfunc)(double []);
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);   
     */  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
    for (i=1;i<=n;i++) {  {
       printf(" %d %.12f",i, p[i]);    double brent(double ax, double bx, double cx,
       fprintf(ficlog," %d %.12lf",i, p[i]);                 double (*f)(double), double tol, double *xmin);
       fprintf(ficrespow," %.12lf", p[i]);    double f1dim(double x);
     }    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
     printf("\n");                double *fc, double (*func)(double));
     fprintf(ficlog,"\n");    int j;
     fprintf(ficrespow,"\n");fflush(ficrespow);    double xx,xmin,bx,ax;
     if(*iter <=3){    double fx,fb,fa;
       tm = *localtime(&curr_time.tv_sec);   
       strcpy(strcurr,asctime(&tm));    ncom=n;
 /*       asctime_r(&tm,strcurr); */    pcom=vector(1,n);
       forecast_time=curr_time;     xicom=vector(1,n);
       itmp = strlen(strcurr);    nrfunc=func;
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */    for (j=1;j<=n;j++) {
         strcurr[itmp-1]='\0';      pcom[j]=p[j];
       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);      xicom[j]=xi[j];
       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){    ax=0.0;
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);    xx=1.0;
         tmf = *localtime(&forecast_time.tv_sec);    mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
 /*      asctime_r(&tmf,strfor); */    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
         strcpy(strfor,asctime(&tmf));  #ifdef DEBUG
         itmp = strlen(strfor);    printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
         if(strfor[itmp-1]=='\n')    fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
         strfor[itmp-1]='\0';  #endif
         printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);    for (j=1;j<=n;j++) {
         fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);      xi[j] *= xmin;
       }      p[j] += xi[j];
     }    }
     for (i=1;i<=n;i++) {     free_vector(xicom,1,n);
       for (j=1;j<=n;j++) xit[j]=xi[j][i];     free_vector(pcom,1,n);
       fptt=(*fret);   }
 #ifdef DEBUG  
       printf("fret=%lf \n",*fret);  char *asc_diff_time(long time_sec, char ascdiff[])
       fprintf(ficlog,"fret=%lf \n",*fret);  {
 #endif    long sec_left, days, hours, minutes;
       printf("%d",i);fflush(stdout);    days = (time_sec) / (60*60*24);
       fprintf(ficlog,"%d",i);fflush(ficlog);    sec_left = (time_sec) % (60*60*24);
       linmin(p,xit,n,fret,func);     hours = (sec_left) / (60*60) ;
       if (fabs(fptt-(*fret)) > del) {     sec_left = (sec_left) %(60*60);
         del=fabs(fptt-(*fret));     minutes = (sec_left) /60;
         ibig=i;     sec_left = (sec_left) % (60);
       }     sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
 #ifdef DEBUG    return ascdiff;
       printf("%d %.12e",i,(*fret));  }
       fprintf(ficlog,"%d %.12e",i,(*fret));  
       for (j=1;j<=n;j++) {  /*************** powell ************************/
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
         printf(" x(%d)=%.12e",j,xit[j]);              double (*func)(double []))
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);  {
       }    void linmin(double p[], double xi[], int n, double *fret,
       for(j=1;j<=n;j++) {                double (*func)(double []));
         printf(" p=%.12e",p[j]);    int i,ibig,j;
         fprintf(ficlog," p=%.12e",p[j]);    double del,t,*pt,*ptt,*xit;
       }    double fp,fptt;
       printf("\n");    double *xits;
       fprintf(ficlog,"\n");    int niterf, itmp;
 #endif  
     }     pt=vector(1,n);
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {    ptt=vector(1,n);
 #ifdef DEBUG    xit=vector(1,n);
       int k[2],l;    xits=vector(1,n);
       k[0]=1;    *fret=(*func)(p);
       k[1]=-1;    for (j=1;j<=n;j++) pt[j]=p[j];
       printf("Max: %.12e",(*func)(p));    for (*iter=1;;++(*iter)) {
       fprintf(ficlog,"Max: %.12e",(*func)(p));      fp=(*fret);
       for (j=1;j<=n;j++) {      ibig=0;
         printf(" %.12e",p[j]);      del=0.0;
         fprintf(ficlog," %.12e",p[j]);      last_time=curr_time;
       }      (void) gettimeofday(&curr_time,&tzp);
       printf("\n");      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,"\n");      fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
       for(l=0;l<=1;l++) {  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
         for (j=1;j<=n;j++) {     for (i=1;i<=n;i++) {
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];        printf(" %d %.12f",i, p[i]);
           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," %d %.12lf",i, p[i]);
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        fprintf(ficrespow," %.12lf", p[i]);
         }      }
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));      printf("\n");
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));      fprintf(ficlog,"\n");
       }      fprintf(ficrespow,"\n");fflush(ficrespow);
 #endif      if(*iter <=3){
         tm = *localtime(&curr_time.tv_sec);
         strcpy(strcurr,asctime(&tm));
       free_vector(xit,1,n);   /*       asctime_r(&tm,strcurr); */
       free_vector(xits,1,n);         forecast_time=curr_time;
       free_vector(ptt,1,n);         itmp = strlen(strcurr);
       free_vector(pt,1,n);         if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
       return;           strcurr[itmp-1]='\0';
     }         printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");         fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
     for (j=1;j<=n;j++) {         for(niterf=10;niterf<=30;niterf+=10){
       ptt[j]=2.0*p[j]-pt[j];           forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
       xit[j]=p[j]-pt[j];           tmf = *localtime(&forecast_time.tv_sec);
       pt[j]=p[j];   /*      asctime_r(&tmf,strfor); */
     }           strcpy(strfor,asctime(&tmf));
     fptt=(*func)(ptt);           itmp = strlen(strfor);
     if (fptt < fp) {           if(strfor[itmp-1]=='\n')
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);           strfor[itmp-1]='\0';
       if (t < 0.0) {           printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
         linmin(p,xit,n,fret,func);           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 (j=1;j<=n;j++) {         }
           xi[j][ibig]=xi[j][n];       }
           xi[j][n]=xit[j];       for (i=1;i<=n;i++) {
         }        for (j=1;j<=n;j++) xit[j]=xi[j][i];
 #ifdef DEBUG        fptt=(*fret);
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);  #ifdef DEBUG
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        printf("fret=%lf \n",*fret);
         for(j=1;j<=n;j++){        fprintf(ficlog,"fret=%lf \n",*fret);
           printf(" %.12e",xit[j]);  #endif
           fprintf(ficlog," %.12e",xit[j]);        printf("%d",i);fflush(stdout);
         }        fprintf(ficlog,"%d",i);fflush(ficlog);
         printf("\n");        linmin(p,xit,n,fret,func);
         fprintf(ficlog,"\n");        if (fabs(fptt-(*fret)) > del) {
 #endif          del=fabs(fptt-(*fret));
       }          ibig=i;
     }         }
   }   #ifdef DEBUG
 }         printf("%d %.12e",i,(*fret));
         fprintf(ficlog,"%d %.12e",i,(*fret));
 /**** Prevalence limit (stable prevalence)  ****************/        for (j=1;j<=n;j++) {
           xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)          printf(" x(%d)=%.12e",j,xit[j]);
 {          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit        }
      matrix by transitions matrix until convergence is reached */        for(j=1;j<=n;j++) {
           printf(" p=%.12e",p[j]);
   int i, ii,j,k;          fprintf(ficlog," p=%.12e",p[j]);
   double min, max, maxmin, maxmax,sumnew=0.;        }
   double **matprod2();        printf("\n");
   double **out, cov[NCOVMAX], **pmij();        fprintf(ficlog,"\n");
   double **newm;  #endif
   double agefin, delaymax=50 ; /* Max number of years to converge */      }
       if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
   for (ii=1;ii<=nlstate+ndeath;ii++)  #ifdef DEBUG
     for (j=1;j<=nlstate+ndeath;j++){        int k[2],l;
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);        k[0]=1;
     }        k[1]=-1;
         printf("Max: %.12e",(*func)(p));
    cov[1]=1.;        fprintf(ficlog,"Max: %.12e",(*func)(p));
          for (j=1;j<=n;j++) {
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */          printf(" %.12e",p[j]);
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){          fprintf(ficlog," %.12e",p[j]);
     newm=savm;        }
     /* Covariates have to be included here again */        printf("\n");
      cov[2]=agefin;        fprintf(ficlog,"\n");
           for(l=0;l<=1;l++) {
       for (k=1; k<=cptcovn;k++) {          for (j=1;j<=n;j++) {
         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];            ptt[j]=p[j]+(p[j]-pt[j])*k[l];
         /*      printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/            printf("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]);
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          }
       for (k=1; k<=cptcovprod;k++)          printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
         }
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/  #endif
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/  
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/  
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);        free_vector(xit,1,n);
         free_vector(xits,1,n);
     savm=oldm;        free_vector(ptt,1,n);
     oldm=newm;        free_vector(pt,1,n);
     maxmax=0.;        return;
     for(j=1;j<=nlstate;j++){      }
       min=1.;      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
       max=0.;      for (j=1;j<=n;j++) {
       for(i=1; i<=nlstate; i++) {        ptt[j]=2.0*p[j]-pt[j];
         sumnew=0;        xit[j]=p[j]-pt[j];
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];        pt[j]=p[j];
         prlim[i][j]= newm[i][j]/(1-sumnew);      }
         max=FMAX(max,prlim[i][j]);      fptt=(*func)(ptt);
         min=FMIN(min,prlim[i][j]);      if (fptt < fp) {
       }        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
       maxmin=max-min;        if (t < 0.0) {
       maxmax=FMAX(maxmax,maxmin);          linmin(p,xit,n,fret,func);
     }          for (j=1;j<=n;j++) {
     if(maxmax < ftolpl){            xi[j][ibig]=xi[j][n];
       return prlim;            xi[j][n]=xit[j];
     }          }
   }  #ifdef DEBUG
 }          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
           fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 /*************** transition probabilities ***************/           for(j=1;j<=n;j++){
             printf(" %.12e",xit[j]);
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )            fprintf(ficlog," %.12e",xit[j]);
 {          }
   double s1, s2;          printf("\n");
   /*double t34;*/          fprintf(ficlog,"\n");
   int i,j,j1, nc, ii, jj;  #endif
         }
     for(i=1; i<= nlstate; i++){      }
       for(j=1; j<i;j++){    }
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){  }
           /*s2 += param[i][j][nc]*cov[nc];*/  
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];  /**** Prevalence limit (stable or period prevalence)  ****************/
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */  
         }  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
         ps[i][j]=s2;  {
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
       }       matrix by transitions matrix until convergence is reached */
       for(j=i+1; j<=nlstate+ndeath;j++){  
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){    int i, ii,j,k;
           s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];    double min, max, maxmin, maxmax,sumnew=0.;
 /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */    double **matprod2();
         }    double **out, cov[NCOVMAX], **pmij();
         ps[i][j]=s2;    double **newm;
       }    double agefin, delaymax=50 ; /* Max number of years to converge */
     }  
     /*ps[3][2]=1;*/    for (ii=1;ii<=nlstate+ndeath;ii++)
           for (j=1;j<=nlstate+ndeath;j++){
     for(i=1; i<= nlstate; i++){        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       s1=0;      }
       for(j=1; j<i; j++)  
         s1+=exp(ps[i][j]);     cov[1]=1.;
       for(j=i+1; j<=nlstate+ndeath; j++)   
         s1+=exp(ps[i][j]);   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
       ps[i][i]=1./(s1+1.);    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
       for(j=1; j<i; j++)      newm=savm;
         ps[i][j]= exp(ps[i][j])*ps[i][i];      /* Covariates have to be included here again */
       for(j=i+1; j<=nlstate+ndeath; j++)       cov[2]=agefin;
         ps[i][j]= exp(ps[i][j])*ps[i][i];   
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */        for (k=1; k<=cptcovn;k++) {
     } /* end i */          cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
               /*      printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){        }
       for(jj=1; jj<= nlstate+ndeath; jj++){        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         ps[ii][jj]=0;        for (k=1; k<=cptcovprod;k++)
         ps[ii][ii]=1;          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
       }  
     }        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
             /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
         /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */  
 /*         printf("ddd %lf ",ps[ii][jj]); */      savm=oldm;
 /*       } */      oldm=newm;
 /*       printf("\n "); */      maxmax=0.;
 /*        } */      for(j=1;j<=nlstate;j++){
 /*        printf("\n ");printf("%lf ",cov[2]); */        min=1.;
        /*        max=0.;
       for(i=1; i<= npar; i++) printf("%f ",x[i]);        for(i=1; i<=nlstate; i++) {
       goto end;*/          sumnew=0;
     return ps;          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 }          prlim[i][j]= newm[i][j]/(1-sumnew);
           max=FMAX(max,prlim[i][j]);
 /**************** Product of 2 matrices ******************/          min=FMIN(min,prlim[i][j]);
         }
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)        maxmin=max-min;
 {        maxmax=FMAX(maxmax,maxmin);
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times      }
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */      if(maxmax < ftolpl){
   /* in, b, out are matrice of pointers which should have been initialized         return prlim;
      before: only the contents of out is modified. The function returns      }
      a pointer to pointers identical to out */    }
   long i, j, k;  }
   for(i=nrl; i<= nrh; i++)  
     for(k=ncolol; k<=ncoloh; k++)  /*************** transition probabilities ***************/
       for(j=ncl,out[i][k]=0.; j<=nch; j++)  
         out[i][k] +=in[i][j]*b[j][k];  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
   {
   return out;    double s1, s2;
 }    /*double t34;*/
     int i,j,j1, nc, ii, jj;
   
 /************* Higher Matrix Product ***************/      for(i=1; i<= nlstate; i++){
         for(j=1; j<i;j++){
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
 {            /*s2 += param[i][j][nc]*cov[nc];*/
   /* Computes the transition matrix starting at age 'age' over             s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
      'nhstepm*hstepm*stepm' months (i.e. until  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying           }
      nhstepm*hstepm matrices.           ps[i][j]=s2;
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step   /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
      (typically every 2 years instead of every month which is too big         }
      for the memory).        for(j=i+1; j<=nlstate+ndeath;j++){
      Model is determined by parameters x and covariates have to be           for (nc=1, s2=0.;nc <=ncovmodel; nc++){
      included manually here.             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); */
      */          }
           ps[i][j]=s2;
   int i, j, d, h, k;        }
   double **out, cov[NCOVMAX];      }
   double **newm;      /*ps[3][2]=1;*/
      
   /* Hstepm could be zero and should return the unit matrix */      for(i=1; i<= nlstate; i++){
   for (i=1;i<=nlstate+ndeath;i++)        s1=0;
     for (j=1;j<=nlstate+ndeath;j++){        for(j=1; j<i; j++)
       oldm[i][j]=(i==j ? 1.0 : 0.0);          s1+=exp(ps[i][j]);
       po[i][j][0]=(i==j ? 1.0 : 0.0);        for(j=i+1; j<=nlstate+ndeath; j++)
     }          s1+=exp(ps[i][j]);
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */        ps[i][i]=1./(s1+1.);
   for(h=1; h <=nhstepm; h++){        for(j=1; j<i; j++)
     for(d=1; d <=hstepm; d++){          ps[i][j]= exp(ps[i][j])*ps[i][i];
       newm=savm;        for(j=i+1; j<=nlstate+ndeath; j++)
       /* Covariates have to be included here again */          ps[i][j]= exp(ps[i][j])*ps[i][i];
       cov[1]=1.;        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;      } /* end i */
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];     
       for (k=1; k<=cptcovage;k++)      for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];        for(jj=1; jj<= nlstate+ndeath; jj++){
       for (k=1; k<=cptcovprod;k++)          ps[ii][jj]=0;
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];          ps[ii][ii]=1;
         }
       }
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/     
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/  
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,   /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
                    pmij(pmmij,cov,ncovmodel,x,nlstate));  /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
       savm=oldm;  /*         printf("ddd %lf ",ps[ii][jj]); */
       oldm=newm;  /*       } */
     }  /*       printf("\n "); */
     for(i=1; i<=nlstate+ndeath; i++)  /*        } */
       for(j=1;j<=nlstate+ndeath;j++) {  /*        printf("\n ");printf("%lf ",cov[2]); */
         po[i][j][h]=newm[i][j];         /*
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);        for(i=1; i<= npar; i++) printf("%f ",x[i]);
          */        goto end;*/
       }      return ps;
   } /* end h */  }
   return po;  
 }  /**************** Product of 2 matrices ******************/
   
   double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
 /*************** log-likelihood *************/  {
 double func( double *x)    /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 {       b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
   int i, ii, j, k, mi, d, kk;    /* in, b, out are matrice of pointers which should have been initialized
   double l, ll[NLSTATEMAX], cov[NCOVMAX];       before: only the contents of out is modified. The function returns
   double **out;       a pointer to pointers identical to out */
   double sw; /* Sum of weights */    long i, j, k;
   double lli; /* Individual log likelihood */    for(i=nrl; i<= nrh; i++)
   int s1, s2;      for(k=ncolol; k<=ncoloh; k++)
   double bbh, survp;        for(j=ncl,out[i][k]=0.; j<=nch; j++)
   long ipmx;          out[i][k] +=in[i][j]*b[j][k];
   /*extern weight */  
   /* We are differentiating ll according to initial status */    return out;
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/  }
   /*for(i=1;i<imx;i++)   
     printf(" %d\n",s[4][i]);  
   */  /************* Higher Matrix Product ***************/
   cov[1]=1.;  
   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<=nlstate; k++) ll[k]=0.;  {
     /* Computes the transition matrix starting at age 'age' over
   if(mle==1){       'nhstepm*hstepm*stepm' months (i.e. until
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];       nhstepm*hstepm matrices.
       for(mi=1; mi<= wav[i]-1; mi++){       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
         for (ii=1;ii<=nlstate+ndeath;ii++)       (typically every 2 years instead of every month which is too big
           for (j=1;j<=nlstate+ndeath;j++){       for the memory).
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);       Model is determined by parameters x and covariates have to be
             savm[ii][j]=(ii==j ? 1.0 : 0.0);       included manually here.
           }  
         for(d=0; d<dh[mi][i]; d++){       */
           newm=savm;  
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    int i, j, d, h, k;
           for (kk=1; kk<=cptcovage;kk++) {    double **out, cov[NCOVMAX];
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    double **newm;
           }  
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    /* Hstepm could be zero and should return the unit matrix */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    for (i=1;i<=nlstate+ndeath;i++)
           savm=oldm;      for (j=1;j<=nlstate+ndeath;j++){
           oldm=newm;        oldm[i][j]=(i==j ? 1.0 : 0.0);
         } /* end mult */        po[i][j][0]=(i==j ? 1.0 : 0.0);
             }
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
         /* But now since version 0.9 we anticipate for bias at large stepm.    for(h=1; h <=nhstepm; h++){
          * If stepm is larger than one month (smallest stepm) and if the exact delay       for(d=1; d <=hstepm; d++){
          * (in months) between two waves is not a multiple of stepm, we rounded to         newm=savm;
          * the nearest (and in case of equal distance, to the lowest) interval but now        /* Covariates have to be included here again */
          * we keep into memory the bias bh[mi][i] and also the previous matrix product        cov[1]=1.;
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
          * probability in order to take into account the bias as a fraction of the way        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies        for (k=1; k<=cptcovage;k++)
          * -stepm/2 to stepm/2 .          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
          * For stepm=1 the results are the same as for previous versions of Imach.        for (k=1; k<=cptcovprod;k++)
          * For stepm > 1 the results are less biased than in previous versions.           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
          */  
         s1=s[mw[mi][i]][i];  
         s2=s[mw[mi+1][i]][i];        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
         bbh=(double)bh[mi][i]/(double)stepm;         /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
         /* bias bh is positive if real duration        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
          * is higher than the multiple of stepm and negative otherwise.                     pmij(pmmij,cov,ncovmodel,x,nlstate));
          */        savm=oldm;
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/        oldm=newm;
         if( s2 > nlstate){       }
           /* i.e. if s2 is a death state and if the date of death is known       for(i=1; i<=nlstate+ndeath; i++)
              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,           po[i][j][h]=newm[i][j];
              which is also equal to probability to die before dh           /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
              minus probability to die before dh-stepm .            */
              In version up to 0.92 likelihood was computed        }
         as if date of death was unknown. Death was treated as any other    } /* end h */
         health state: the date of the interview describes the actual state    return po;
         and not the date of a change in health state. The former idea was  }
         to consider that at each interview the state was recorded  
         (healthy, disable or death) and IMaCh was corrected; but when we  
         introduced the exact date of death then we should have modified  /*************** log-likelihood *************/
         the contribution of an exact death to the likelihood. This new  double func( double *x)
         contribution is smaller and very dependent of the step unit  {
         stepm. It is no more the probability to die between last interview    int i, ii, j, k, mi, d, kk;
         and month of death but the probability to survive from last    double l, ll[NLSTATEMAX], cov[NCOVMAX];
         interview up to one month before death multiplied by the    double **out;
         probability to die within a month. Thanks to Chris    double sw; /* Sum of weights */
         Jackson for correcting this bug.  Former versions increased    double lli; /* Individual log likelihood */
         mortality artificially. The bad side is that we add another loop    int s1, s2;
         which slows down the processing. The difference can be up to 10%    double bbh, survp;
         lower mortality.    long ipmx;
           */    /*extern weight */
           lli=log(out[s1][s2] - savm[s1][s2]);    /* We are differentiating ll according to initial status */
     /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
     /*for(i=1;i<imx;i++)
         } else if  (s2==-2) {      printf(" %d\n",s[4][i]);
           for (j=1,survp=0. ; j<=nlstate; j++)     */
             survp += out[s1][j];    cov[1]=1.;
           lli= survp;  
         }    for(k=1; k<=nlstate; k++) ll[k]=0.;
           
         else if  (s2==-4) {    if(mle==1){
           for (j=3,survp=0. ; j<=nlstate; j++)       for (i=1,ipmx=0, sw=0.; i<=imx; i++){
             survp += out[s1][j];        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           lli= survp;        for(mi=1; mi<= wav[i]-1; mi++){
         }          for (ii=1;ii<=nlstate+ndeath;ii++)
                     for (j=1;j<=nlstate+ndeath;j++){
         else if  (s2==-5) {              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           for (j=1,survp=0. ; j<=2; j++)               savm[ii][j]=(ii==j ? 1.0 : 0.0);
             survp += out[s1][j];            }
           lli= survp;          for(d=0; d<dh[mi][i]; d++){
         }            newm=savm;
             cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
             for (kk=1; kk<=cptcovage;kk++) {
         else{              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
           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];          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          /* But now since version 0.9 we anticipate for bias at large stepm.
       } /* end of wave */           * If stepm is larger than one month (smallest stepm) and if the exact delay
     } /* end of individual */           * (in months) between two waves is not a multiple of stepm, we rounded to
   }  else if(mle==2){           * the nearest (and in case of equal distance, to the lowest) interval but now
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){           * we keep into memory the bias bh[mi][i] and also the previous matrix product
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
       for(mi=1; mi<= wav[i]-1; mi++){           * probability in order to take into account the bias as a fraction of the way
         for (ii=1;ii<=nlstate+ndeath;ii++)           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
           for (j=1;j<=nlstate+ndeath;j++){           * -stepm/2 to stepm/2 .
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);           * For stepm=1 the results are the same as for previous versions of Imach.
             savm[ii][j]=(ii==j ? 1.0 : 0.0);           * For stepm > 1 the results are less biased than in previous versions.
           }           */
         for(d=0; d<=dh[mi][i]; d++){          s1=s[mw[mi][i]][i];
           newm=savm;          s2=s[mw[mi+1][i]][i];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          bbh=(double)bh[mi][i]/(double)stepm;
           for (kk=1; kk<=cptcovage;kk++) {          /* bias bh is positive if real duration
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];           * is higher than the multiple of stepm and negative otherwise.
           }           */
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          if( s2 > nlstate){
           savm=oldm;            /* i.e. if s2 is a death state and if the date of death is known
           oldm=newm;               then the contribution to the likelihood is the probability to
         } /* end mult */               die between last step unit time and current  step unit time,
                      which is also equal to probability to die before dh
         s1=s[mw[mi][i]][i];               minus probability to die before dh-stepm .
         s2=s[mw[mi+1][i]][i];               In version up to 0.92 likelihood was computed
         bbh=(double)bh[mi][i]/(double)stepm;           as if date of death was unknown. Death was treated as any other
         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 */          health state: the date of the interview describes the actual state
         ipmx +=1;          and not the date of a change in health state. The former idea was
         sw += weight[i];          to consider that at each interview the state was recorded
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          (healthy, disable or death) and IMaCh was corrected; but when we
       } /* end of wave */          introduced the exact date of death then we should have modified
     } /* end of individual */          the contribution of an exact death to the likelihood. This new
   }  else if(mle==3){  /* exponential inter-extrapolation */          contribution is smaller and very dependent of the step unit
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          stepm. It is no more the probability to die between last interview
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          and month of death but the probability to survive from last
       for(mi=1; mi<= wav[i]-1; mi++){          interview up to one month before death multiplied by the
         for (ii=1;ii<=nlstate+ndeath;ii++)          probability to die within a month. Thanks to Chris
           for (j=1;j<=nlstate+ndeath;j++){          Jackson for correcting this bug.  Former versions increased
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          mortality artificially. The bad side is that we add another loop
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          which slows down the processing. The difference can be up to 10%
           }          lower mortality.
         for(d=0; d<dh[mi][i]; d++){            */
           newm=savm;            lli=log(out[s1][s2] - savm[s1][s2]);
           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 if  (s2==-2) {
           }            for (j=1,survp=0. ; j<=nlstate; j++)
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            /*survp += out[s1][j]; */
           savm=oldm;            lli= log(survp);
           oldm=newm;          }
         } /* end mult */         
                 else if  (s2==-4) {
         s1=s[mw[mi][i]][i];            for (j=3,survp=0. ; j<=nlstate; j++)  
         s2=s[mw[mi+1][i]][i];              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         bbh=(double)bh[mi][i]/(double)stepm;             lli= log(survp);
         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;  
         sw += weight[i];          else if  (s2==-5) {
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            for (j=1,survp=0. ; j<=2; j++)  
       } /* end of wave */              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
     } /* end of individual */            lli= log(survp);
   }else if (mle==4){  /* ml=4 no inter-extrapolation */          }
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){         
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          else{
       for(mi=1; mi<= wav[i]-1; mi++){            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
         for (ii=1;ii<=nlstate+ndeath;ii++)            /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
           for (j=1;j<=nlstate+ndeath;j++){          }
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          /*if(lli ==000.0)*/
           }          /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
         for(d=0; d<dh[mi][i]; d++){          ipmx +=1;
           newm=savm;          sw += weight[i];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           for (kk=1; kk<=cptcovage;kk++) {        } /* end of wave */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];      } /* end of individual */
           }    }  else if(mle==2){
               for (i=1,ipmx=0, sw=0.; i<=imx; i++){
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));        for(mi=1; mi<= wav[i]-1; mi++){
           savm=oldm;          for (ii=1;ii<=nlstate+ndeath;ii++)
           oldm=newm;            for (j=1;j<=nlstate+ndeath;j++){
         } /* end mult */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                     savm[ii][j]=(ii==j ? 1.0 : 0.0);
         s1=s[mw[mi][i]][i];            }
         s2=s[mw[mi+1][i]][i];          for(d=0; d<=dh[mi][i]; d++){
         if( s2 > nlstate){             newm=savm;
           lli=log(out[s1][s2] - savm[s1][s2]);            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         }else{            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];
         }            }
         ipmx +=1;            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         sw += weight[i];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            savm=oldm;
 /*      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]); */            oldm=newm;
       } /* end of wave */          } /* end mult */
     } /* end of individual */       
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */          s1=s[mw[mi][i]][i];
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          s2=s[mw[mi+1][i]][i];
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          bbh=(double)bh[mi][i]/(double)stepm;
       for(mi=1; mi<= wav[i]-1; mi++){          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 (ii=1;ii<=nlstate+ndeath;ii++)          ipmx +=1;
           for (j=1;j<=nlstate+ndeath;j++){          sw += weight[i];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);        } /* end of wave */
           }      } /* end of individual */
         for(d=0; d<dh[mi][i]; d++){    }  else if(mle==3){  /* exponential inter-extrapolation */
           newm=savm;      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           for (kk=1; kk<=cptcovage;kk++) {        for(mi=1; mi<= wav[i]-1; mi++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          for (ii=1;ii<=nlstate+ndeath;ii++)
           }            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++) {
         s1=s[mw[mi][i]][i];              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         s2=s[mw[mi+1][i]][i];            }
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         ipmx +=1;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         sw += weight[i];            savm=oldm;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            oldm=newm;
         /*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 mult */
       } /* end of wave */       
     } /* end of individual */          s1=s[mw[mi][i]][i];
   } /* End of if */          s2=s[mw[mi+1][i]][i];
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];          bbh=(double)bh[mi][i]/(double)stepm;
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */          lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          ipmx +=1;
   return -l;          sw += weight[i];
 }          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         } /* end of wave */
 /*************** log-likelihood *************/      } /* end of individual */
 double funcone( double *x)    }else if (mle==4){  /* ml=4 no inter-extrapolation */
 {      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   /* Same as likeli but slower because of a lot of printf and if */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   int i, ii, j, k, mi, d, kk;        for(mi=1; mi<= wav[i]-1; mi++){
   double l, ll[NLSTATEMAX], cov[NCOVMAX];          for (ii=1;ii<=nlstate+ndeath;ii++)
   double **out;            for (j=1;j<=nlstate+ndeath;j++){
   double lli; /* Individual log likelihood */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   double llt;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   int s1, s2;            }
   double bbh, survp;          for(d=0; d<dh[mi][i]; d++){
   /*extern weight */            newm=savm;
   /* We are differentiating ll according to initial status */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/            for (kk=1; kk<=cptcovage;kk++) {
   /*for(i=1;i<imx;i++)               cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     printf(" %d\n",s[4][i]);            }
   */         
   cov[1]=1.;            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   for(k=1; k<=nlstate; k++) ll[k]=0.;            savm=oldm;
             oldm=newm;
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){          } /* end mult */
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];       
     for(mi=1; mi<= wav[i]-1; mi++){          s1=s[mw[mi][i]][i];
       for (ii=1;ii<=nlstate+ndeath;ii++)          s2=s[mw[mi+1][i]][i];
         for (j=1;j<=nlstate+ndeath;j++){          if( s2 > nlstate){
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);            lli=log(out[s1][s2] - savm[s1][s2]);
           savm[ii][j]=(ii==j ? 1.0 : 0.0);          }else{
         }            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
       for(d=0; d<dh[mi][i]; d++){          }
         newm=savm;          ipmx +=1;
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          sw += weight[i];
         for (kk=1; kk<=cptcovage;kk++) {          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];  /*      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 */
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,      } /* end of individual */
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
         savm=oldm;      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         oldm=newm;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       } /* end mult */        for(mi=1; mi<= wav[i]-1; mi++){
                 for (ii=1;ii<=nlstate+ndeath;ii++)
       s1=s[mw[mi][i]][i];            for (j=1;j<=nlstate+ndeath;j++){
       s2=s[mw[mi+1][i]][i];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       bbh=(double)bh[mi][i]/(double)stepm;               savm[ii][j]=(ii==j ? 1.0 : 0.0);
       /* bias is positive if real duration            }
        * is higher than the multiple of stepm and negative otherwise.          for(d=0; d<dh[mi][i]; d++){
        */            newm=savm;
       if( s2 > nlstate && (mle <5) ){  /* Jackson */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         lli=log(out[s1][s2] - savm[s1][s2]);            for (kk=1; kk<=cptcovage;kk++) {
       } else if (mle==1){              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */            }
       } else if(mle==2){         
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
       } else if(mle==3){  /* exponential inter-extrapolation */                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         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=oldm;
       } else if (mle==4){  /* mle=4 no inter-extrapolation */            oldm=newm;
         lli=log(out[s1][s2]); /* Original formula */          } /* end mult */
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */       
         lli=log(out[s1][s2]); /* Original formula */          s1=s[mw[mi][i]][i];
       } /* End of if */          s2=s[mw[mi+1][i]][i];
       ipmx +=1;          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
       sw += weight[i];          ipmx +=1;
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          sw += weight[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]); */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       if(globpr){          /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/
         fprintf(ficresilk,"%9d %6d %1d %1d %1d %1d %3d %10.6f %6.4f\        } /* end of wave */
  %10.6f %10.6f %10.6f ", \      } /* end of individual */
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],    } /* End of if */
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
           llt +=ll[k]*gipmx/gsw;    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);    return -l;
         }  }
         fprintf(ficresilk," %10.6f\n", -llt);  
       }  /*************** log-likelihood *************/
     } /* end of wave */  double funcone( double *x)
   } /* end of individual */  {
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];    /* Same as likeli but slower because of a lot of printf and if */
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */    int i, ii, j, k, mi, d, kk;
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */    double l, ll[NLSTATEMAX], cov[NCOVMAX];
   if(globpr==0){ /* First time we count the contributions and weights */    double **out;
     gipmx=ipmx;    double lli; /* Individual log likelihood */
     gsw=sw;    double llt;
   }    int s1, s2;
   return -l;    double bbh, survp;
 }    /*extern weight */
     /* We are differentiating ll according to initial status */
     /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 /*************** function likelione ***********/    /*for(i=1;i<imx;i++)
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))      printf(" %d\n",s[4][i]);
 {    */
   /* This routine should help understanding what is done with     cov[1]=1.;
      the selection of individuals/waves and  
      to check the exact contribution to the likelihood.    for(k=1; k<=nlstate; k++) ll[k]=0.;
      Plotting could be done.  
    */    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   int k;      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       for(mi=1; mi<= wav[i]-1; mi++){
   if(*globpri !=0){ /* Just counts and sums, no printings */        for (ii=1;ii<=nlstate+ndeath;ii++)
     strcpy(fileresilk,"ilk");           for (j=1;j<=nlstate+ndeath;j++){
     strcat(fileresilk,fileres);            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {            savm[ii][j]=(ii==j ? 1.0 : 0.0);
       printf("Problem with resultfile: %s\n", fileresilk);          }
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);        for(d=0; d<dh[mi][i]; d++){
     }          newm=savm;
     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");          for (kk=1; kk<=cptcovage;kk++) {
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     for(k=1; k<=nlstate; k++)           }
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   }          savm=oldm;
           oldm=newm;
   *fretone=(*funcone)(p);        } /* end mult */
   if(*globpri !=0){       
     fclose(ficresilk);        s1=s[mw[mi][i]][i];
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));        s2=s[mw[mi+1][i]][i];
     fflush(fichtm);         bbh=(double)bh[mi][i]/(double)stepm;
   }         /* bias is positive if real duration
   return;         * is higher than the multiple of stepm and negative otherwise.
 }         */
         if( s2 > nlstate && (mle <5) ){  /* Jackson */
           lli=log(out[s1][s2] - savm[s1][s2]);
 /*********** Maximum Likelihood Estimation ***************/        } else if  (s2==-2) {
           for (j=1,survp=0. ; j<=nlstate; j++)
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 {          lli= log(survp);
   int i,j, iter;        }else if (mle==1){
   double **xi;          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
   double fret;        } else if(mle==2){
   double fretone; /* Only one call to likelihood */          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 */
   /*  char filerespow[FILENAMELENGTH];*/        } else if(mle==3){  /* exponential inter-extrapolation */
   xi=matrix(1,npar,1,npar);          lli= (savm[s1][s2]>(double)1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
   for (i=1;i<=npar;i++)        } else if (mle==4){  /* mle=4 no inter-extrapolation */
     for (j=1;j<=npar;j++)          lli=log(out[s1][s2]); /* Original formula */
       xi[i][j]=(i==j ? 1.0 : 0.0);        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
   printf("Powell\n");  fprintf(ficlog,"Powell\n");          lli=log(out[s1][s2]); /* Original formula */
   strcpy(filerespow,"pow");         } /* End of if */
   strcat(filerespow,fileres);        ipmx +=1;
   if((ficrespow=fopen(filerespow,"w"))==NULL) {        sw += weight[i];
     printf("Problem with resultfile: %s\n", filerespow);        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);  /*       printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
   }        if(globpr){
   fprintf(ficrespow,"# Powell\n# iter -2*LL");          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
   for (i=1;i<=nlstate;i++)   %11.6f %11.6f %11.6f ", \
     for(j=1;j<=nlstate+ndeath;j++)                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);                  2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
   fprintf(ficrespow,"\n");          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
             llt +=ll[k]*gipmx/gsw;
   powell(p,xi,npar,ftol,&iter,&fret,func);            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
           }
   fclose(ficrespow);          fprintf(ficresilk," %10.6f\n", -llt);
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));        }
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));      } /* end of wave */
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));    } /* end of individual */
     for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 }    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 /**** Computes Hessian and covariance matrix ***/    if(globpr==0){ /* First time we count the contributions and weights */
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))      gipmx=ipmx;
 {      gsw=sw;
   double  **a,**y,*x,pd;    }
   double **hess;    return -l;
   int i, j,jk;  }
   int *indx;  
   
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);  /*************** function likelione ***********/
   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
   void lubksb(double **a, int npar, int *indx, double b[]) ;  {
   void ludcmp(double **a, int npar, int *indx, double *d) ;    /* This routine should help understanding what is done with
   double gompertz(double p[]);       the selection of individuals/waves and
   hess=matrix(1,npar,1,npar);       to check the exact contribution to the likelihood.
        Plotting could be done.
   printf("\nCalculation of the hessian matrix. Wait...\n");     */
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");    int k;
   for (i=1;i<=npar;i++){  
     printf("%d",i);fflush(stdout);    if(*globpri !=0){ /* Just counts and sums, no printings */
     fprintf(ficlog,"%d",i);fflush(ficlog);      strcpy(fileresilk,"ilk");
          strcat(fileresilk,fileres);
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
             printf("Problem with resultfile: %s\n", fileresilk);
     /*  printf(" %f ",p[i]);        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[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");
         fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
   for (i=1;i<=npar;i++) {      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
     for (j=1;j<=npar;j++)  {      for(k=1; k<=nlstate; k++)
       if (j>i) {         fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
         printf(".%d%d",i,j);fflush(stdout);      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);    }
         hess[i][j]=hessij(p,delti,i,j,func,npar);  
             *fretone=(*funcone)(p);
         hess[j][i]=hess[i][j];        if(*globpri !=0){
         /*printf(" %lf ",hess[i][j]);*/      fclose(ficresilk);
       }      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
     }      fflush(fichtm);
   }    }
   printf("\n");    return;
   fprintf(ficlog,"\n");  }
   
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");  
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");  /*********** Maximum Likelihood Estimation ***************/
     
   a=matrix(1,npar,1,npar);  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   y=matrix(1,npar,1,npar);  {
   x=vector(1,npar);    int i,j, iter;
   indx=ivector(1,npar);    double **xi;
   for (i=1;i<=npar;i++)    double fret;
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];    double fretone; /* Only one call to likelihood */
   ludcmp(a,npar,indx,&pd);    /*  char filerespow[FILENAMELENGTH];*/
     xi=matrix(1,npar,1,npar);
   for (j=1;j<=npar;j++) {    for (i=1;i<=npar;i++)
     for (i=1;i<=npar;i++) x[i]=0;      for (j=1;j<=npar;j++)
     x[j]=1;        xi[i][j]=(i==j ? 1.0 : 0.0);
     lubksb(a,npar,indx,x);    printf("Powell\n");  fprintf(ficlog,"Powell\n");
     for (i=1;i<=npar;i++){     strcpy(filerespow,"pow");
       matcov[i][j]=x[i];    strcat(filerespow,fileres);
     }    if((ficrespow=fopen(filerespow,"w"))==NULL) {
   }      printf("Problem with resultfile: %s\n", filerespow);
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
   printf("\n#Hessian matrix#\n");    }
   fprintf(ficlog,"\n#Hessian matrix#\n");    fprintf(ficrespow,"# Powell\n# iter -2*LL");
   for (i=1;i<=npar;i++) {     for (i=1;i<=nlstate;i++)
     for (j=1;j<=npar;j++) {       for(j=1;j<=nlstate+ndeath;j++)
       printf("%.3e ",hess[i][j]);        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
       fprintf(ficlog,"%.3e ",hess[i][j]);    fprintf(ficrespow,"\n");
     }  
     printf("\n");    powell(p,xi,npar,ftol,&iter,&fret,func);
     fprintf(ficlog,"\n");  
   }    free_matrix(xi,1,npar,1,npar);
     fclose(ficrespow);
   /* Recompute Inverse */    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
   for (i=1;i<=npar;i++)    fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];    fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
   ludcmp(a,npar,indx,&pd);  
   }
   /*  printf("\n#Hessian matrix recomputed#\n");  
   /**** Computes Hessian and covariance matrix ***/
   for (j=1;j<=npar;j++) {  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
     for (i=1;i<=npar;i++) x[i]=0;  {
     x[j]=1;    double  **a,**y,*x,pd;
     lubksb(a,npar,indx,x);    double **hess;
     for (i=1;i<=npar;i++){     int i, j,jk;
       y[i][j]=x[i];    int *indx;
       printf("%.3e ",y[i][j]);  
       fprintf(ficlog,"%.3e ",y[i][j]);    double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
     }    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
     printf("\n");    void lubksb(double **a, int npar, int *indx, double b[]) ;
     fprintf(ficlog,"\n");    void ludcmp(double **a, int npar, int *indx, double *d) ;
   }    double gompertz(double p[]);
   */    hess=matrix(1,npar,1,npar);
   
   free_matrix(a,1,npar,1,npar);    printf("\nCalculation of the hessian matrix. Wait...\n");
   free_matrix(y,1,npar,1,npar);    fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
   free_vector(x,1,npar);    for (i=1;i<=npar;i++){
   free_ivector(indx,1,npar);      printf("%d",i);fflush(stdout);
   free_matrix(hess,1,npar,1,npar);      fprintf(ficlog,"%d",i);fflush(ficlog);
      
        hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 }     
       /*  printf(" %f ",p[i]);
 /*************** hessian matrix ****************/          printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)    }
 {   
   int i;    for (i=1;i<=npar;i++) {
   int l=1, lmax=20;      for (j=1;j<=npar;j++)  {
   double k1,k2;        if (j>i) {
   double p2[NPARMAX+1];          printf(".%d%d",i,j);fflush(stdout);
   double res;          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;          hess[i][j]=hessij(p,delti,i,j,func,npar);
   double fx;         
   int k=0,kmax=10;          hess[j][i]=hess[i][j];    
   double l1;          /*printf(" %lf ",hess[i][j]);*/
         }
   fx=func(x);      }
   for (i=1;i<=npar;i++) p2[i]=x[i];    }
   for(l=0 ; l <=lmax; l++){    printf("\n");
     l1=pow(10,l);    fprintf(ficlog,"\n");
     delts=delt;  
     for(k=1 ; k <kmax; k=k+1){    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
       delt = delta*(l1*k);    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
       p2[theta]=x[theta] +delt;   
       k1=func(p2)-fx;    a=matrix(1,npar,1,npar);
       p2[theta]=x[theta]-delt;    y=matrix(1,npar,1,npar);
       k2=func(p2)-fx;    x=vector(1,npar);
       /*res= (k1-2.0*fx+k2)/delt/delt; */    indx=ivector(1,npar);
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */    for (i=1;i<=npar;i++)
             for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 #ifdef DEBUG    ludcmp(a,npar,indx,&pd);
       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);    for (j=1;j<=npar;j++) {
 #endif      for (i=1;i<=npar;i++) x[i]=0;
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */      x[j]=1;
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){      lubksb(a,npar,indx,x);
         k=kmax;      for (i=1;i<=npar;i++){
       }        matcov[i][j]=x[i];
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */      }
         k=kmax; l=lmax*10.;    }
       }  
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){     printf("\n#Hessian matrix#\n");
         delts=delt;    fprintf(ficlog,"\n#Hessian matrix#\n");
       }    for (i=1;i<=npar;i++) {
     }      for (j=1;j<=npar;j++) {
   }        printf("%.3e ",hess[i][j]);
   delti[theta]=delts;        fprintf(ficlog,"%.3e ",hess[i][j]);
   return res;       }
         printf("\n");
 }      fprintf(ficlog,"\n");
     }
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)  
 {    /* Recompute Inverse */
   int i;    for (i=1;i<=npar;i++)
   int l=1, l1, lmax=20;      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
   double k1,k2,k3,k4,res,fx;    ludcmp(a,npar,indx,&pd);
   double p2[NPARMAX+1];  
   int k;    /*  printf("\n#Hessian matrix recomputed#\n");
   
   fx=func(x);    for (j=1;j<=npar;j++) {
   for (k=1; k<=2; k++) {      for (i=1;i<=npar;i++) x[i]=0;
     for (i=1;i<=npar;i++) p2[i]=x[i];      x[j]=1;
     p2[thetai]=x[thetai]+delti[thetai]/k;      lubksb(a,npar,indx,x);
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;      for (i=1;i<=npar;i++){
     k1=func(p2)-fx;        y[i][j]=x[i];
           printf("%.3e ",y[i][j]);
     p2[thetai]=x[thetai]+delti[thetai]/k;        fprintf(ficlog,"%.3e ",y[i][j]);
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;      }
     k2=func(p2)-fx;      printf("\n");
         fprintf(ficlog,"\n");
     p2[thetai]=x[thetai]-delti[thetai]/k;    }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    */
     k3=func(p2)-fx;  
       free_matrix(a,1,npar,1,npar);
     p2[thetai]=x[thetai]-delti[thetai]/k;    free_matrix(y,1,npar,1,npar);
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    free_vector(x,1,npar);
     k4=func(p2)-fx;    free_ivector(indx,1,npar);
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */    free_matrix(hess,1,npar,1,npar);
 #ifdef DEBUG  
     printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);  
     fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);  }
 #endif  
   }  /*************** hessian matrix ****************/
   return res;  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 }  {
     int i;
 /************** Inverse of matrix **************/    int l=1, lmax=20;
 void ludcmp(double **a, int n, int *indx, double *d)     double k1,k2;
 {     double p2[NPARMAX+1];
   int i,imax,j,k;     double res;
   double big,dum,sum,temp;     double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
   double *vv;     double fx;
      int k=0,kmax=10;
   vv=vector(1,n);     double l1;
   *d=1.0;   
   for (i=1;i<=n;i++) {     fx=func(x);
     big=0.0;     for (i=1;i<=npar;i++) p2[i]=x[i];
     for (j=1;j<=n;j++)     for(l=0 ; l <=lmax; l++){
       if ((temp=fabs(a[i][j])) > big) big=temp;       l1=pow(10,l);
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");       delts=delt;
     vv[i]=1.0/big;       for(k=1 ; k <kmax; k=k+1){
   }         delt = delta*(l1*k);
   for (j=1;j<=n;j++) {         p2[theta]=x[theta] +delt;
     for (i=1;i<j;i++) {         k1=func(p2)-fx;
       sum=a[i][j];         p2[theta]=x[theta]-delt;
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];         k2=func(p2)-fx;
       a[i][j]=sum;         /*res= (k1-2.0*fx+k2)/delt/delt; */
     }         res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
     big=0.0;        
     for (i=j;i<=n;i++) {   #ifdef DEBUG
       sum=a[i][j];         printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
       for (k=1;k<j;k++)         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);
         sum -= a[i][k]*a[k][j];   #endif
       a[i][j]=sum;         /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
       if ( (dum=vv[i]*fabs(sum)) >= big) {         if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
         big=dum;           k=kmax;
         imax=i;         }
       }         else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
     }           k=kmax; l=lmax*10.;
     if (j != imax) {         }
       for (k=1;k<=n;k++) {         else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
         dum=a[imax][k];           delts=delt;
         a[imax][k]=a[j][k];         }
         a[j][k]=dum;       }
       }     }
       *d = -(*d);     delti[theta]=delts;
       vv[imax]=vv[j];     return res;
     }    
     indx[j]=imax;   }
     if (a[j][j] == 0.0) a[j][j]=TINY;   
     if (j != n) {   double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
       dum=1.0/(a[j][j]);   {
       for (i=j+1;i<=n;i++) a[i][j] *= dum;     int i;
     }     int l=1, l1, lmax=20;
   }     double k1,k2,k3,k4,res,fx;
   free_vector(vv,1,n);  /* Doesn't work */    double p2[NPARMAX+1];
 ;    int k;
 }   
     fx=func(x);
 void lubksb(double **a, int n, int *indx, double b[])     for (k=1; k<=2; k++) {
 {       for (i=1;i<=npar;i++) p2[i]=x[i];
   int i,ii=0,ip,j;       p2[thetai]=x[thetai]+delti[thetai]/k;
   double sum;       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
        k1=func(p2)-fx;
   for (i=1;i<=n;i++) {    
     ip=indx[i];       p2[thetai]=x[thetai]+delti[thetai]/k;
     sum=b[ip];       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
     b[ip]=b[i];       k2=func(p2)-fx;
     if (ii)    
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];       p2[thetai]=x[thetai]-delti[thetai]/k;
     else if (sum) ii=i;       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
     b[i]=sum;       k3=func(p2)-fx;
   }    
   for (i=n;i>=1;i--) {       p2[thetai]=x[thetai]-delti[thetai]/k;
     sum=b[i];       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];       k4=func(p2)-fx;
     b[i]=sum/a[i][i];       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
   }   #ifdef DEBUG
 }       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
       fprintf(ficlog,"%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);
 /************ Frequencies ********************/  #endif
 void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])    }
 {  /* Some frequencies */    return res;
     }
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;  
   int first;  /************** Inverse of matrix **************/
   double ***freq; /* Frequencies */  void ludcmp(double **a, int n, int *indx, double *d)
   double *pp, **prop;  {
   double pos,posprop, k2, dateintsum=0,k2cpt=0;    int i,imax,j,k;
   FILE *ficresp;    double big,dum,sum,temp;
   char fileresp[FILENAMELENGTH];    double *vv;
      
   pp=vector(1,nlstate);    vv=vector(1,n);
   prop=matrix(1,nlstate,iagemin,iagemax+3);    *d=1.0;
   strcpy(fileresp,"p");    for (i=1;i<=n;i++) {
   strcat(fileresp,fileres);      big=0.0;
   if((ficresp=fopen(fileresp,"w"))==NULL) {      for (j=1;j<=n;j++)
     printf("Problem with prevalence resultfile: %s\n", fileresp);        if ((temp=fabs(a[i][j])) > big) big=temp;
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);      if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
     exit(0);      vv[i]=1.0/big;
   }    }
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);    for (j=1;j<=n;j++) {
   j1=0;      for (i=1;i<j;i++) {
           sum=a[i][j];
   j=cptcoveff;        for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
   if (cptcovn<1) {j=1;ncodemax[1]=1;}        a[i][j]=sum;
       }
   first=1;      big=0.0;
       for (i=j;i<=n;i++) {
   for(k1=1; k1<=j;k1++){        sum=a[i][j];
     for(i1=1; i1<=ncodemax[k1];i1++){        for (k=1;k<j;k++)
       j1++;          sum -= a[i][k]*a[k][j];
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);        a[i][j]=sum;
         scanf("%d", i);*/        if ( (dum=vv[i]*fabs(sum)) >= big) {
       for (i=-5; i<=nlstate+ndeath; i++)            big=dum;
         for (jk=-5; jk<=nlstate+ndeath; jk++)            imax=i;
           for(m=iagemin; m <= iagemax+3; m++)        }
             freq[i][jk][m]=0;      }
       if (j != imax) {
     for (i=1; i<=nlstate; i++)          for (k=1;k<=n;k++) {
       for(m=iagemin; m <= iagemax+3; m++)          dum=a[imax][k];
         prop[i][m]=0;          a[imax][k]=a[j][k];
                 a[j][k]=dum;
       dateintsum=0;        }
       k2cpt=0;        *d = -(*d);
       for (i=1; i<=imx; i++) {        vv[imax]=vv[j];
         bool=1;      }
         if  (cptcovn>0) {      indx[j]=imax;
           for (z1=1; z1<=cptcoveff; z1++)       if (a[j][j] == 0.0) a[j][j]=TINY;
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])       if (j != n) {
               bool=0;        dum=1.0/(a[j][j]);
         }        for (i=j+1;i<=n;i++) a[i][j] *= dum;
         if (bool==1){      }
           for(m=firstpass; m<=lastpass; m++){    }
             k2=anint[m][i]+(mint[m][i]/12.);    free_vector(vv,1,n);  /* Doesn't work */
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/  ;
               if(agev[m][i]==0) agev[m][i]=iagemax+1;  }
               if(agev[m][i]==1) agev[m][i]=iagemax+2;  
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];  void lubksb(double **a, int n, int *indx, double b[])
               if (m<lastpass) {  {
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];    int i,ii=0,ip,j;
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];    double sum;
               }   
                   for (i=1;i<=n;i++) {
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {      ip=indx[i];
                 dateintsum=dateintsum+k2;      sum=b[ip];
                 k2cpt++;      b[ip]=b[i];
               }      if (ii)
               /*}*/        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
           }      else if (sum) ii=i;
         }      b[i]=sum;
       }    }
            for (i=n;i>=1;i--) {
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/      sum=b[i];
 fprintf(ficresp, "#Local time at start: %s", strstart);      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
       if  (cptcovn>0) {      b[i]=sum/a[i][i];
         fprintf(ficresp, "\n#********** Variable ");     }
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);  }
         fprintf(ficresp, "**********\n#");  
       }  void pstamp(FILE *fichier)
       for(i=1; i<=nlstate;i++)   {
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
       fprintf(ficresp, "\n");  }
         
       for(i=iagemin; i <= iagemax+3; i++){  /************ Frequencies ********************/
         if(i==iagemax+3){  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[])
           fprintf(ficlog,"Total");  {  /* Some frequencies */
         }else{   
           if(first==1){    int i, m, jk, k1,i1, j1, bool, z1,z2,j;
             first=0;    int first;
             printf("See log file for details...\n");    double ***freq; /* Frequencies */
           }    double *pp, **prop;
           fprintf(ficlog,"Age %d", i);    double pos,posprop, k2, dateintsum=0,k2cpt=0;
         }    char fileresp[FILENAMELENGTH];
         for(jk=1; jk <=nlstate ; jk++){   
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)    pp=vector(1,nlstate);
             pp[jk] += freq[jk][m][i];     prop=matrix(1,nlstate,iagemin,iagemax+3);
         }    strcpy(fileresp,"p");
         for(jk=1; jk <=nlstate ; jk++){    strcat(fileresp,fileres);
           for(m=-1, pos=0; m <=0 ; m++)    if((ficresp=fopen(fileresp,"w"))==NULL) {
             pos += freq[jk][m][i];      printf("Problem with prevalence resultfile: %s\n", fileresp);
           if(pp[jk]>=1.e-10){      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
             if(first==1){      exit(0);
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);    }
             }    freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);    j1=0;
           }else{   
             if(first==1)    j=cptcoveff;
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);    if (cptcovn<1) {j=1;ncodemax[1]=1;}
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);  
           }    first=1;
         }  
     for(k1=1; k1<=j;k1++){
         for(jk=1; jk <=nlstate ; jk++){      for(i1=1; i1<=ncodemax[k1];i1++){
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)        j1++;
             pp[jk] += freq[jk][m][i];        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
         }                 scanf("%d", i);*/
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){        for (i=-5; i<=nlstate+ndeath; i++)  
           pos += pp[jk];          for (jk=-5; jk<=nlstate+ndeath; jk++)  
           posprop += prop[jk][i];            for(m=iagemin; m <= iagemax+3; m++)
         }              freq[i][jk][m]=0;
         for(jk=1; jk <=nlstate ; jk++){  
           if(pos>=1.e-5){      for (i=1; i<=nlstate; i++)  
             if(first==1)        for(m=iagemin; m <= iagemax+3; m++)
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);          prop[i][m]=0;
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);       
           }else{        dateintsum=0;
             if(first==1)        k2cpt=0;
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);        for (i=1; i<=imx; i++) {
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);          bool=1;
           }          if  (cptcovn>0) {
           if( i <= iagemax){            for (z1=1; z1<=cptcoveff; z1++)
             if(pos>=1.e-5){              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);                bool=0;
               /*probs[i][jk][j1]= pp[jk]/pos;*/          }
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/          if (bool==1){
             }            for(m=firstpass; m<=lastpass; m++){
             else              k2=anint[m][i]+(mint[m][i]/12.);
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
           }                if(agev[m][i]==0) agev[m][i]=iagemax+1;
         }                if(agev[m][i]==1) agev[m][i]=iagemax+2;
                         if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
         for(jk=-1; jk <=nlstate+ndeath; jk++)                if (m<lastpass) {
           for(m=-1; m <=nlstate+ndeath; m++)                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
             if(freq[jk][m][i] !=0 ) {                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
             if(first==1)                }
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);               
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
             }                  dateintsum=dateintsum+k2;
         if(i <= iagemax)                  k2cpt++;
           fprintf(ficresp,"\n");                }
         if(first==1)                /*}*/
           printf("Others in log...\n");            }
         fprintf(ficlog,"\n");          }
       }        }
     }         
   }        /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
   dateintmean=dateintsum/k2cpt;         pstamp(ficresp);
          if  (cptcovn>0) {
   fclose(ficresp);          fprintf(ficresp, "\n#********** Variable ");
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
   free_vector(pp,1,nlstate);          fprintf(ficresp, "**********\n#");
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);        }
   /* End of Freq */        for(i=1; i<=nlstate;i++)
 }          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
         fprintf(ficresp, "\n");
 /************ Prevalence ********************/       
 void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)        for(i=iagemin; i <= iagemax+3; i++){
 {            if(i==iagemax+3){
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people            fprintf(ficlog,"Total");
      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(first==1){
   */              first=0;
                printf("See log file for details...\n");
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;            }
   double ***freq; /* Frequencies */            fprintf(ficlog,"Age %d", i);
   double *pp, **prop;          }
   double pos,posprop;           for(jk=1; jk <=nlstate ; jk++){
   double  y2; /* in fractional years */            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
   int iagemin, iagemax;              pp[jk] += freq[jk][m][i];
           }
   iagemin= (int) agemin;          for(jk=1; jk <=nlstate ; jk++){
   iagemax= (int) agemax;            for(m=-1, pos=0; m <=0 ; m++)
   /*pp=vector(1,nlstate);*/              pos += freq[jk][m][i];
   prop=matrix(1,nlstate,iagemin,iagemax+3);             if(pp[jk]>=1.e-10){
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/              if(first==1){
   j1=0;              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                 }
   j=cptcoveff;              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}            }else{
                 if(first==1)
   for(k1=1; k1<=j;k1++){                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
     for(i1=1; i1<=ncodemax[k1];i1++){              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
       j1++;            }
                 }
       for (i=1; i<=nlstate; i++)    
         for(m=iagemin; m <= iagemax+3; m++)          for(jk=1; jk <=nlstate ; jk++){
           prop[i][m]=0.0;            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                    pp[jk] += freq[jk][m][i];
       for (i=1; i<=imx; i++) { /* Each individual */          }      
         bool=1;          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
         if  (cptcovn>0) {            pos += pp[jk];
           for (z1=1; z1<=cptcoveff; z1++)             posprop += prop[jk][i];
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])           }
               bool=0;          for(jk=1; jk <=nlstate ; jk++){
         }             if(pos>=1.e-5){
         if (bool==1) {               if(first==1)
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */            }else{
               if(agev[m][i]==0) agev[m][i]=iagemax+1;              if(first==1)
               if(agev[m][i]==1) agev[m][i]=iagemax+2;                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
               if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m);               fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
               if (s[m][i]>0 && s[m][i]<=nlstate) {             }
                 /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/            if( i <= iagemax){
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];              if(pos>=1.e-5){
                 prop[s[m][i]][iagemax+3] += weight[i];                 fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
               }                 /*probs[i][jk][j1]= pp[jk]/pos;*/
             }                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
           } /* end selection of waves */              }
         }              else
       }                fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
       for(i=iagemin; i <= iagemax+3; i++){              }
                   }
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {          
           posprop += prop[jk][i];           for(jk=-1; jk <=nlstate+ndeath; jk++)
         }             for(m=-1; m <=nlstate+ndeath; m++)
               if(freq[jk][m][i] !=0 ) {
         for(jk=1; jk <=nlstate ; jk++){                   if(first==1)
           if( i <=  iagemax){                 printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
             if(posprop>=1.e-5){                 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
               probs[i][jk][j1]= prop[jk][i]/posprop;              }
             }           if(i <= iagemax)
           }             fprintf(ficresp,"\n");
         }/* end jk */           if(first==1)
       }/* end i */             printf("Others in log...\n");
     } /* end i1 */          fprintf(ficlog,"\n");
   } /* end k1 */        }
         }
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/    }
   /*free_vector(pp,1,nlstate);*/    dateintmean=dateintsum/k2cpt;
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);   
 }  /* End of prevalence */    fclose(ficresp);
     free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 /************* Waves Concatenation ***************/    free_vector(pp,1,nlstate);
     free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 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)    /* End of Freq */
 {  }
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.  
      Death is a valid wave (if date is known).  /************ Prevalence ********************/
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual 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)
      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.    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
      */       in each health status at the date of interview (if between dateprev1 and dateprev2).
        We still use firstpass and lastpass as another selection.
   int i, mi, m;    */
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;   
      double sum=0., jmean=0.;*/    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
   int first;    double ***freq; /* Frequencies */
   int j, k=0,jk, ju, jl;    double *pp, **prop;
   double sum=0.;    double pos,posprop;
   first=0;    double  y2; /* in fractional years */
   jmin=1e+5;    int iagemin, iagemax;
   jmax=-1;  
   jmean=0.;    iagemin= (int) agemin;
   for(i=1; i<=imx; i++){    iagemax= (int) agemax;
     mi=0;    /*pp=vector(1,nlstate);*/
     m=firstpass;    prop=matrix(1,nlstate,iagemin,iagemax+3);
     while(s[m][i] <= nlstate){    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)    j1=0;
         mw[++mi][i]=m;   
       if(m >=lastpass)    j=cptcoveff;
         break;    if (cptcovn<1) {j=1;ncodemax[1]=1;}
       else   
         m++;    for(k1=1; k1<=j;k1++){
     }/* end while */      for(i1=1; i1<=ncodemax[k1];i1++){
     if (s[m][i] > nlstate){        j1++;
       mi++;     /* Death is another wave */       
       /* if(mi==0)  never been interviewed correctly before death */        for (i=1; i<=nlstate; i++)  
          /* Only death is a correct wave */          for(m=iagemin; m <= iagemax+3; m++)
       mw[mi][i]=m;            prop[i][m]=0.0;
     }       
         for (i=1; i<=imx; i++) { /* Each individual */
     wav[i]=mi;          bool=1;
     if(mi==0){          if  (cptcovn>0) {
       nbwarn++;            for (z1=1; z1<=cptcoveff; z1++)
       if(first==0){              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
         printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);                bool=0;
         first=1;          }
       }          if (bool==1) {
       if(first==1){            for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
         fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);              y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
       }              if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
     } /* end mi==0 */                if(agev[m][i]==0) agev[m][i]=iagemax+1;
   } /* End individuals */                if(agev[m][i]==1) agev[m][i]=iagemax+2;
                 if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m);
   for(i=1; i<=imx; i++){                if (s[m][i]>0 && s[m][i]<=nlstate) {
     for(mi=1; mi<wav[i];mi++){                  /*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 (stepm <=0)                  prop[s[m][i]][(int)agev[m][i]] += weight[i];
         dh[mi][i]=1;                  prop[s[m][i]][iagemax+3] += weight[i];
       else{                }
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */              }
           if (agedc[i] < 2*AGESUP) {            } /* end selection of waves */
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);           }
             if(j==0) j=1;  /* Survives at least one month after exam */        }
             else if(j<0){        for(i=iagemin; i <= iagemax+3; i++){  
               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]);          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
               j=1; /* Temporary Dangerous patch */            posprop += prop[jk][i];
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);          }
               fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);  
               fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);          for(jk=1; jk <=nlstate ; jk++){    
             }            if( i <=  iagemax){
             k=k+1;              if(posprop>=1.e-5){
             if (j >= jmax){                probs[i][jk][j1]= prop[jk][i]/posprop;
               jmax=j;              }
               ijmax=i;            }
             }          }/* end jk */
             if (j <= jmin){        }/* end i */
               jmin=j;      } /* end i1 */
               ijmin=i;    } /* end k1 */
             }   
             sum=sum+j;    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/    /*free_vector(pp,1,nlstate);*/
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
           }  }  /* End of prevalence */
         }  
         else{  /************* Waves Concatenation ***************/
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));  
 /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */  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)
   {
           k=k+1;    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
           if (j >= jmax) {       Death is a valid wave (if date is known).
             jmax=j;       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
             ijmax=i;       dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
           }       and mw[mi+1][i]. dh depends on stepm.
           else if (j <= jmin){       */
             jmin=j;  
             ijmin=i;    int i, mi, m;
           }    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */       double sum=0., jmean=0.;*/
           /*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]);*/    int first;
           if(j<0){    int j, k=0,jk, ju, jl;
             nberr++;    double sum=0.;
             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]);    first=0;
             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]);    jmin=1e+5;
           }    jmax=-1;
           sum=sum+j;    jmean=0.;
         }    for(i=1; i<=imx; i++){
         jk= j/stepm;      mi=0;
         jl= j -jk*stepm;      m=firstpass;
         ju= j -(jk+1)*stepm;      while(s[m][i] <= nlstate){
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
           if(jl==0){          mw[++mi][i]=m;
             dh[mi][i]=jk;        if(m >=lastpass)
             bh[mi][i]=0;          break;
           }else{ /* We want a negative bias in order to only have interpolation ie        else
                   * at the price of an extra matrix product in likelihood */          m++;
             dh[mi][i]=jk+1;      }/* end while */
             bh[mi][i]=ju;      if (s[m][i] > nlstate){
           }        mi++;     /* Death is another wave */
         }else{        /* if(mi==0)  never been interviewed correctly before death */
           if(jl <= -ju){           /* Only death is a correct wave */
             dh[mi][i]=jk;        mw[mi][i]=m;
             bh[mi][i]=jl;       /* bias is positive if real duration      }
                                  * is higher than the multiple of stepm and negative otherwise.  
                                  */      wav[i]=mi;
           }      if(mi==0){
           else{        nbwarn++;
             dh[mi][i]=jk+1;        if(first==0){
             bh[mi][i]=ju;          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
           }          first=1;
           if(dh[mi][i]==0){        }
             dh[mi][i]=1; /* At least one step */        if(first==1){
             bh[mi][i]=ju; /* At least one step */          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
             /*  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 mi==0 */
         } /* end if mle */    } /* End individuals */
       }  
     } /* end wave */    for(i=1; i<=imx; i++){
   }      for(mi=1; mi<wav[i];mi++){
   jmean=sum/k;        if (stepm <=0)
   printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);          dh[mi][i]=1;
   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);        else{
  }          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
             if (agedc[i] < 2*AGESUP) {
 /*********** Tricode ****************************/              j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
 void tricode(int *Tvar, int **nbcode, int imx)              if(j==0) j=1;  /* Survives at least one month after exam */
 {              else if(j<0){
                   nberr++;
   int Ndum[20],ij=1, k, j, i, maxncov=19;                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]);
   int cptcode=0;                j=1; /* Temporary Dangerous patch */
   cptcoveff=0;                 printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
                  fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
   for (k=0; k<maxncov; k++) Ndum[k]=0;                fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
   for (k=1; k<=7; k++) ncodemax[k]=0;              }
               k=k+1;
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {              if (j >= jmax){
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum                 jmax=j;
                                modality*/                 ijmax=i;
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/              }
       Ndum[ij]++; /*store the modality */              if (j <= jmin){
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/                jmin=j;
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable                 ijmin=i;
                                        Tvar[j]. If V=sex and male is 0 and               }
                                        female is 1, then  cptcode=1.*/              sum=sum+j;
     }              /*if (j<0) printf("j=%d num=%d \n",j,i);*/
               /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
     for (i=0; i<=cptcode; i++) {            }
       if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */          }
     }          else{
             j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
     ij=1;   /*        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<=ncodemax[j]; i++) {  
       for (k=0; k<= maxncov; k++) {            k=k+1;
         if (Ndum[k] != 0) {            if (j >= jmax) {
           nbcode[Tvar[j]][ij]=k;               jmax=j;
           /* 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; */              ijmax=i;
                       }
           ij++;            else if (j <= jmin){
         }              jmin=j;
         if (ij > ncodemax[j]) break;               ijmin=i;
       }              }
     }             /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
   }              /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
             if(j<0){
  for (k=0; k< maxncov; k++) Ndum[k]=0;              nberr++;
               printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
  for (i=1; i<=ncovmodel-2; i++) {               fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/            }
    ij=Tvar[i];            sum=sum+j;
    Ndum[ij]++;          }
  }          jk= j/stepm;
           jl= j -jk*stepm;
  ij=1;          ju= j -(jk+1)*stepm;
  for (i=1; i<= maxncov; i++) {          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
    if((Ndum[i]!=0) && (i<=ncovcol)){            if(jl==0){
      Tvaraff[ij]=i; /*For printing */              dh[mi][i]=jk;
      ij++;              bh[mi][i]=0;
    }            }else{ /* We want a negative bias in order to only have interpolation ie
  }                    * at the price of an extra matrix product in likelihood */
                dh[mi][i]=jk+1;
  cptcoveff=ij-1; /*Number of simple covariates*/              bh[mi][i]=ju;
 }            }
           }else{
 /*********** Health Expectancies ****************/            if(jl <= -ju){
               dh[mi][i]=jk;
 void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int ij, int estepm,double delti[],double **matcov,char strstart[] )              bh[mi][i]=jl;       /* bias is positive if real duration
                                    * is higher than the multiple of stepm and negative otherwise.
 {                                   */
   /* Health expectancies */            }
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj;            else{
   double age, agelim, hf;              dh[mi][i]=jk+1;
   double ***p3mat,***varhe;              bh[mi][i]=ju;
   double **dnewm,**doldm;            }
   double *xp;            if(dh[mi][i]==0){
   double **gp, **gm;              dh[mi][i]=1; /* At least one step */
   double ***gradg, ***trgradg;              bh[mi][i]=ju; /* At least one step */
   int theta;              /*  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);*/
             }
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);          } /* end if mle */
   xp=vector(1,npar);        }
   dnewm=matrix(1,nlstate*nlstate,1,npar);      } /* end wave */
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);    }
       jmean=sum/k;
   fprintf(ficreseij,"# Local time at start: %s", strstart);    printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);
   fprintf(ficreseij,"# Health expectancies\n");    fprintf(ficlog,"Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, ijmin, jmax, ijmax, jmean);
   fprintf(ficreseij,"# Age");   }
   for(i=1; i<=nlstate;i++)  
     for(j=1; j<=nlstate;j++)  /*********** Tricode ****************************/
       fprintf(ficreseij," %1d-%1d (SE)",i,j);  void tricode(int *Tvar, int **nbcode, int imx)
   fprintf(ficreseij,"\n");  {
    
   if(estepm < stepm){    int Ndum[20],ij=1, k, j, i, maxncov=19;
     printf ("Problem %d lower than %d\n",estepm, stepm);    int cptcode=0;
   }    cptcoveff=0;
   else  hstepm=estepm;      
   /* We compute the life expectancy from trapezoids spaced every estepm months    for (k=0; k<maxncov; k++) Ndum[k]=0;
    * This is mainly to measure the difference between two models: for example    for (k=1; k<=7; k++) ncodemax[k]=0;
    * if stepm=24 months pijx are given only every 2 years and by summing them  
    * we are calculating an estimate of the Life Expectancy assuming a linear     for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
    * progression in between and thus overestimating or underestimating according      for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
    * to the curvature of the survival function. If, for the same date, we                                  modality*/
    * estimate the model with stepm=1 month, we can keep estepm to 24 months        ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
    * to compare the new estimate of Life expectancy with the same linear         Ndum[ij]++; /*store the modality */
    * hypothesis. A more precise result, taking into account a more precise        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
    * curvature will be obtained if estepm is as small as stepm. */        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
                                          Tvar[j]. If V=sex and male is 0 and
   /* For example we decided to compute the life expectancy with the smallest unit */                                         female is 1, then  cptcode=1.*/
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.       }
      nhstepm is the number of hstepm from age to agelim   
      nstepm is the number of stepm from age to agelin.       for (i=0; i<=cptcode; i++) {
      Look at hpijx to understand the reason of that which relies in memory size        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 */
      and note for a fixed period like estepm months */      }
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the  
      survival function given by stepm (the optimization length). Unfortunately it      ij=1;
      means that if the survival funtion is printed only each two years of age and if      for (i=1; i<=ncodemax[j]; i++) {
      you sum them up and add 1 year (area under the trapezoids) you won't get the same         for (k=0; k<= maxncov; k++) {
      results. So we changed our mind and took the option of the best precision.          if (Ndum[k] != 0) {
   */            nbcode[Tvar[j]][ij]=k;
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */             /* 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; */
            
   agelim=AGESUP;            ij++;
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */          }
     /* nhstepm age range expressed in number of stepm */          if (ij > ncodemax[j]) break;
     nstepm=(int) rint((agelim-age)*YEARM/stepm);         }  
     /* Typically if 20 years nstepm = 20*12/6=40 stepm */       }
     /* if (stepm >= YEARM) hstepm=1;*/    }  
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */  
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   for (k=0; k< maxncov; k++) Ndum[k]=0;
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);  
     gp=matrix(0,nhstepm,1,nlstate*nlstate);   for (i=1; i<=ncovmodel-2; i++) {
     gm=matrix(0,nhstepm,1,nlstate*nlstate);     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
      ij=Tvar[i];
     /* Computed by stepm unit matrices, product of hstepm matrices, stored     Ndum[ij]++;
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */   }
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, ij);    
     ij=1;
    for (i=1; i<= maxncov; i++) {
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */     if((Ndum[i]!=0) && (i<=ncovcol)){
        Tvaraff[ij]=i; /*For printing */
     /* Computing  Variances of health expectancies */       ij++;
      }
      for(theta=1; theta <=npar; theta++){   }
       for(i=1; i<=npar; i++){    
         xp[i] = x[i] + (i==theta ?delti[theta]:0);   cptcoveff=ij-1; /*Number of simple covariates*/
       }  }
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);    
     /*********** Health Expectancies ****************/
       cptj=0;  
       for(j=1; j<= nlstate; j++){  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[] )
         for(i=1; i<=nlstate; i++){  
           cptj=cptj+1;  {
           for(h=0, gp[h][cptj]=0.; h<=nhstepm-1; h++){    /* Health expectancies, no variances */
             gp[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
           }    double age, agelim, hf;
         }    double ***p3mat;
       }    double eip;
        
          pstamp(ficreseij);
       for(i=1; i<=npar; i++)     fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    fprintf(ficreseij,"# Age");
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);      for(i=1; i<=nlstate;i++){
             for(j=1; j<=nlstate;j++){
       cptj=0;        fprintf(ficreseij," e%1d%1d ",i,j);
       for(j=1; j<= nlstate; j++){      }
         for(i=1;i<=nlstate;i++){      fprintf(ficreseij," e%1d. ",i);
           cptj=cptj+1;    }
           for(h=0, gm[h][cptj]=0.; h<=nhstepm-1; h++){    fprintf(ficreseij,"\n");
   
             gm[h][cptj] = (p3mat[i][j][h]+p3mat[i][j][h+1])/2.;   
           }    if(estepm < stepm){
         }      printf ("Problem %d lower than %d\n",estepm, stepm);
       }    }
       for(j=1; j<= nlstate*nlstate; j++)    else  hstepm=estepm;  
         for(h=0; h<=nhstepm-1; h++){    /* We compute the life expectancy from trapezoids spaced every estepm months
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];     * This is mainly to measure the difference between two models: for example
         }     * if stepm=24 months pijx are given only every 2 years and by summing them
      }      * we are calculating an estimate of the Life Expectancy assuming a linear
         * progression in between and thus overestimating or underestimating according
 /* End theta */     * to the curvature of the survival function. If, for the same date, we
      * estimate the model with stepm=1 month, we can keep estepm to 24 months
      trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);     * to compare the new estimate of Life expectancy with the same linear
      * hypothesis. A more precise result, taking into account a more precise
      for(h=0; h<=nhstepm-1; h++)     * curvature will be obtained if estepm is as small as stepm. */
       for(j=1; j<=nlstate*nlstate;j++)  
         for(theta=1; theta <=npar; theta++)    /* For example we decided to compute the life expectancy with the smallest unit */
           trgradg[h][j][theta]=gradg[h][theta][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
        nstepm is the number of stepm from age to agelin.
      for(i=1;i<=nlstate*nlstate;i++)       Look at hpijx to understand the reason of that which relies in memory size
       for(j=1;j<=nlstate*nlstate;j++)       and note for a fixed period like estepm months */
         varhe[i][j][(int)age] =0.;    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
        survival function given by stepm (the optimization length). Unfortunately it
      printf("%d|",(int)age);fflush(stdout);       means that if the survival funtion is printed only each two years of age and if
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);       you sum them up and add 1 year (area under the trapezoids) you won't get the same
      for(h=0;h<=nhstepm-1;h++){       results. So we changed our mind and took the option of the best precision.
       for(k=0;k<=nhstepm-1;k++){    */
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);  
         for(i=1;i<=nlstate*nlstate;i++)    agelim=AGESUP;
           for(j=1;j<=nlstate*nlstate;j++)    /* If stepm=6 months */
             varhe[i][j][(int)age] += doldm[i][j]*hf*hf;      /* Computed by stepm unit matrices, product of hstepm matrices, stored
       }         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
     }     
     /* Computing expectancies */  /* nhstepm age range expressed in number of stepm */
     for(i=1; i<=nlstate;i++)    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
       for(j=1; j<=nlstate;j++)    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){    /* if (stepm >= YEARM) hstepm=1;*/
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
               p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/  
     for (age=bage; age<=fage; age ++){
         }  
   
     fprintf(ficreseij,"%3.0f",age );      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
     cptj=0;     
     for(i=1; i<=nlstate;i++)      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       for(j=1; j<=nlstate;j++){     
         cptj++;      printf("%d|",(int)age);fflush(stdout);
         fprintf(ficreseij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[cptj][cptj][(int)age]) );      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
       }     
     fprintf(ficreseij,"\n");  
          /* Computing expectancies */
     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);          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);           
   }            /*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]);*/
   printf("\n");  
   fprintf(ficlog,"\n");          }
      
   free_vector(xp,1,npar);      fprintf(ficreseij,"%3.0f",age );
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);      for(i=1; i<=nlstate;i++){
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);        eip=0;
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);        for(j=1; j<=nlstate;j++){
 }          eip +=eij[i][j][(int)age];
           fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 /************ Variance ******************/        }
 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(ficreseij,"%9.4f", eip );
 {      }
   /* Variance of health expectancies */      fprintf(ficreseij,"\n");
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/     
   /* double **newm;*/    }
   double **dnewm,**doldm;    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double **dnewmp,**doldmp;    printf("\n");
   int i, j, nhstepm, hstepm, h, nstepm ;    fprintf(ficlog,"\n");
   int k, cptcode;   
   double *xp;  }
   double **gp, **gm;  /* for var eij */  
   double ***gradg, ***trgradg; /*for var eij */  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[] )
   double **gradgp, **trgradgp; /* for var p point j */  
   double *gpp, *gmp; /* for var p point j */  {
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */    /* Covariances of health expectancies eij and of total life expectancies according
   double ***p3mat;     to initial status i, ei. .
   double age,agelim, hf;    */
   double ***mobaverage;    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
   int theta;    double age, agelim, hf;
   char digit[4];    double ***p3matp, ***p3matm, ***varhe;
   char digitp[25];    double **dnewm,**doldm;
     double *xp, *xm;
   char fileresprobmorprev[FILENAMELENGTH];    double **gp, **gm;
     double ***gradg, ***trgradg;
   if(popbased==1){    int theta;
     if(mobilav!=0)  
       strcpy(digitp,"-populbased-mobilav-");    double eip, vip;
     else strcpy(digitp,"-populbased-nomobil-");  
   }    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
   else     xp=vector(1,npar);
     strcpy(digitp,"-stablbased-");    xm=vector(1,npar);
     dnewm=matrix(1,nlstate*nlstate,1,npar);
   if (mobilav!=0) {    doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);   
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){    pstamp(ficresstdeij);
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    fprintf(ficresstdeij,"# Age");
     }    for(i=1; i<=nlstate;i++){
   }      for(j=1; j<=nlstate;j++)
         fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
   strcpy(fileresprobmorprev,"prmorprev");       fprintf(ficresstdeij," e%1d. ",i);
   sprintf(digit,"%-d",ij);    }
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/    fprintf(ficresstdeij,"\n");
   strcat(fileresprobmorprev,digit); /* Tvar to be done */  
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */    pstamp(ficrescveij);
   strcat(fileresprobmorprev,fileres);    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {    fprintf(ficrescveij,"# Age");
     printf("Problem with resultfile: %s\n", fileresprobmorprev);    for(i=1; i<=nlstate;i++)
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);      for(j=1; j<=nlstate;j++){
   }        cptj= (j-1)*nlstate+i;
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);        for(i2=1; i2<=nlstate;i2++)
            for(j2=1; j2<=nlstate;j2++){
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);            cptj2= (j2-1)*nlstate+i2;
   fprintf(ficresprobmorprev, "#Local time at start: %s", strstart);            if(cptj2 <= cptj)
   fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);          }
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){      }
     fprintf(ficresprobmorprev," p.%-d SE",j);    fprintf(ficrescveij,"\n");
     for(i=1; i<=nlstate;i++)   
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);    if(estepm < stepm){
   }        printf ("Problem %d lower than %d\n",estepm, stepm);
   fprintf(ficresprobmorprev,"\n");    }
   fprintf(ficgp,"\n# Routine varevsij");    else  hstepm=estepm;  
   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/    /* We compute the life expectancy from trapezoids spaced every estepm months
   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");     * This is mainly to measure the difference between two models: for example
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);     * if stepm=24 months pijx are given only every 2 years and by summing them
 /*   } */     * we are calculating an estimate of the Life Expectancy assuming a linear
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);     * progression in between and thus overestimating or underestimating according
  fprintf(ficresvij, "#Local time at start: %s", strstart);     * to the curvature of the survival function. If, for the same date, we
   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");     * estimate the model with stepm=1 month, we can keep estepm to 24 months
   fprintf(ficresvij,"# Age");     * to compare the new estimate of Life expectancy with the same linear
   for(i=1; i<=nlstate;i++)     * hypothesis. A more precise result, taking into account a more precise
     for(j=1; j<=nlstate;j++)     * curvature will be obtained if estepm is as small as stepm. */
       fprintf(ficresvij," Cov(e%1d, e%1d)",i,j);  
   fprintf(ficresvij,"\n");    /* For example we decided to compute the life expectancy with the smallest unit */
     /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   xp=vector(1,npar);       nhstepm is the number of hstepm from age to agelim
   dnewm=matrix(1,nlstate,1,npar);       nstepm is the number of stepm from age to agelin.
   doldm=matrix(1,nlstate,1,nlstate);       Look at hpijx to understand the reason of that which relies in memory size
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);       and note for a fixed period like estepm months */
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
        survival function given by stepm (the optimization length). Unfortunately it
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);       means that if the survival funtion is printed only each two years of age and if
   gpp=vector(nlstate+1,nlstate+ndeath);       you sum them up and add 1 year (area under the trapezoids) you won't get the same
   gmp=vector(nlstate+1,nlstate+ndeath);       results. So we changed our mind and took the option of the best precision.
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/    */
       hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   if(estepm < stepm){  
     printf ("Problem %d lower than %d\n",estepm, stepm);    /* If stepm=6 months */
   }    /* nhstepm age range expressed in number of stepm */
   else  hstepm=estepm;       agelim=AGESUP;
   /* For example we decided to compute the life expectancy with the smallest unit */    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.     /* Typically if 20 years nstepm = 20*12/6=40 stepm */
      nhstepm is the number of hstepm from age to agelim     /* if (stepm >= YEARM) hstepm=1;*/
      nstepm is the number of stepm from age to agelin.     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
      Look at hpijx to understand the reason of that which relies in memory size   
      and note for a fixed period like k years */    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
      survival function given by stepm (the optimization length). Unfortunately it    gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
      means that if the survival funtion is printed every two years of age and if    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     gp=matrix(0,nhstepm,1,nlstate*nlstate);
      results. So we changed our mind and took the option of the best precision.    gm=matrix(0,nhstepm,1,nlstate*nlstate);
   */  
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     for (age=bage; age<=fage; age ++){
   agelim = AGESUP;  
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */      /* Computed by stepm unit matrices, product of hstepm matrices, stored
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */          in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */   
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);  
     gp=matrix(0,nhstepm,1,nlstate);      /* Computing  Variances of health expectancies */
     gm=matrix(0,nhstepm,1,nlstate);      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
          decrease memory allocation */
       for(theta=1; theta <=npar; theta++){
     for(theta=1; theta <=npar; theta++){        for(i=1; i<=npar; i++){
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/          xp[i] = x[i] + (i==theta ?delti[theta]:0);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);          xm[i] = x[i] - (i==theta ?delti[theta]:0);
       }        }
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);          hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
    
       if (popbased==1) {        for(j=1; j<= nlstate; j++){
         if(mobilav ==0){          for(i=1; i<=nlstate; i++){
           for(i=1; i<=nlstate;i++)            for(h=0; h<=nhstepm-1; h++){
             prlim[i][i]=probs[(int)age][i][ij];              gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
         }else{ /* mobilav */               gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
           for(i=1; i<=nlstate;i++)            }
             prlim[i][i]=mobaverage[(int)age][i][ij];          }
         }        }
       }       
           for(ij=1; ij<= nlstate*nlstate; ij++)
       for(j=1; j<= nlstate; j++){          for(h=0; h<=nhstepm-1; h++){
         for(h=0; h<=nhstepm; h++){            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)          }
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];      }/* End theta */
         }     
       }     
       /* This for computing probability of death (h=1 means      for(h=0; h<=nhstepm-1; h++)
          computed over hstepm matrices product = hstepm*stepm months)         for(j=1; j<=nlstate*nlstate;j++)
          as a weighted average of prlim.          for(theta=1; theta <=npar; theta++)
       */            trgradg[h][j][theta]=gradg[h][theta][j];
       for(j=nlstate+1;j<=nlstate+ndeath;j++){     
         for(i=1,gpp[j]=0.; i<= nlstate; i++)  
           gpp[j] += prlim[i][i]*p3mat[i][j][1];       for(ij=1;ij<=nlstate*nlstate;ij++)
       }            for(ji=1;ji<=nlstate*nlstate;ji++)
       /* end probability of death */          varhe[ij][ji][(int)age] =0.;
   
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */       printf("%d|",(int)age);fflush(stdout);
         xp[i] = x[i] - (i==theta ?delti[theta]:0);       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);         for(h=0;h<=nhstepm-1;h++){
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);        for(k=0;k<=nhstepm-1;k++){
            matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
       if (popbased==1) {          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
         if(mobilav ==0){          for(ij=1;ij<=nlstate*nlstate;ij++)
           for(i=1; i<=nlstate;i++)            for(ji=1;ji<=nlstate*nlstate;ji++)
             prlim[i][i]=probs[(int)age][i][ij];              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
         }else{ /* mobilav */         }
           for(i=1; i<=nlstate;i++)      }
             prlim[i][i]=mobaverage[(int)age][i][ij];  
         }      /* Computing expectancies */
       }      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
       for(i=1; i<=nlstate;i++)
       for(j=1; j<= nlstate; j++){        for(j=1; j<=nlstate;j++)
         for(h=0; h<=nhstepm; h++){          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];           
         }            /* 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]);*/
       }  
       /* This for computing probability of death (h=1 means          }
          computed over hstepm matrices product = hstepm*stepm months)   
          as a weighted average of prlim.      fprintf(ficresstdeij,"%3.0f",age );
       */      for(i=1; i<=nlstate;i++){
       for(j=nlstate+1;j<=nlstate+ndeath;j++){        eip=0.;
         for(i=1,gmp[j]=0.; i<= nlstate; i++)        vip=0.;
          gmp[j] += prlim[i][i]*p3mat[i][j][1];        for(j=1; j<=nlstate;j++){
       }              eip += eij[i][j][(int)age];
       /* end probability of death */          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];
       for(j=1; j<= nlstate; j++) /* vareij */          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
         for(h=0; h<=nhstepm; h++){        }
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
         }      }
       fprintf(ficresstdeij,"\n");
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */  
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];      fprintf(ficrescveij,"%3.0f",age );
       }      for(i=1; i<=nlstate;i++)
         for(j=1; j<=nlstate;j++){
     } /* End theta */          cptj= (j-1)*nlstate+i;
           for(i2=1; i2<=nlstate;i2++)
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */            for(j2=1; j2<=nlstate;j2++){
               cptj2= (j2-1)*nlstate+i2;
     for(h=0; h<=nhstepm; h++) /* veij */              if(cptj2 <= cptj)
       for(j=1; j<=nlstate;j++)                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
         for(theta=1; theta <=npar; theta++)            }
           trgradg[h][j][theta]=gradg[h][theta][j];        }
       fprintf(ficrescveij,"\n");
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */     
       for(theta=1; theta <=npar; theta++)    }
         trgradgp[j][theta]=gradgp[theta][j];    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
       free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
     for(i=1;i<=nlstate;i++)    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       for(j=1;j<=nlstate;j++)    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         vareij[i][j][(int)age] =0.;    printf("\n");
     fprintf(ficlog,"\n");
     for(h=0;h<=nhstepm;h++){  
       for(k=0;k<=nhstepm;k++){    free_vector(xm,1,npar);
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);    free_vector(xp,1,npar);
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
         for(i=1;i<=nlstate;i++)    free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
           for(j=1;j<=nlstate;j++)    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;  }
       }  
     }  /************ Variance ******************/
     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[])
     /* pptj */  {
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);    /* Variance of health expectancies */
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
     for(j=nlstate+1;j<=nlstate+ndeath;j++)    /* double **newm;*/
       for(i=nlstate+1;i<=nlstate+ndeath;i++)    double **dnewm,**doldm;
         varppt[j][i]=doldmp[j][i];    double **dnewmp,**doldmp;
     /* end ppptj */    int i, j, nhstepm, hstepm, h, nstepm ;
     /*  x centered again */    int k, cptcode;
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);      double *xp;
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);    double **gp, **gm;  /* for var eij */
      double ***gradg, ***trgradg; /*for var eij */
     if (popbased==1) {    double **gradgp, **trgradgp; /* for var p point j */
       if(mobilav ==0){    double *gpp, *gmp; /* for var p point j */
         for(i=1; i<=nlstate;i++)    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
           prlim[i][i]=probs[(int)age][i][ij];    double ***p3mat;
       }else{ /* mobilav */     double age,agelim, hf;
         for(i=1; i<=nlstate;i++)    double ***mobaverage;
           prlim[i][i]=mobaverage[(int)age][i][ij];    int theta;
       }    char digit[4];
     }    char digitp[25];
                
     /* This for computing probability of death (h=1 means    char fileresprobmorprev[FILENAMELENGTH];
        computed over hstepm (estepm) matrices product = hstepm*stepm months)   
        as a weighted average of prlim.    if(popbased==1){
     */      if(mobilav!=0)
     for(j=nlstate+1;j<=nlstate+ndeath;j++){        strcpy(digitp,"-populbased-mobilav-");
       for(i=1,gmp[j]=0.;i<= nlstate; i++)       else strcpy(digitp,"-populbased-nomobil-");
         gmp[j] += prlim[i][i]*p3mat[i][j][1];     }
     }        else
     /* end probability of death */      strcpy(digitp,"-stablbased-");
   
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);    if (mobilav!=0) {
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
       for(i=1; i<=nlstate;i++){        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
       }      }
     }     }
     fprintf(ficresprobmorprev,"\n");  
     strcpy(fileresprobmorprev,"prmorprev");
     fprintf(ficresvij,"%.0f ",age );    sprintf(digit,"%-d",ij);
     for(i=1; i<=nlstate;i++)    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
       for(j=1; j<=nlstate;j++){    strcat(fileresprobmorprev,digit); /* Tvar to be done */
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
       }    strcat(fileresprobmorprev,fileres);
     fprintf(ficresvij,"\n");    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
     free_matrix(gp,0,nhstepm,1,nlstate);      printf("Problem with resultfile: %s\n", fileresprobmorprev);
     free_matrix(gm,0,nhstepm,1,nlstate);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);    }
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   
   } /* End age */    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   free_vector(gpp,nlstate+1,nlstate+ndeath);    pstamp(ficresprobmorprev);
   free_vector(gmp,nlstate+1,nlstate+ndeath);    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);
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");      fprintf(ficresprobmorprev," p.%-d SE",j);
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */      for(i=1; i<=nlstate;i++)
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */    }  
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */    fprintf(ficresprobmorprev,"\n");
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */    fprintf(ficgp,"\n# Routine varevsij");
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));    fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
   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);    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   /*  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);    pstamp(ficresvij);
 */    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */    if(popbased==1)
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
     else
   free_vector(xp,1,npar);      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
   free_matrix(doldm,1,nlstate,1,nlstate);    fprintf(ficresvij,"# Age");
   free_matrix(dnewm,1,nlstate,1,npar);    for(i=1; i<=nlstate;i++)
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);      for(j=1; j<=nlstate;j++)
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    fprintf(ficresvij,"\n");
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  
   fclose(ficresprobmorprev);    xp=vector(1,npar);
   fflush(ficgp);    dnewm=matrix(1,nlstate,1,npar);
   fflush(fichtm);     doldm=matrix(1,nlstate,1,nlstate);
 }  /* end varevsij */    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
     doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 /************ Variance of prevlim ******************/  
 void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 {    gpp=vector(nlstate+1,nlstate+ndeath);
   /* Variance of prevalence limit */    gmp=vector(nlstate+1,nlstate+ndeath);
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
   double **newm;   
   double **dnewm,**doldm;    if(estepm < stepm){
   int i, j, nhstepm, hstepm;      printf ("Problem %d lower than %d\n",estepm, stepm);
   int k, cptcode;    }
   double *xp;    else  hstepm=estepm;  
   double *gp, *gm;    /* For example we decided to compute the life expectancy with the smallest unit */
   double **gradg, **trgradg;    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   double age,agelim;       nhstepm is the number of hstepm from age to agelim
   int theta;       nstepm is the number of stepm from age to agelin.
   fprintf(ficresvpl, "#Local time at start: %s", strstart);        Look at hpijx to understand the reason of that which relies in memory size
   fprintf(ficresvpl,"# Standard deviation of stable prevalences \n");       and note for a fixed period like k years */
   fprintf(ficresvpl,"# Age");    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   for(i=1; i<=nlstate;i++)       survival function given by stepm (the optimization length). Unfortunately it
       fprintf(ficresvpl," %1d-%1d",i,i);       means that if the survival funtion is printed every two years of age and if
   fprintf(ficresvpl,"\n");       you sum them up and add 1 year (area under the trapezoids) you won't get the same
        results. So we changed our mind and took the option of the best precision.
   xp=vector(1,npar);    */
   dnewm=matrix(1,nlstate,1,npar);    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   doldm=matrix(1,nlstate,1,nlstate);    agelim = AGESUP;
       for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
   hstepm=1*YEARM; /* Every year of age */      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */       nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
   agelim = AGESUP;      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */       gp=matrix(0,nhstepm,1,nlstate);
     if (stepm >= YEARM) hstepm=1;      gm=matrix(0,nhstepm,1,nlstate);
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */  
     gradg=matrix(1,npar,1,nlstate);  
     gp=vector(1,nlstate);      for(theta=1; theta <=npar; theta++){
     gm=vector(1,nlstate);        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
           xp[i] = x[i] + (i==theta ?delti[theta]:0);
     for(theta=1; theta <=npar; theta++){        }
       for(i=1; i<=npar; i++){ /* Computes gradient */        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
         xp[i] = x[i] + (i==theta ?delti[theta]:0);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
       }  
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);        if (popbased==1) {
       for(i=1;i<=nlstate;i++)          if(mobilav ==0){
         gp[i] = prlim[i][i];            for(i=1; i<=nlstate;i++)
                   prlim[i][i]=probs[(int)age][i][ij];
       for(i=1; i<=npar; i++) /* Computes gradient */          }else{ /* mobilav */
         xp[i] = x[i] - (i==theta ?delti[theta]:0);            for(i=1; i<=nlstate;i++)
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);              prlim[i][i]=mobaverage[(int)age][i][ij];
       for(i=1;i<=nlstate;i++)          }
         gm[i] = prlim[i][i];        }
    
       for(i=1;i<=nlstate;i++)        for(j=1; j<= nlstate; j++){
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];          for(h=0; h<=nhstepm; h++){
     } /* End theta */            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
               gp[h][j] += prlim[i][i]*p3mat[i][j][h];
     trgradg =matrix(1,nlstate,1,npar);          }
         }
     for(j=1; j<=nlstate;j++)        /* This for computing probability of death (h=1 means
       for(theta=1; theta <=npar; theta++)           computed over hstepm matrices product = hstepm*stepm months)
         trgradg[j][theta]=gradg[theta][j];           as a weighted average of prlim.
         */
     for(i=1;i<=nlstate;i++)        for(j=nlstate+1;j<=nlstate+ndeath;j++){
       varpl[i][(int)age] =0.;          for(i=1,gpp[j]=0.; i<= nlstate; i++)
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);            gpp[j] += prlim[i][i]*p3mat[i][j][1];
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);        }    
     for(i=1;i<=nlstate;i++)        /* end probability of death */
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */  
         for(i=1; i<=npar; i++) /* Computes gradient x - delta */
     fprintf(ficresvpl,"%.0f ",age );          xp[i] = x[i] - (i==theta ?delti[theta]:0);
     for(i=1; i<=nlstate;i++)        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
     fprintf(ficresvpl,"\n");   
     free_vector(gp,1,nlstate);        if (popbased==1) {
     free_vector(gm,1,nlstate);          if(mobilav ==0){
     free_matrix(gradg,1,npar,1,nlstate);            for(i=1; i<=nlstate;i++)
     free_matrix(trgradg,1,nlstate,1,npar);              prlim[i][i]=probs[(int)age][i][ij];
   } /* End age */          }else{ /* mobilav */
             for(i=1; i<=nlstate;i++)
   free_vector(xp,1,npar);              prlim[i][i]=mobaverage[(int)age][i][ij];
   free_matrix(doldm,1,nlstate,1,npar);          }
   free_matrix(dnewm,1,nlstate,1,nlstate);        }
   
 }        for(j=1; j<= nlstate; j++){
           for(h=0; h<=nhstepm; h++){
 /************ Variance of one-step probabilities  ******************/            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 {          }
   int i, j=0,  i1, k1, l1, t, tj;        }
   int k2, l2, j1,  z1;        /* This for computing probability of death (h=1 means
   int k=0,l, cptcode;           computed over hstepm matrices product = hstepm*stepm months)
   int first=1, first1;           as a weighted average of prlim.
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;        */
   double **dnewm,**doldm;        for(j=nlstate+1;j<=nlstate+ndeath;j++){
   double *xp;          for(i=1,gmp[j]=0.; i<= nlstate; i++)
   double *gp, *gm;           gmp[j] += prlim[i][i]*p3mat[i][j][1];
   double **gradg, **trgradg;        }    
   double **mu;        /* end probability of death */
   double age,agelim, cov[NCOVMAX];  
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */        for(j=1; j<= nlstate; j++) /* vareij */
   int theta;          for(h=0; h<=nhstepm; h++){
   char fileresprob[FILENAMELENGTH];            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
   char fileresprobcov[FILENAMELENGTH];          }
   char fileresprobcor[FILENAMELENGTH];  
         for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
   double ***varpij;          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
         }
   strcpy(fileresprob,"prob");   
   strcat(fileresprob,fileres);      } /* End theta */
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {  
     printf("Problem with resultfile: %s\n", fileresprob);      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);  
   }      for(h=0; h<=nhstepm; h++) /* veij */
   strcpy(fileresprobcov,"probcov");         for(j=1; j<=nlstate;j++)
   strcat(fileresprobcov,fileres);          for(theta=1; theta <=npar; theta++)
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {            trgradg[h][j][theta]=gradg[h][theta][j];
     printf("Problem with resultfile: %s\n", fileresprobcov);  
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
   }        for(theta=1; theta <=npar; theta++)
   strcpy(fileresprobcor,"probcor");           trgradgp[j][theta]=gradgp[theta][j];
   strcat(fileresprobcor,fileres);   
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {  
     printf("Problem with resultfile: %s\n", fileresprobcor);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);      for(i=1;i<=nlstate;i++)
   }        for(j=1;j<=nlstate;j++)
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);          vareij[i][j][(int)age] =0.;
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);  
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);      for(h=0;h<=nhstepm;h++){
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);        for(k=0;k<=nhstepm;k++){
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
   fprintf(ficresprob, "#Local time at start: %s", strstart);          for(i=1;i<=nlstate;i++)
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");            for(j=1;j<=nlstate;j++)
   fprintf(ficresprob,"# Age");              vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
   fprintf(ficresprobcov, "#Local time at start: %s", strstart);        }
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");      }
   fprintf(ficresprobcov,"# Age");   
   fprintf(ficresprobcor, "#Local time at start: %s", strstart);      /* pptj */
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
   fprintf(ficresprobcov,"# Age");      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
       for(j=nlstate+1;j<=nlstate+ndeath;j++)
         for(i=nlstate+1;i<=nlstate+ndeath;i++)
   for(i=1; i<=nlstate;i++)          varppt[j][i]=doldmp[j][i];
     for(j=1; j<=(nlstate+ndeath);j++){      /* end ppptj */
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);      /*  x centered again */
       fprintf(ficresprobcov," p%1d-%1d ",i,j);      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
       fprintf(ficresprobcor," p%1d-%1d ",i,j);      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
     }     
  /* fprintf(ficresprob,"\n");      if (popbased==1) {
   fprintf(ficresprobcov,"\n");        if(mobilav ==0){
   fprintf(ficresprobcor,"\n");          for(i=1; i<=nlstate;i++)
  */            prlim[i][i]=probs[(int)age][i][ij];
  xp=vector(1,npar);        }else{ /* mobilav */
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);          for(i=1; i<=nlstate;i++)
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));            prlim[i][i]=mobaverage[(int)age][i][ij];
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);        }
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);      }
   first=1;               
   fprintf(ficgp,"\n# Routine varprob");      /* This for computing probability of death (h=1 means
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");         computed over hstepm (estepm) matrices product = hstepm*stepm months)
   fprintf(fichtm,"\n");         as a weighted average of prlim.
       */
   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++){
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\        for(i=1,gmp[j]=0.;i<= nlstate; i++)
   file %s<br>\n",optionfilehtmcov);          gmp[j] += prlim[i][i]*p3mat[i][j][1];
   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 probability of death */
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");  
   fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 standard deviations wide on each axis. <br>\        for(i=1; i<=nlstate;i++){
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
  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");      }
       fprintf(ficresprobmorprev,"\n");
   cov[1]=1;  
   tj=cptcoveff;      fprintf(ficresvij,"%.0f ",age );
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}      for(i=1; i<=nlstate;i++)
   j1=0;        for(j=1; j<=nlstate;j++){
   for(t=1; t<=tj;t++){          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
     for(i1=1; i1<=ncodemax[t];i1++){         }
       j1++;      fprintf(ficresvij,"\n");
       if  (cptcovn>0) {      free_matrix(gp,0,nhstepm,1,nlstate);
         fprintf(ficresprob, "\n#********** Variable ");       free_matrix(gm,0,nhstepm,1,nlstate);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
         fprintf(ficresprob, "**********\n#\n");      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
         fprintf(ficresprobcov, "\n#********** Variable ");       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    } /* End age */
         fprintf(ficresprobcov, "**********\n#\n");    free_vector(gpp,nlstate+1,nlstate+ndeath);
             free_vector(gmp,nlstate+1,nlstate+ndeath);
         fprintf(ficgp, "\n#********** Variable ");     free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
         fprintf(ficgp, "**********\n#\n");    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
             /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
             fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");   /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
             fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
         fprintf(ficresprobcor, "\n#********** Variable ");        fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
         fprintf(ficresprobcor, "**********\n#");        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);
           /*  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 (age=bage; age<=fage; age ++){   */
         cov[2]=age;  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
         for (k=1; k<=cptcovn;k++) {    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];  
         }    free_vector(xp,1,npar);
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];    free_matrix(doldm,1,nlstate,1,nlstate);
         for (k=1; k<=cptcovprod;k++)    free_matrix(dnewm,1,nlstate,1,npar);
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
             free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         gp=vector(1,(nlstate)*(nlstate+ndeath));    fclose(ficresprobmorprev);
         gm=vector(1,(nlstate)*(nlstate+ndeath));    fflush(ficgp);
         fflush(fichtm);
         for(theta=1; theta <=npar; theta++){  }  /* end varevsij */
           for(i=1; i<=npar; i++)  
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);  /************ Variance of prevlim ******************/
             void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])
           pmij(pmmij,cov,ncovmodel,xp,nlstate);  {
               /* Variance of prevalence limit */
           k=0;    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
           for(i=1; i<= (nlstate); i++){    double **newm;
             for(j=1; j<=(nlstate+ndeath);j++){    double **dnewm,**doldm;
               k=k+1;    int i, j, nhstepm, hstepm;
               gp[k]=pmmij[i][j];    int k, cptcode;
             }    double *xp;
           }    double *gp, *gm;
               double **gradg, **trgradg;
           for(i=1; i<=npar; i++)    double age,agelim;
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);    int theta;
        
           pmij(pmmij,cov,ncovmodel,xp,nlstate);    pstamp(ficresvpl);
           k=0;    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
           for(i=1; i<=(nlstate); i++){    fprintf(ficresvpl,"# Age");
             for(j=1; j<=(nlstate+ndeath);j++){    for(i=1; i<=nlstate;i++)
               k=k+1;        fprintf(ficresvpl," %1d-%1d",i,i);
               gm[k]=pmmij[i][j];    fprintf(ficresvpl,"\n");
             }  
           }    xp=vector(1,npar);
          dnewm=matrix(1,nlstate,1,npar);
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)     doldm=matrix(1,nlstate,1,nlstate);
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];     
         }    hstepm=1*YEARM; /* Every year of age */
     hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)    agelim = AGESUP;
           for(theta=1; theta <=npar; theta++)    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
             trgradg[j][theta]=gradg[theta][j];      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
               if (stepm >= YEARM) hstepm=1;
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);      gradg=matrix(1,npar,1,nlstate);
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));      gp=vector(1,nlstate);
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));      gm=vector(1,nlstate);
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);  
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);      for(theta=1; theta <=npar; theta++){
         for(i=1; i<=npar; i++){ /* Computes gradient */
         pmij(pmmij,cov,ncovmodel,x,nlstate);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
                 }
         k=0;        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(i=1; i<=(nlstate); i++){        for(i=1;i<=nlstate;i++)
           for(j=1; j<=(nlstate+ndeath);j++){          gp[i] = prlim[i][i];
             k=k+1;     
             mu[k][(int) age]=pmmij[i][j];        for(i=1; i<=npar; i++) /* Computes gradient */
           }          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         }        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)        for(i=1;i<=nlstate;i++)
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)          gm[i] = prlim[i][i];
             varpij[i][j][(int)age] = doldm[i][j];  
         for(i=1;i<=nlstate;i++)
         /*printf("\n%d ",(int)age);          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){      } /* End theta */
           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]));      trgradg =matrix(1,nlstate,1,npar);
           }*/  
       for(j=1; j<=nlstate;j++)
         fprintf(ficresprob,"\n%d ",(int)age);        for(theta=1; theta <=npar; theta++)
         fprintf(ficresprobcov,"\n%d ",(int)age);          trgradg[j][theta]=gradg[theta][j];
         fprintf(ficresprobcor,"\n%d ",(int)age);  
       for(i=1;i<=nlstate;i++)
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)        varpl[i][(int)age] =0.;
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);      for(i=1;i<=nlstate;i++)
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
         }  
         i=0;      fprintf(ficresvpl,"%.0f ",age );
         for (k=1; k<=(nlstate);k++){      for(i=1; i<=nlstate;i++)
           for (l=1; l<=(nlstate+ndeath);l++){         fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
             i=i++;      fprintf(ficresvpl,"\n");
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);      free_vector(gp,1,nlstate);
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);      free_vector(gm,1,nlstate);
             for (j=1; j<=i;j++){      free_matrix(gradg,1,npar,1,nlstate);
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);      free_matrix(trgradg,1,nlstate,1,npar);
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));    } /* End age */
             }  
           }    free_vector(xp,1,npar);
         }/* end of loop for state */    free_matrix(doldm,1,nlstate,1,npar);
       } /* end of loop for age */    free_matrix(dnewm,1,nlstate,1,nlstate);
   
       /* Confidence intervalle of pij  */  }
       /*  
         fprintf(ficgp,"\nset noparametric;unset label");  /************ Variance of one-step probabilities  ******************/
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");  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,"\nset ter png small\nset size 0.65,0.65");  {
         fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);    int i, j=0,  i1, k1, l1, t, tj;
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);    int k2, l2, j1,  z1;
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);    int k=0,l, cptcode;
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);    int first=1, first1;
       */    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
     double **dnewm,**doldm;
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/    double *xp;
       first1=1;    double *gp, *gm;
       for (k2=1; k2<=(nlstate);k2++){    double **gradg, **trgradg;
         for (l2=1; l2<=(nlstate+ndeath);l2++){     double **mu;
           if(l2==k2) continue;    double age,agelim, cov[NCOVMAX];
           j=(k2-1)*(nlstate+ndeath)+l2;    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
           for (k1=1; k1<=(nlstate);k1++){    int theta;
             for (l1=1; l1<=(nlstate+ndeath);l1++){     char fileresprob[FILENAMELENGTH];
               if(l1==k1) continue;    char fileresprobcov[FILENAMELENGTH];
               i=(k1-1)*(nlstate+ndeath)+l1;    char fileresprobcor[FILENAMELENGTH];
               if(i<=j) continue;  
               for (age=bage; age<=fage; age ++){     double ***varpij;
                 if ((int)age %5==0){  
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;    strcpy(fileresprob,"prob");
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;    strcat(fileresprob,fileres);
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   mu1=mu[i][(int) age]/stepm*YEARM ;      printf("Problem with resultfile: %s\n", fileresprob);
                   mu2=mu[j][(int) age]/stepm*YEARM;      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   c12=cv12/sqrt(v1*v2);    }
                   /* Computing eigen value of matrix of covariance */    strcpy(fileresprobcov,"probcov");
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;    strcat(fileresprobcov,fileres);
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   /* Eigen vectors */      printf("Problem with resultfile: %s\n", fileresprobcov);
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   /*v21=sqrt(1.-v11*v11); *//* error */    }
                   v21=(lc1-v1)/cv12*v11;    strcpy(fileresprobcor,"probcor");
                   v12=-v21;    strcat(fileresprobcor,fileres);
                   v22=v11;    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   tnalp=v21/v11;      printf("Problem with resultfile: %s\n", fileresprobcor);
                   if(first1==1){      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                     first1=0;    }
                     printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);    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);
                   fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   /*printf(fignu*/    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   if(first==1){    pstamp(ficresprob);
                     first=0;    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                     fprintf(ficgp,"\nset parametric;unset label");    fprintf(ficresprob,"# Age");
                     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);    pstamp(ficresprobcov);
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\    fprintf(ficresprobcov,"# Age");
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\    pstamp(ficresprobcor);
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\    fprintf(ficresprobcor,"# Age");
                             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);    for(i=1; i<=nlstate;i++)
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);      for(j=1; j<=(nlstate+ndeath);j++){
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                     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",\        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\      }  
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));   /* fprintf(ficresprob,"\n");
                   }else{    fprintf(ficresprobcov,"\n");
                     first=0;    fprintf(ficresprobcor,"\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);   xp=vector(1,npar);
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                     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",\    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   }/* if first */    first=1;
                 } /* age mod 5 */    fprintf(ficgp,"\n# Routine varprob");
               } /* end loop age */    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);    fprintf(fichtm,"\n");
               first=1;  
             } /*l12 */    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
           } /* k12 */    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
         } /*l1 */    file %s<br>\n",optionfilehtmcov);
       }/* k1 */    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
     } /* loop covariates */  and drawn. It helps understanding how is the covariance between two incidences.\
   }   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);    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. \
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));  would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);  standard deviations wide on each axis. <br>\
   free_vector(xp,1,npar);   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
   fclose(ficresprob);   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
   fclose(ficresprobcov);  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
   fclose(ficresprobcor);  
   fflush(ficgp);    cov[1]=1;
   fflush(fichtmcov);    tj=cptcoveff;
 }    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
     j1=0;
     for(t=1; t<=tj;t++){
 /******************* Printing html file ***********/      for(i1=1; i1<=ncodemax[t];i1++){
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \        j1++;
                   int lastpass, int stepm, int weightopt, char model[],\        if  (cptcovn>0) {
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\          fprintf(ficresprob, "\n#********** Variable ");
                   int popforecast, int estepm ,\          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   double jprev1, double mprev1,double anprev1, \          fprintf(ficresprob, "**********\n#\n");
                   double jprev2, double mprev2,double anprev2){          fprintf(ficresprobcov, "\n#********** Variable ");
   int jj1, k1, i1, cpt;          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,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \         
    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \          fprintf(ficgp, "\n#********** Variable ");
 </ul>");          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \          fprintf(ficgp, "**********\n#\n");
  - 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(fichtm,"\          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
  - Estimated transition probabilities over %d (stepm) months: <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]]);
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
    fprintf(fichtm,"\         
  - Stable prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",          fprintf(ficresprobcor, "\n#********** Variable ");    
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
    fprintf(fichtm,"\          fprintf(ficresprobcor, "**********\n#");    
  - 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 (age=bage; age<=fage; age ++){
           cov[2]=age;
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");          for (k=1; k<=cptcovn;k++) {
             cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
  m=cptcoveff;          }
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           for (k=1; k<=cptcovprod;k++)
  jj1=0;            cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
  for(k1=1; k1<=m;k1++){         
    for(i1=1; i1<=ncodemax[k1];i1++){          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
      jj1++;          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
      if (cptcovn > 0) {          gp=vector(1,(nlstate)*(nlstate+ndeath));
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");          gm=vector(1,(nlstate)*(nlstate+ndeath));
        for (cpt=1; cpt<=cptcoveff;cpt++)      
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);          for(theta=1; theta <=npar; theta++){
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");            for(i=1; i<=npar; i++)
      }              xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
      /* Pij */           
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: %s%d1.png<br> \            pmij(pmmij,cov,ncovmodel,xp,nlstate);
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);                
      /* Quasi-incidences */            k=0;
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\            for(i=1; i<= (nlstate); i++){
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: %s%d2.png<br> \              for(j=1; j<=(nlstate+ndeath);j++){
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);                 k=k+1;
        /* Stable prevalence in each health state */                gp[k]=pmmij[i][j];
        for(cpt=1; cpt<nlstate;cpt++){              }
          fprintf(fichtm,"<br>- Stable prevalence in each health state : p%s%d%d.png<br> \            }
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);           
        }            for(i=1; i<=npar; i++)
      for(cpt=1; cpt<=nlstate;cpt++) {              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
         fprintf(fichtm,"\n<br>- Health life expectancies by age and initial health state (%d): %s%d%d.png <br> \     
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);            pmij(pmmij,cov,ncovmodel,xp,nlstate);
      }            k=0;
    } /* end i1 */            for(i=1; i<=(nlstate); i++){
  }/* End k1 */              for(j=1; j<=(nlstate+ndeath);j++){
  fprintf(fichtm,"</ul>");                k=k+1;
                 gm[k]=pmmij[i][j];
               }
  fprintf(fichtm,"\            }
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\       
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
               gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",          }
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));  
  fprintf(fichtm,"\          for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",            for(theta=1; theta <=npar; theta++)
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));              trgradg[j][theta]=gradg[theta][j];
          
  fprintf(fichtm,"\          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
  fprintf(fichtm,"\          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
  - Variances and covariances of life expectancies by age and initial health status (estepm=%d months): <a href=\"%s\">%s</a><br>\n",          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
  fprintf(fichtm,"\  
  - Health expectancies with their variances (no covariance): <a href=\"%s\">%s</a> <br>\n",          pmij(pmmij,cov,ncovmodel,x,nlstate);
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));         
  fprintf(fichtm,"\          k=0;
  - Standard deviation of stable prevalences: <a href=\"%s\">%s</a> <br>\n",\          for(i=1; i<=(nlstate); i++){
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));            for(j=1; j<=(nlstate+ndeath);j++){
               k=k+1;
 /*  if(popforecast==1) fprintf(fichtm,"\n */              mu[k][(int) age]=pmmij[i][j];
 /*  - 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 */          }
 /*      <br>",fileres,fileres,fileres,fileres); */          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 /*  else  */            for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 /*    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); */              varpij[i][j][(int)age] = doldm[i][j];
  fflush(fichtm);  
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");          /*printf("\n%d ",(int)age);
             for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
  m=cptcoveff;            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
             }*/
  jj1=0;  
  for(k1=1; k1<=m;k1++){          fprintf(ficresprob,"\n%d ",(int)age);
    for(i1=1; i1<=ncodemax[k1];i1++){          fprintf(ficresprobcov,"\n%d ",(int)age);
      jj1++;          fprintf(ficresprobcor,"\n%d ",(int)age);
      if (cptcovn > 0) {  
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
        for (cpt=1; cpt<=cptcoveff;cpt++)             fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
      }            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
      for(cpt=1; cpt<=nlstate;cpt++) {          }
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \          i=0;
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\          for (k=1; k<=(nlstate);k++){
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);              for (l=1; l<=(nlstate+ndeath);l++){
      }              i=i++;
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 health expectancies in states (1) and (2): %s%d.png<br>\              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);              for (j=1; j<=i;j++){
    } /* end i1 */                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
  }/* End k1 */                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
  fprintf(fichtm,"</ul>");              }
  fflush(fichtm);            }
 }          }/* end of loop for state */
         } /* end of loop for age */
 /******************* Gnuplot file **************/  
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){        /* Confidence intervalle of pij  */
         /*
   char dirfileres[132],optfileres[132];          fprintf(ficgp,"\nset noparametric;unset label");
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
   int ng;          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */          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);
 /*     printf("Problem with file %s",optionfilegnuplot); */          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 /*   } */          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
         */
   /*#ifdef windows */  
   fprintf(ficgp,"cd \"%s\" \n",pathc);        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
     /*#endif */        first1=1;
   m=pow(2,cptcoveff);        for (k2=1; k2<=(nlstate);k2++){
           for (l2=1; l2<=(nlstate+ndeath);l2++){
   strcpy(dirfileres,optionfilefiname);            if(l2==k2) continue;
   strcpy(optfileres,"vpl");            j=(k2-1)*(nlstate+ndeath)+l2;
  /* 1eme*/            for (k1=1; k1<=(nlstate);k1++){
   for (cpt=1; cpt<= nlstate ; cpt ++) {              for (l1=1; l1<=(nlstate+ndeath);l1++){
    for (k1=1; k1<= m ; k1 ++) {                if(l1==k1) continue;
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);                i=(k1-1)*(nlstate+ndeath)+l1;
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);                if(i<=j) continue;
      fprintf(ficgp,"set xlabel \"Age\" \n\                for (age=bage; age<=fage; age ++){
 set ylabel \"Probability\" \n\                  if ((int)age %5==0){
 set ter png small\n\                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 set size 0.65,0.65\n\                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);                    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;
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");                    c12=cv12/sqrt(v1*v2);
        else fprintf(ficgp," \%%*lf (\%%*lf)");                    /* Computing eigen value of matrix of covariance */
      }                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
      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);                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
      for (i=1; i<= nlstate ; i ++) {                    /* Eigen vectors */
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
        else fprintf(ficgp," \%%*lf (\%%*lf)");                    /*v21=sqrt(1.-v11*v11); *//* error */
      }                     v21=(lc1-v1)/cv12*v11;
      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);                     v12=-v21;
      for (i=1; i<= nlstate ; i ++) {                    v22=v11;
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");                    tnalp=v21/v11;
        else fprintf(ficgp," \%%*lf (\%%*lf)");                    if(first1==1){
      }                        first1=0;
      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));                      printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
    }                    }
   }                    fprintf(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);
   /*2 eme*/                    /*printf(fignu*/
                       /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
   for (k1=1; k1<= m ; k1 ++) {                     /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);                    if(first==1){
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);                      first=0;
                           fprintf(ficgp,"\nset parametric;unset label");
     for (i=1; i<= nlstate+1 ; i ++) {                      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);
       k=2*i;                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
       for (j=1; j<= nlstate+1 ; j ++) {   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
         else fprintf(ficgp," \%%*lf (\%%*lf)");                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
       }                                 subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);                      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
       for (j=1; j<= nlstate+1 ; j ++) {                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
         else fprintf(ficgp," \%%*lf (\%%*lf)");                      fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
       }                                 mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
       fprintf(ficgp,"\" t\"\" w l 0,");                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);                    }else{
       for (j=1; j<= nlstate+1 ; j ++) {                      first=0;
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
         else fprintf(ficgp," \%%*lf (\%%*lf)");                      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);
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");                      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",\
       else fprintf(ficgp,"\" t\"\" w l 0,");                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
     }                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
   }                    }/* if first */
                     } /* age mod 5 */
   /*3eme*/                } /* end loop age */
                   fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   for (k1=1; k1<= m ; k1 ++) {                 first=1;
     for (cpt=1; cpt<= nlstate ; cpt ++) {              } /*l12 */
       k=2+nlstate*(2*cpt-2);            } /* k12 */
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);          } /*l1 */
       fprintf(ficgp,"set ter png small\n\        }/* k1 */
 set size 0.65,0.65\n\      } /* loop covariates */
 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);    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
         fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");    free_vector(xp,1,npar);
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);    fclose(ficresprob);
             fclose(ficresprobcov);
       */    fclose(ficresprobcor);
       for (i=1; i< nlstate ; i ++) {    fflush(ficgp);
         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);    fflush(fichtmcov);
           }
       }   
     }  
   }  /******************* Printing html file ***********/
     void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
   /* CV preval stable (period) */                    int lastpass, int stepm, int weightopt, char model[],\
   for (k1=1; k1<= m ; k1 ++) {                     int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
     for (cpt=1; cpt<=nlstate ; cpt ++) {                    int popforecast, int estepm ,\
       k=3;                    double jprev1, double mprev1,double anprev1, \
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);                    double jprev2, double mprev2,double anprev2){
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\    int jj1, k1, i1, cpt;
 set ter png small\nset size 0.65,0.65\n\  
 unset log y\n\     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
         </ul>");
       for (i=1; i< nlstate ; i ++)     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
         fprintf(ficgp,"+$%d",k+i+1);   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
            fprintf(fichtm,"\
       l=3+(nlstate+ndeath)*cpt;   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
       for (i=1; i< nlstate ; i ++) {     fprintf(fichtm,"\
         l=3+(nlstate+ndeath)*cpt;   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
         fprintf(ficgp,"+$%d",l+i+1);             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
       }     fprintf(fichtm,"\
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);      - (a) Life expectancies by health status at initial age, (b) health expectancies by health status at initial age:  ei., eij . If one or more covariate are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
     }      <a href=\"%s\">%s</a> <br>\n",
   }               estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
        fprintf(fichtm,"\
   /* proba elementaires */   - Population projections by age and states: \
   for(i=1,jk=1; i <=nlstate; i++){     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
     for(k=1; k <=(nlstate+ndeath); k++){  
       if (k != i) {  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
         for(j=1; j <=ncovmodel; j++){  
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);   m=cptcoveff;
           jk++;    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
           fprintf(ficgp,"\n");  
         }   jj1=0;
       }   for(k1=1; k1<=m;k1++){
     }     for(i1=1; i1<=ncodemax[k1];i1++){
    }       jj1++;
        if (cptcovn > 0) {
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
      for(jk=1; jk <=m; jk++) {         for (cpt=1; cpt<=cptcoveff;cpt++)
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);            fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
        if (ng==2)         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");       }
        else       /* Pij */
          fprintf(ficgp,"\nset title \"Probability\"\n");       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> \
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
        i=1;       /* Quasi-incidences */
        for(k2=1; k2<=nlstate; k2++) {       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
          k3=i;   before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \
          for(k=1; k<=(nlstate+ndeath); k++) {  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
            if (k != k2){         /* Period (stable) prevalence in each health state */
              if(ng==2)         for(cpt=1; cpt<nlstate;cpt++){
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
              else  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);         }
              ij=1;       for(cpt=1; cpt<=nlstate;cpt++) {
              for(j=3; j <=ncovmodel; j++) {          fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);       }
                  ij++;     } /* end i1 */
                }   }/* End k1 */
                else   fprintf(fichtm,"</ul>");
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);  
              }  
              fprintf(ficgp,")/(1");   fprintf(fichtm,"\
                \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
              for(k1=1; k1 <=nlstate; k1++){      - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);  
                ij=1;   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                for(j=3; j <=ncovmodel; j++){           subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {   fprintf(fichtm,"\
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                    ij++;           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                  }  
                  else   fprintf(fichtm,"\
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                }           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                fprintf(ficgp,")");   fprintf(fichtm,"\
              }   - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);     <a href=\"%s\">%s</a> <br>\n</li>",
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
              i=i+ncovmodel;   fprintf(fichtm,"\
            }   - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \
          } /* end k */     <a href=\"%s\">%s</a> <br>\n</li>",
        } /* end k2 */             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
      } /* end jk */   fprintf(fichtm,"\
    } /* end ng */   - 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",
    fflush(ficgp);            estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 }  /* end gnuplot */   fprintf(fichtm,"\
    - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors: <a href=\"%s\">%s</a> <br>\n",
            subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 /*************** Moving average **************/   fprintf(fichtm,"\
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
            subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
   int i, cpt, cptcod;  
   int modcovmax =1;  /*  if(popforecast==1) fprintf(fichtm,"\n */
   int mobilavrange, mob;  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
   double age;  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
   /*      <br>",fileres,fileres,fileres,fileres); */
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose   /*  else  */
                            a covariate has 2 modalities */  /*    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); */
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */   fflush(fichtm);
    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){  
     if(mobilav==1) mobilavrange=5; /* default */   m=cptcoveff;
     else mobilavrange=mobilav;   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
     for (age=bage; age<=fage; age++)  
       for (i=1; i<=nlstate;i++)   jj1=0;
         for (cptcod=1;cptcod<=modcovmax;cptcod++)   for(k1=1; k1<=m;k1++){
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];     for(i1=1; i1<=ncodemax[k1];i1++){
     /* We keep the original values on the extreme ages bage, fage and for        jj1++;
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2       if (cptcovn > 0) {
        we use a 5 terms etc. until the borders are no more concerned.          fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
     */          for (cpt=1; cpt<=cptcoveff;cpt++)
     for (mob=3;mob <=mobilavrange;mob=mob+2){           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
         for (i=1; i<=nlstate;i++){       }
           for (cptcod=1;cptcod<=modcovmax;cptcod++){       for(cpt=1; cpt<=nlstate;cpt++) {
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
               for (cpt=1;cpt<=(mob-1)/2;cpt++){  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];       }
               }       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;  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 */
       }/* end age */   }/* End k1 */
     }/* end mob */   fprintf(fichtm,"</ul>");
   }else return -1;   fflush(fichtm);
   return 0;  }
 }/* End movingaverage */  
   /******************* Gnuplot file **************/
   void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 /************** 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){    char dirfileres[132],optfileres[132];
   /* proj1, year, month, day of starting projection     int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
      agemin, agemax range of age    int ng;
      dateprev1 dateprev2 range of dates during which prevalence is computed  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
      anproj2 year of en of projection (same day and month as proj1).  /*     printf("Problem with file %s",optionfilegnuplot); */
   */  /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;  /*   } */
   int *popage;  
   double agec; /* generic age */    /*#ifdef windows */
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;    fprintf(ficgp,"cd \"%s\" \n",pathc);
   double *popeffectif,*popcount;      /*#endif */
   double ***p3mat;    m=pow(2,cptcoveff);
   double ***mobaverage;  
   char fileresf[FILENAMELENGTH];    strcpy(dirfileres,optionfilefiname);
     strcpy(optfileres,"vpl");
   agelim=AGESUP;   /* 1eme*/
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);    for (cpt=1; cpt<= nlstate ; cpt ++) {
       for (k1=1; k1<= m ; k1 ++) {
   strcpy(fileresf,"f");        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
   strcat(fileresf,fileres);       fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
   if((ficresf=fopen(fileresf,"w"))==NULL) {       fprintf(ficgp,"set xlabel \"Age\" \n\
     printf("Problem with forecast resultfile: %s\n", fileresf);  set ylabel \"Probability\" \n\
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);  set ter png small\n\
   }  set size 0.65,0.65\n\
   printf("Computing forecasting: result on file '%s' \n", fileresf);  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);  
        for (i=1; i<= nlstate ; i ++) {
   if (cptcoveff==0) ncodemax[cptcoveff]=1;         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
          else fprintf(ficgp," \%%*lf (\%%*lf)");
   if (mobilav!=0) {       }
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);       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);
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){       for (i=1; i<= nlstate ; i ++) {
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       printf(" Error in movingaverage mobilav=%d\n",mobilav);         else fprintf(ficgp," \%%*lf (\%%*lf)");
     }       }
   }       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 ++) {
   stepsize=(int) (stepm+YEARM-1)/YEARM;         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
   if (stepm<=12) stepsize=1;         else fprintf(ficgp," \%%*lf (\%%*lf)");
   if(estepm < stepm){       }  
     printf ("Problem %d lower than %d\n",estepm, stepm);       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));
   }     }
   else  hstepm=estepm;       }
     /*2 eme*/
   hstepm=hstepm/stepm;    
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and    for (k1=1; k1<= m ; k1 ++) {
                                fractional in yp1 */      fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
   anprojmean=yp;      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
   yp2=modf((yp1*12),&yp);     
   mprojmean=yp;      for (i=1; i<= nlstate+1 ; i ++) {
   yp1=modf((yp2*30.5),&yp);        k=2*i;
   jprojmean=yp;        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
   if(jprojmean==0) jprojmean=1;        for (j=1; j<= nlstate+1 ; j ++) {
   if(mprojmean==0) jprojmean=1;          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
           else fprintf(ficgp," \%%*lf (\%%*lf)");
   i1=cptcoveff;        }  
   if (cptcovn < 1){i1=1;}        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
           else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);         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 ++) {
   fprintf(ficresf,"#****** Routine prevforecast **\n");          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
           else fprintf(ficgp," \%%*lf (\%%*lf)");
 /*            if (h==(int)(YEARM*yearp)){ */        }  
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){        fprintf(ficgp,"\" t\"\" w l 0,");
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
       k=k+1;        for (j=1; j<= nlstate+1 ; j ++) {
       fprintf(ficresf,"\n#******");          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       for(j=1;j<=cptcoveff;j++) {          else fprintf(ficgp," \%%*lf (\%%*lf)");
         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]]);        }  
       }        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
       fprintf(ficresf,"******\n");        else fprintf(ficgp,"\" t\"\" w l 0,");
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");      }
       for(j=1; j<=nlstate+ndeath;j++){     }
         for(i=1; i<=nlstate;i++)                 
           fprintf(ficresf," p%d%d",i,j);    /*3eme*/
         fprintf(ficresf," p.%d",j);   
       }    for (k1=1; k1<= m ; k1 ++) {
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {       for (cpt=1; cpt<= nlstate ; cpt ++) {
         fprintf(ficresf,"\n");        /*       k=2+nlstate*(2*cpt-2); */
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);           k=2+(nlstate+1)*(cpt-1);
         fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
         for (agec=fage; agec>=(ageminpar-1); agec--){         fprintf(ficgp,"set ter png small\n\
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);   set size 0.65,0.65\n\
           nhstepm = nhstepm/hstepm;   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);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
           oldm=oldms;savm=savms;          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);            fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
           for (h=0; h<=nhstepm; h++){          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
             if (h*hstepm/YEARM*stepm ==yearp) {          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
               fprintf(ficresf,"\n");         
               for(j=1;j<=cptcoveff;j++)         */
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        for (i=1; i< nlstate ; i ++) {
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);          fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
             }           /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/
             for(j=1; j<=nlstate+ndeath;j++) {         
               ppij=0.;        }
               for(i=1; i<=nlstate;i++) {        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                 if (mobilav==1)       }
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];    }
                 else {   
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];    /* CV preval stable (period) */
                 }    for (k1=1; k1<= m ; k1 ++) {
                 if (h*hstepm/YEARM*stepm== yearp) {      for (cpt=1; cpt<=nlstate ; cpt ++) {
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);        k=3;
                 }        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
               } /* end i */        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
               if (h*hstepm/YEARM*stepm==yearp) {  set ter png small\nset size 0.65,0.65\n\
                 fprintf(ficresf," %.3f", ppij);  unset log y\n\
               }  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
             }/* end j */       
           } /* end h */        for (i=1; i< nlstate ; i ++)
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          fprintf(ficgp,"+$%d",k+i+1);
         } /* end agec */        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
       } /* end yearp */       
     } /* end cptcod */        l=3+(nlstate+ndeath)*cpt;
   } /* end  cptcov */        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
                for (i=1; i< nlstate ; i ++) {
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          l=3+(nlstate+ndeath)*cpt;
           fprintf(ficgp,"+$%d",l+i+1);
   fclose(ficresf);        }
 }        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
       }
 /************** Forecasting *****not tested NB*************/    }  
 populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){   
       /* proba elementaires */
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;    for(i=1,jk=1; i <=nlstate; i++){
   int *popage;      for(k=1; k <=(nlstate+ndeath); k++){
   double calagedatem, agelim, kk1, kk2;        if (k != i) {
   double *popeffectif,*popcount;          for(j=1; j <=ncovmodel; j++){
   double ***p3mat,***tabpop,***tabpopprev;            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
   double ***mobaverage;            jk++;
   char filerespop[FILENAMELENGTH];            fprintf(ficgp,"\n");
           }
   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;  
        for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);       for(jk=1; jk <=m; jk++) {
            fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
            if (ng==2)
   strcpy(filerespop,"pop");            fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
   strcat(filerespop,fileres);         else
   if((ficrespop=fopen(filerespop,"w"))==NULL) {           fprintf(ficgp,"\nset title \"Probability\"\n");
     printf("Problem with forecast resultfile: %s\n", filerespop);         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);         i=1;
   }         for(k2=1; k2<=nlstate; k2++) {
   printf("Computing forecasting: result on file '%s' \n", filerespop);           k3=i;
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);           for(k=1; k<=(nlstate+ndeath); k++) {
              if (k != k2){
   if (cptcoveff==0) ncodemax[cptcoveff]=1;               if(ng==2)
                  fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
   if (mobilav!=0) {               else
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){               ij=1;
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);               for(j=3; j <=ncovmodel; j++) {
       printf(" Error in movingaverage mobilav=%d\n",mobilav);                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
     }                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
   }                   ij++;
                  }
   stepsize=(int) (stepm+YEARM-1)/YEARM;                 else
   if (stepm<=12) stepsize=1;                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                  }
   agelim=AGESUP;               fprintf(ficgp,")/(1");
                  
   hstepm=1;               for(k1=1; k1 <=nlstate; k1++){  
   hstepm=hstepm/stepm;                  fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                    ij=1;
   if (popforecast==1) {                 for(j=3; j <=ncovmodel; j++){
     if((ficpop=fopen(popfile,"r"))==NULL) {                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
       printf("Problem with population file : %s\n",popfile);exit(0);                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);                     ij++;
     }                    }
     popage=ivector(0,AGESUP);                   else
     popeffectif=vector(0,AGESUP);                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
     popcount=vector(0,AGESUP);                 }
                      fprintf(ficgp,")");
     i=1;                  }
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
     imx=i;               i=i+ncovmodel;
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];             }
   }           } /* end k */
          } /* end k2 */
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){       } /* end jk */
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){     } /* end ng */
       k=k+1;     fflush(ficgp);
       fprintf(ficrespop,"\n#******");  }  /* end gnuplot */
       for(j=1;j<=cptcoveff;j++) {  
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
       }  /*************** Moving average **************/
       fprintf(ficrespop,"******\n");  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
       fprintf(ficrespop,"# Age");  
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);    int i, cpt, cptcod;
       if (popforecast==1)  fprintf(ficrespop," [Population]");    int modcovmax =1;
           int mobilavrange, mob;
       for (cpt=0; cpt<=0;cpt++) {     double age;
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);     
             modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){                              a covariate has 2 modalities */
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);     if (cptcovn<1) modcovmax=1; /* At least 1 pass */
           nhstepm = nhstepm/hstepm;   
               if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      if(mobilav==1) mobilavrange=5; /* default */
           oldm=oldms;savm=savms;      else mobilavrange=mobilav;
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        for (age=bage; age<=fage; age++)
                 for (i=1; i<=nlstate;i++)
           for (h=0; h<=nhstepm; h++){          for (cptcod=1;cptcod<=modcovmax;cptcod++)
             if (h==(int) (calagedatem+YEARM*cpt)) {            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);      /* We keep the original values on the extreme ages bage, fage and for
             }          fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
             for(j=1; j<=nlstate+ndeath;j++) {         we use a 5 terms etc. until the borders are no more concerned.
               kk1=0.;kk2=0;      */
               for(i=1; i<=nlstate;i++) {                    for (mob=3;mob <=mobilavrange;mob=mob+2){
                 if (mobilav==1)         for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];          for (i=1; i<=nlstate;i++){
                 else {            for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                 }                for (cpt=1;cpt<=(mob-1)/2;cpt++){
               }                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
               if (h==(int)(calagedatem+12*cpt)){                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;                }
                   /*fprintf(ficrespop," %.3f", kk1);              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/            }
               }          }
             }        }/* end age */
             for(i=1; i<=nlstate;i++){      }/* end mob */
               kk1=0.;    }else return -1;
                 for(j=1; j<=nlstate;j++){    return 0;
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];   }/* End movingaverage */
                 }  
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];  
             }  /************** Forecasting ******************/
   prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)     /* proj1, year, month, day of starting projection
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);       agemin, agemax range of age
           }       dateprev1 dateprev2 range of dates during which prevalence is computed
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);       anproj2 year of en of projection (same day and month as proj1).
         }    */
       }    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
      int *popage;
   /******/    double agec; /* generic age */
     double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {     double *popeffectif,*popcount;
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);       double ***p3mat;
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){     double ***mobaverage;
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);     char fileresf[FILENAMELENGTH];
           nhstepm = nhstepm/hstepm;   
               agelim=AGESUP;
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
           oldm=oldms;savm=savms;   
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);      strcpy(fileresf,"f");
           for (h=0; h<=nhstepm; h++){    strcat(fileresf,fileres);
             if (h==(int) (calagedatem+YEARM*cpt)) {    if((ficresf=fopen(fileresf,"w"))==NULL) {
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);      printf("Problem with forecast resultfile: %s\n", fileresf);
             }       fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
             for(j=1; j<=nlstate+ndeath;j++) {    }
               kk1=0.;kk2=0;    printf("Computing forecasting: result on file '%s' \n", fileresf);
               for(i=1; i<=nlstate;i++) {                  fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];      
               }    if (cptcoveff==0) ncodemax[cptcoveff]=1;
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);          
             }    if (mobilav!=0) {
           }      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
         }        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
       }        printf(" Error in movingaverage mobilav=%d\n",mobilav);
    }       }
   }    }
    
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    stepsize=(int) (stepm+YEARM-1)/YEARM;
     if (stepm<=12) stepsize=1;
   if (popforecast==1) {    if(estepm < stepm){
     free_ivector(popage,0,AGESUP);      printf ("Problem %d lower than %d\n",estepm, stepm);
     free_vector(popeffectif,0,AGESUP);    }
     free_vector(popcount,0,AGESUP);    else  hstepm=estepm;  
   }  
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    hstepm=hstepm/stepm;
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
   fclose(ficrespop);                                 fractional in yp1 */
 } /* End of popforecast */    anprojmean=yp;
     yp2=modf((yp1*12),&yp);
 int fileappend(FILE *fichier, char *optionfich)    mprojmean=yp;
 {    yp1=modf((yp2*30.5),&yp);
   if((fichier=fopen(optionfich,"a"))==NULL) {    jprojmean=yp;
     printf("Problem with file: %s\n", optionfich);    if(jprojmean==0) jprojmean=1;
     fprintf(ficlog,"Problem with file: %s\n", optionfich);    if(mprojmean==0) jprojmean=1;
     return (0);  
   }    i1=cptcoveff;
   fflush(fichier);    if (cptcovn < 1){i1=1;}
   return (1);   
 }    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");
 /**************** function prwizard **********************/  
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)  /*            if (h==(int)(YEARM*yearp)){ */
 {    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
       for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   /* Wizard to print covariance matrix template */        k=k+1;
         fprintf(ficresf,"\n#******");
   char ca[32], cb[32], cc[32];        for(j=1;j<=cptcoveff;j++) {
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;          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]]);
   int numlinepar;        }
         fprintf(ficresf,"******\n");
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        for(j=1; j<=nlstate+ndeath;j++){
   for(i=1; i <=nlstate; i++){          for(i=1; i<=nlstate;i++)              
     jj=0;            fprintf(ficresf," p%d%d",i,j);
     for(j=1; j <=nlstate+ndeath; j++){          fprintf(ficresf," p.%d",j);
       if(j==i) continue;        }
       jj++;        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
       /*ca[0]= k+'a'-1;ca[1]='\0';*/          fprintf(ficresf,"\n");
       printf("%1d%1d",i,j);          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
       fprintf(ficparo,"%1d%1d",i,j);  
       for(k=1; k<=ncovmodel;k++){          for (agec=fage; agec>=(ageminpar-1); agec--){
         /*        printf(" %lf",param[i][j][k]); */            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
         /*        fprintf(ficparo," %lf",param[i][j][k]); */            nhstepm = nhstepm/hstepm;
         printf(" 0.");            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         fprintf(ficparo," 0.");            oldm=oldms;savm=savms;
       }            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
       printf("\n");         
       fprintf(ficparo,"\n");            for (h=0; h<=nhstepm; h++){
     }              if (h*hstepm/YEARM*stepm ==yearp) {
   }                fprintf(ficresf,"\n");
   printf("# Scales (for hessian or gradient estimation)\n");                for(j=1;j<=cptcoveff;j++)
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/                 fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
   for(i=1; i <=nlstate; i++){              }
     jj=0;              for(j=1; j<=nlstate+ndeath;j++) {
     for(j=1; j <=nlstate+ndeath; j++){                ppij=0.;
       if(j==i) continue;                for(i=1; i<=nlstate;i++) {
       jj++;                  if (mobilav==1)
       fprintf(ficparo,"%1d%1d",i,j);                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
       printf("%1d%1d",i,j);                  else {
       fflush(stdout);                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
       for(k=1; k<=ncovmodel;k++){                  }
         /*      printf(" %le",delti3[i][j][k]); */                  if (h*hstepm/YEARM*stepm== yearp) {
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
         printf(" 0.");                  }
         fprintf(ficparo," 0.");                } /* end i */
       }                if (h*hstepm/YEARM*stepm==yearp) {
       numlinepar++;                  fprintf(ficresf," %.3f", ppij);
       printf("\n");                }
       fprintf(ficparo,"\n");              }/* end j */
     }            } /* end h */
   }            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   printf("# Covariance matrix\n");          } /* end agec */
 /* # 121 Var(a12)\n\ */        } /* end yearp */
 /* # 122 Cov(b12,a12) Var(b12)\n\ */      } /* end cptcod */
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */    } /* end  cptcov */
 /* # 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\ */    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 /* # 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\ */    fclose(ficresf);
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */  }
   fflush(stdout);  
   fprintf(ficparo,"# Covariance matrix\n");  /************** Forecasting *****not tested NB*************/
   /* # 121 Var(a12)\n\ */  populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
   /* # 122 Cov(b12,a12) Var(b12)\n\ */   
   /* #   ...\n\ */    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */    int *popage;
       double calagedatem, agelim, kk1, kk2;
   for(itimes=1;itimes<=2;itimes++){    double *popeffectif,*popcount;
     jj=0;    double ***p3mat,***tabpop,***tabpopprev;
     for(i=1; i <=nlstate; i++){    double ***mobaverage;
       for(j=1; j <=nlstate+ndeath; j++){    char filerespop[FILENAMELENGTH];
         if(j==i) continue;  
         for(k=1; k<=ncovmodel;k++){    tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           jj++;    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           ca[0]= k+'a'-1;ca[1]='\0';    agelim=AGESUP;
           if(itimes==1){    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
             printf("#%1d%1d%d",i,j,k);   
             fprintf(ficparo,"#%1d%1d%d",i,j,k);    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
           }else{   
             printf("%1d%1d%d",i,j,k);   
             fprintf(ficparo,"%1d%1d%d",i,j,k);    strcpy(filerespop,"pop");
             /*  printf(" %.5le",matcov[i][j]); */    strcat(filerespop,fileres);
           }    if((ficrespop=fopen(filerespop,"w"))==NULL) {
           ll=0;      printf("Problem with forecast resultfile: %s\n", filerespop);
           for(li=1;li <=nlstate; li++){      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
             for(lj=1;lj <=nlstate+ndeath; lj++){    }
               if(lj==li) continue;    printf("Computing forecasting: result on file '%s' \n", filerespop);
               for(lk=1;lk<=ncovmodel;lk++){    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                 ll++;  
                 if(ll<=jj){    if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   cb[0]= lk +'a'-1;cb[1]='\0';  
                   if(ll<jj){    if (mobilav!=0) {
                     if(itimes==1){      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                     }else{        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                       printf(" 0.");      }
                       fprintf(ficparo," 0.");    }
                     }  
                   }else{    stepsize=(int) (stepm+YEARM-1)/YEARM;
                     if(itimes==1){    if (stepm<=12) stepsize=1;
                       printf(" Var(%s%1d%1d)",ca,i,j);   
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);    agelim=AGESUP;
                     }else{   
                       printf(" 0.");    hstepm=1;
                       fprintf(ficparo," 0.");    hstepm=hstepm/stepm;
                     }   
                   }    if (popforecast==1) {
                 }      if((ficpop=fopen(popfile,"r"))==NULL) {
               } /* end lk */        printf("Problem with population file : %s\n",popfile);exit(0);
             } /* end lj */        fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
           } /* end li */      }
           printf("\n");      popage=ivector(0,AGESUP);
           fprintf(ficparo,"\n");      popeffectif=vector(0,AGESUP);
           numlinepar++;      popcount=vector(0,AGESUP);
         } /* end k*/     
       } /*end j */      i=1;  
     } /* end i */      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
   } /* end itimes */     
       imx=i;
 } /* end of prwizard */      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 /******************* Gompertz Likelihood ******************************/    }
 double gompertz(double x[])  
 {     for(cptcov=1,k=0;cptcov<=i2;cptcov++){
   double A,B,L=0.0,sump=0.,num=0.;     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
   int i,n=0; /* n is the size of the sample */        k=k+1;
         fprintf(ficrespop,"\n#******");
   for (i=0;i<=imx-1 ; i++) {        for(j=1;j<=cptcoveff;j++) {
     sump=sump+weight[i];          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     /*    sump=sump+1;*/        }
     num=num+1;        fprintf(ficrespop,"******\n");
   }        fprintf(ficrespop,"# Age");
          for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
          if (popforecast==1)  fprintf(ficrespop," [Population]");
   /* for (i=0; i<=imx; i++)        
      if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/        for (cpt=0; cpt<=0;cpt++) {
           fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   for (i=1;i<=imx ; i++)         
     {          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
       if (cens[i] == 1 && wav[i]>1)            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));            nhstepm = nhstepm/hstepm;
                  
       if (cens[i] == 0 && wav[i]>1)            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))            oldm=oldms;savm=savms;
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);              hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                
       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */            for (h=0; h<=nhstepm; h++){
       if (wav[i] > 1 ) { /* ??? */              if (h==(int) (calagedatem+YEARM*cpt)) {
         L=L+A*weight[i];                fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
         /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/              }
       }              for(j=1; j<=nlstate+ndeath;j++) {
     }                kk1=0.;kk2=0;
                 for(i=1; i<=nlstate;i++) {              
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/                  if (mobilav==1)
                      kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
   return -2*L*num/sump;                  else {
 }                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   }
 /******************* Printing html file ***********/                }
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \                if (h==(int)(calagedatem+12*cpt)){
                   int lastpass, int stepm, int weightopt, char model[],\                  tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   int imx,  double p[],double **matcov,double agemortsup){                    /*fprintf(ficrespop," %.3f", kk1);
   int i,k;                      if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                 }
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");              }
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);              for(i=1; i<=nlstate;i++){
   for (i=1;i<=2;i++)                 kk1=0.;
     fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));                  for(j=1; j<=nlstate;j++){
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
   fprintf(fichtm,"</ul>");                  }
                     tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");              }
   
  fprintf(fichtm,"\nAge   l<inf>x</inf>     q<inf>x</inf> d(x,x+1)    L<inf>x</inf>     T<inf>x</inf>     e<infx</inf><br>");              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
                 fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
  for (k=agegomp;k<(agemortsup-2);k++)             }
    fprintf(fichtm,"%d %.0lf %lf %.0lf %.0lf %.0lf %lf<br>\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           }
          }
   fflush(fichtm);   
 }    /******/
   
 /******************* Gnuplot file **************/        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){          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--){
   char dirfileres[132],optfileres[132];            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;            nhstepm = nhstepm/hstepm;
   int ng;           
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             oldm=oldms;savm=savms;
   /*#ifdef windows */            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   fprintf(ficgp,"cd \"%s\" \n",pathc);            for (h=0; h<=nhstepm; h++){
     /*#endif */              if (h==(int) (calagedatem+YEARM*cpt)) {
                 fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
               }
   strcpy(dirfileres,optionfilefiname);              for(j=1; j<=nlstate+ndeath;j++) {
   strcpy(optfileres,"vpl");                kk1=0.;kk2=0;
   fprintf(ficgp,"set out \"graphmort.png\"\n ");                 for(i=1; i<=nlstate;i++) {              
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");                   kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
   fprintf(ficgp, "set ter png small\n set log y\n");                 }
   fprintf(ficgp, "set size 0.65,0.65\n");                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);              }
             }
 }             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           }
         }
      }
     }
 /***********************************************/   
 /**************** Main Program *****************/    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 /***********************************************/  
     if (popforecast==1) {
 int main(int argc, char *argv[])      free_ivector(popage,0,AGESUP);
 {      free_vector(popeffectif,0,AGESUP);
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);      free_vector(popcount,0,AGESUP);
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;    }
   int linei, month, year,iout;    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   int jj, ll, li, lj, lk, imk;    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   int numlinepar=0; /* Current linenumber of parameter file */    fclose(ficrespop);
   int itimes;  } /* End of popforecast */
   int NDIM=2;  
   int fileappend(FILE *fichier, char *optionfich)
   char ca[32], cb[32], cc[32];  {
   char dummy[]="                         ";    if((fichier=fopen(optionfich,"a"))==NULL) {
   /*  FILE *fichtm; *//* Html File */      printf("Problem with file: %s\n", optionfich);
   /* FILE *ficgp;*/ /*Gnuplot File */      fprintf(ficlog,"Problem with file: %s\n", optionfich);
   struct stat info;      return (0);
   double agedeb, agefin,hf;    }
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;    fflush(fichier);
     return (1);
   double fret;  }
   double **xi,tmp,delta;  
   
   double dum; /* Dummy variable */  /**************** function prwizard **********************/
   double ***p3mat;  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
   double ***mobaverage;  {
   int *indx;  
   char line[MAXLINE], linepar[MAXLINE];    /* Wizard to print covariance matrix template */
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];  
   char pathr[MAXLINE], pathimach[MAXLINE];     char ca[32], cb[32], cc[32];
   int firstobs=1, lastobs=10;    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
   int sdeb, sfin; /* Status at beginning and end */    int numlinepar;
   int c,  h , cpt,l;  
   int ju,jl, mi;    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;     for(i=1; i <=nlstate; i++){
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */      jj=0;
   int mobilav=0,popforecast=0;      for(j=1; j <=nlstate+ndeath; j++){
   int hstepm, nhstepm;        if(j==i) continue;
   int agemortsup;        jj++;
   float  sumlpop=0.;        /*ca[0]= k+'a'-1;ca[1]='\0';*/
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;        printf("%1d%1d",i,j);
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;        fprintf(ficparo,"%1d%1d",i,j);
         for(k=1; k<=ncovmodel;k++){
   double bage, fage, age, agelim, agebase;          /*        printf(" %lf",param[i][j][k]); */
   double ftolpl=FTOL;          /*        fprintf(ficparo," %lf",param[i][j][k]); */
   double **prlim;          printf(" 0.");
   double *severity;          fprintf(ficparo," 0.");
   double ***param; /* Matrix of parameters */        }
   double  *p;        printf("\n");
   double **matcov; /* Matrix of covariance */        fprintf(ficparo,"\n");
   double ***delti3; /* Scale */      }
   double *delti; /* Scale */    }
   double ***eij, ***vareij;    printf("# Scales (for hessian or gradient estimation)\n");
   double **varpl; /* Variances of prevalence limits by age */    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
   double *epj, vepp;    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
   double kk1, kk2;    for(i=1; i <=nlstate; i++){
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;      jj=0;
   double **ximort;      for(j=1; j <=nlstate+ndeath; j++){
   char *alph[]={"a","a","b","c","d","e"}, str[4];        if(j==i) continue;
   int *dcwave;        jj++;
         fprintf(ficparo,"%1d%1d",i,j);
   char z[1]="c", occ;        printf("%1d%1d",i,j);
         fflush(stdout);
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];        for(k=1; k<=ncovmodel;k++){
   char strstart[80], *strt, strtend[80];          /*      printf(" %le",delti3[i][j][k]); */
   char *stratrunc;          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
   int lstra;          printf(" 0.");
           fprintf(ficparo," 0.");
   long total_usecs;        }
          numlinepar++;
 /*   setlocale (LC_ALL, ""); */        printf("\n");
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */        fprintf(ficparo,"\n");
 /*   textdomain (PACKAGE); */      }
 /*   setlocale (LC_CTYPE, ""); */    }
 /*   setlocale (LC_MESSAGES, ""); */    printf("# Covariance matrix\n");
   /* # 121 Var(a12)\n\ */
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */  /* # 122 Cov(b12,a12) Var(b12)\n\ */
   (void) gettimeofday(&start_time,&tzp);  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
   curr_time=start_time;  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
   tm = *localtime(&start_time.tv_sec);  /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
   tmg = *gmtime(&start_time.tv_sec);  /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
   strcpy(strstart,asctime(&tm));  /* # 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("Localtime (at start)=%s",strstart); */    fflush(stdout);
 /*  tp.tv_sec = tp.tv_sec +86400; */    fprintf(ficparo,"# Covariance matrix\n");
 /*  tm = *localtime(&start_time.tv_sec); */    /* # 121 Var(a12)\n\ */
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */    /* # 122 Cov(b12,a12) Var(b12)\n\ */
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */    /* #   ...\n\ */
 /*   tmg.tm_hour=tmg.tm_hour + 1; */    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 /*   tp.tv_sec = mktime(&tmg); */   
 /*   strt=asctime(&tmg); */    for(itimes=1;itimes<=2;itimes++){
 /*   printf("Time(after) =%s",strstart);  */      jj=0;
 /*  (void) time (&time_value);      for(i=1; i <=nlstate; i++){
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);        for(j=1; j <=nlstate+ndeath; j++){
 *  tm = *localtime(&time_value);          if(j==i) continue;
 *  strstart=asctime(&tm);          for(k=1; k<=ncovmodel;k++){
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);             jj++;
 */            ca[0]= k+'a'-1;ca[1]='\0';
             if(itimes==1){
   nberr=0; /* Number of errors and warnings */              printf("#%1d%1d%d",i,j,k);
   nbwarn=0;              fprintf(ficparo,"#%1d%1d%d",i,j,k);
   getcwd(pathcd, size);            }else{
               printf("%1d%1d%d",i,j,k);
   printf("\n%s\n%s",version,fullversion);              fprintf(ficparo,"%1d%1d%d",i,j,k);
   if(argc <=1){              /*  printf(" %.5le",matcov[i][j]); */
     printf("\nEnter the parameter file name: ");            }
     scanf("%s",pathtot);            ll=0;
   }            for(li=1;li <=nlstate; li++){
   else{              for(lj=1;lj <=nlstate+ndeath; lj++){
     strcpy(pathtot,argv[1]);                if(lj==li) continue;
   }                for(lk=1;lk<=ncovmodel;lk++){
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/                  ll++;
   /*cygwin_split_path(pathtot,path,optionfile);                  if(ll<=jj){
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/                    cb[0]= lk +'a'-1;cb[1]='\0';
   /* cutv(path,optionfile,pathtot,'\\');*/                    if(ll<jj){
                       if(itimes==1){
   /* Split argv[0], imach program to get pathimach */                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);                      }else{
   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);                        printf(" 0.");
  /*   strcpy(pathimach,argv[0]); */                        fprintf(ficparo," 0.");
   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */                      }
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);                    }else{
   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);                      if(itimes==1){
   chdir(path);                        printf(" Var(%s%1d%1d)",ca,i,j);
   strcpy(command,"mkdir ");                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
   strcat(command,optionfilefiname);                      }else{
   if((outcmd=system(command)) != 0){                        printf(" 0.");
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);                        fprintf(ficparo," 0.");
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */                      }
     /* fclose(ficlog); */                    }
 /*     exit(1); */                  }
   }                } /* end lk */
 /*   if((imk=mkdir(optionfilefiname))<0){ */              } /* end lj */
 /*     perror("mkdir"); */            } /* end li */
 /*   } */            printf("\n");
             fprintf(ficparo,"\n");
   /*-------- arguments in the command line --------*/            numlinepar++;
           } /* end k*/
   /* Log file */        } /*end j */
   strcat(filelog, optionfilefiname);      } /* end i */
   strcat(filelog,".log");    /* */    } /* end itimes */
   if((ficlog=fopen(filelog,"w"))==NULL)    {  
     printf("Problem with logfile %s\n",filelog);  } /* end of prwizard */
     goto end;  /******************* Gompertz Likelihood ******************************/
   }  double gompertz(double x[])
   fprintf(ficlog,"Log filename:%s\n",filelog);  {
   fprintf(ficlog,"\n%s\n%s",version,fullversion);    double A,B,L=0.0,sump=0.,num=0.;
   fprintf(ficlog,"\nEnter the parameter file name: \n");    int i,n=0; /* n is the size of the sample */
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\  
  path=%s \n\    for (i=0;i<=imx-1 ; i++) {
  optionfile=%s\n\      sump=sump+weight[i];
  optionfilext=%s\n\      /*    sump=sump+1;*/
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);      num=num+1;
     }
   printf("Local time (at start):%s",strstart);   
   fprintf(ficlog,"Local time (at start): %s",strstart);   
   fflush(ficlog);    /* for (i=0; i<=imx; i++)
 /*   (void) gettimeofday(&curr_time,&tzp); */       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]);*/
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */  
     for (i=1;i<=imx ; i++)
   /* */      {
   strcpy(fileres,"r");        if (cens[i] == 1 && wav[i]>1)
   strcat(fileres, optionfilefiname);          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
   strcat(fileres,".txt");    /* Other files have txt extension */       
         if (cens[i] == 0 && wav[i]>1)
   /*---------arguments file --------*/          A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
   if((ficpar=fopen(optionfile,"r"))==NULL)    {       
     printf("Problem with optionfile %s\n",optionfile);        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);        if (wav[i] > 1 ) { /* ??? */
     fflush(ficlog);          L=L+A*weight[i];
     goto end;          /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
   }        }
       }
   
    /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
   strcpy(filereso,"o");   
   strcat(filereso,fileres);    return -2*L*num/sump;
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */  }
     printf("Problem with Output resultfile: %s\n", filereso);  
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);  /******************* Printing html file ***********/
     fflush(ficlog);  void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
     goto end;                    int lastpass, int stepm, int weightopt, char model[],\
   }                    int imx,  double p[],double **matcov,double agemortsup){
     int i,k;
   /* Reads comments: lines beginning with '#' */  
   numlinepar=0;    fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
   while((c=getc(ficpar))=='#' && c!= EOF){    fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
     ungetc(c,ficpar);    for (i=1;i<=2;i++)
     fgets(line, MAXLINE, ficpar);      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]));
     numlinepar++;    fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
     puts(line);    fprintf(fichtm,"</ul>");
     fputs(line,ficparo);  
     fputs(line,ficlog);  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
   }  
   ungetc(c,ficpar);   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>");
   
   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);   for (k=agegomp;k<(agemortsup-2);k++)
   numlinepar++;     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]);
   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);  
   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);   
   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    fflush(fichtm);
   fflush(ficlog);  }
   while((c=getc(ficpar))=='#' && c!= EOF){  
     ungetc(c,ficpar);  /******************* Gnuplot file **************/
     fgets(line, MAXLINE, ficpar);  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
     numlinepar++;  
     puts(line);    char dirfileres[132],optfileres[132];
     fputs(line,ficparo);    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     fputs(line,ficlog);    int ng;
   }  
   ungetc(c,ficpar);  
     /*#ifdef windows */
        fprintf(ficgp,"cd \"%s\" \n",pathc);
   covar=matrix(0,NCOVMAX,1,n);       /*#endif */
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/  
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;  
     strcpy(dirfileres,optionfilefiname);
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */    strcpy(optfileres,"vpl");
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */    fprintf(ficgp,"set out \"graphmort.png\"\n ");
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
     fprintf(ficgp, "set ter png small\n set log y\n");
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    fprintf(ficgp, "set size 0.65,0.65\n");
   delti=delti3[1][1];    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/  
   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);  
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);   
     fclose (ficparo);  
     fclose (ficlog);  /***********************************************/
     exit(0);  /**************** Main Program *****************/
   }  /***********************************************/
   else if(mle==-3) {  
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);  int main(int argc, char *argv[])
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);  {
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
     matcov=matrix(1,npar,1,npar);    int linei, month, year,iout;
   }    int jj, ll, li, lj, lk, imk;
   else{    int numlinepar=0; /* Current linenumber of parameter file */
     /* Read guess parameters */    int itimes;
     /* Reads comments: lines beginning with '#' */    int NDIM=2;
     while((c=getc(ficpar))=='#' && c!= EOF){  
       ungetc(c,ficpar);    char ca[32], cb[32], cc[32];
       fgets(line, MAXLINE, ficpar);    char dummy[]="                         ";
       numlinepar++;    /*  FILE *fichtm; *//* Html File */
       puts(line);    /* FILE *ficgp;*/ /*Gnuplot File */
       fputs(line,ficparo);    struct stat info;
       fputs(line,ficlog);    double agedeb, agefin,hf;
     }    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
     ungetc(c,ficpar);  
         double fret;
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    double **xi,tmp,delta;
     for(i=1; i <=nlstate; i++){  
       j=0;    double dum; /* Dummy variable */
       for(jj=1; jj <=nlstate+ndeath; jj++){    double ***p3mat;
         if(jj==i) continue;    double ***mobaverage;
         j++;    int *indx;
         fscanf(ficpar,"%1d%1d",&i1,&j1);    char line[MAXLINE], linepar[MAXLINE];
         if ((i1 != i) && (j1 != j)){    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);    char pathr[MAXLINE], pathimach[MAXLINE];
           exit(1);    char **bp, *tok, *val; /* pathtot */
         }    int firstobs=1, lastobs=10;
         fprintf(ficparo,"%1d%1d",i1,j1);    int sdeb, sfin; /* Status at beginning and end */
         if(mle==1)    int c,  h , cpt,l;
           printf("%1d%1d",i,j);    int ju,jl, mi;
         fprintf(ficlog,"%1d%1d",i,j);    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
         for(k=1; k<=ncovmodel;k++){    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
           fscanf(ficpar," %lf",&param[i][j][k]);    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
           if(mle==1){    int mobilav=0,popforecast=0;
             printf(" %lf",param[i][j][k]);    int hstepm, nhstepm;
             fprintf(ficlog," %lf",param[i][j][k]);    int agemortsup;
           }    float  sumlpop=0.;
           else    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
             fprintf(ficlog," %lf",param[i][j][k]);    double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
           fprintf(ficparo," %lf",param[i][j][k]);  
         }    double bage, fage, age, agelim, agebase;
         fscanf(ficpar,"\n");    double ftolpl=FTOL;
         numlinepar++;    double **prlim;
         if(mle==1)    double *severity;
           printf("\n");    double ***param; /* Matrix of parameters */
         fprintf(ficlog,"\n");    double  *p;
         fprintf(ficparo,"\n");    double **matcov; /* Matrix of covariance */
       }    double ***delti3; /* Scale */
     }      double *delti; /* Scale */
     fflush(ficlog);    double ***eij, ***vareij;
     double **varpl; /* Variances of prevalence limits by age */
     p=param[1][1];    double *epj, vepp;
         double kk1, kk2;
     /* Reads comments: lines beginning with '#' */    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
     while((c=getc(ficpar))=='#' && c!= EOF){    double **ximort;
       ungetc(c,ficpar);    char *alph[]={"a","a","b","c","d","e"}, str[4];
       fgets(line, MAXLINE, ficpar);    int *dcwave;
       numlinepar++;  
       puts(line);    char z[1]="c", occ;
       fputs(line,ficparo);  
       fputs(line,ficlog);    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
     }    char  *strt, strtend[80];
     ungetc(c,ficpar);    char *stratrunc;
     int lstra;
     for(i=1; i <=nlstate; i++){  
       for(j=1; j <=nlstate+ndeath-1; j++){    long total_usecs;
         fscanf(ficpar,"%1d%1d",&i1,&j1);   
         if ((i1-i)*(j1-j)!=0){  /*   setlocale (LC_ALL, ""); */
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
           exit(1);  /*   textdomain (PACKAGE); */
         }  /*   setlocale (LC_CTYPE, ""); */
         printf("%1d%1d",i,j);  /*   setlocale (LC_MESSAGES, ""); */
         fprintf(ficparo,"%1d%1d",i1,j1);  
         fprintf(ficlog,"%1d%1d",i1,j1);    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
         for(k=1; k<=ncovmodel;k++){    (void) gettimeofday(&start_time,&tzp);
           fscanf(ficpar,"%le",&delti3[i][j][k]);    curr_time=start_time;
           printf(" %le",delti3[i][j][k]);    tm = *localtime(&start_time.tv_sec);
           fprintf(ficparo," %le",delti3[i][j][k]);    tmg = *gmtime(&start_time.tv_sec);
           fprintf(ficlog," %le",delti3[i][j][k]);    strcpy(strstart,asctime(&tm));
         }  
         fscanf(ficpar,"\n");  /*  printf("Localtime (at start)=%s",strstart); */
         numlinepar++;  /*  tp.tv_sec = tp.tv_sec +86400; */
         printf("\n");  /*  tm = *localtime(&start_time.tv_sec); */
         fprintf(ficparo,"\n");  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
         fprintf(ficlog,"\n");  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
       }  /*   tmg.tm_hour=tmg.tm_hour + 1; */
     }  /*   tp.tv_sec = mktime(&tmg); */
     fflush(ficlog);  /*   strt=asctime(&tmg); */
   /*   printf("Time(after) =%s",strstart);  */
     delti=delti3[1][1];  /*  (void) time (&time_value);
   *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
   *  tm = *localtime(&time_value);
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */  *  strstart=asctime(&tm);
     *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
     /* Reads comments: lines beginning with '#' */  */
     while((c=getc(ficpar))=='#' && c!= EOF){  
       ungetc(c,ficpar);    nberr=0; /* Number of errors and warnings */
       fgets(line, MAXLINE, ficpar);    nbwarn=0;
       numlinepar++;    getcwd(pathcd, size);
       puts(line);  
       fputs(line,ficparo);    printf("\n%s\n%s",version,fullversion);
       fputs(line,ficlog);    if(argc <=1){
     }      printf("\nEnter the parameter file name: ");
     ungetc(c,ficpar);      fgets(pathr,FILENAMELENGTH,stdin);
         i=strlen(pathr);
     matcov=matrix(1,npar,1,npar);      if(pathr[i-1]=='\n')
     for(i=1; i <=npar; i++){        pathr[i-1]='\0';
       fscanf(ficpar,"%s",&str);     for (tok = pathr; tok != NULL; ){
       if(mle==1)        printf("Pathr |%s|\n",pathr);
         printf("%s",str);        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
       fprintf(ficlog,"%s",str);        printf("val= |%s| pathr=%s\n",val,pathr);
       fprintf(ficparo,"%s",str);        strcpy (pathtot, val);
       for(j=1; j <=i; j++){        if(pathr[0] == '\0') break; /* Dirty */
         fscanf(ficpar," %le",&matcov[i][j]);      }
         if(mle==1){    }
           printf(" %.5le",matcov[i][j]);    else{
         }      strcpy(pathtot,argv[1]);
         fprintf(ficlog," %.5le",matcov[i][j]);    }
         fprintf(ficparo," %.5le",matcov[i][j]);    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
       }    /*cygwin_split_path(pathtot,path,optionfile);
       fscanf(ficpar,"\n");      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
       numlinepar++;    /* cutv(path,optionfile,pathtot,'\\');*/
       if(mle==1)  
         printf("\n");    /* Split argv[0], imach program to get pathimach */
       fprintf(ficlog,"\n");    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
       fprintf(ficparo,"\n");    split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
     }    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
     for(i=1; i <=npar; i++)   /*   strcpy(pathimach,argv[0]); */
       for(j=i+1;j<=npar;j++)    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
         matcov[i][j]=matcov[j][i];    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
         printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
     if(mle==1)    chdir(path); /* Can be a relative path */
       printf("\n");    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
     fprintf(ficlog,"\n");      printf("Current directory %s!\n",pathcd);
         strcpy(command,"mkdir ");
     fflush(ficlog);    strcat(command,optionfilefiname);
         if((outcmd=system(command)) != 0){
     /*-------- Rewriting parameter file ----------*/      printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
     strcpy(rfileres,"r");    /* "Rparameterfile */      /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/      /* fclose(ficlog); */
     strcat(rfileres,".");    /* */  /*     exit(1); */
     strcat(rfileres,optionfilext);    /* Other files have txt extension */    }
     if((ficres =fopen(rfileres,"w"))==NULL) {  /*   if((imk=mkdir(optionfilefiname))<0){ */
       printf("Problem writing new parameter file: %s\n", fileres);goto end;  /*     perror("mkdir"); */
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;  /*   } */
     }  
     fprintf(ficres,"#%s\n",version);    /*-------- arguments in the command line --------*/
   }    /* End of mle != -3 */  
     /* Log file */
   /*-------- data file ----------*/    strcat(filelog, optionfilefiname);
   if((fic=fopen(datafile,"r"))==NULL)    {    strcat(filelog,".log");    /* */
     printf("Problem with datafile: %s\n", datafile);goto end;    if((ficlog=fopen(filelog,"w"))==NULL)    {
     fprintf(ficlog,"Problem with datafile: %s\n", datafile);goto end;      printf("Problem with logfile %s\n",filelog);
   }      goto end;
     }
   n= lastobs;    fprintf(ficlog,"Log filename:%s\n",filelog);
   severity = vector(1,maxwav);    fprintf(ficlog,"\n%s\n%s",version,fullversion);
   outcome=imatrix(1,maxwav+1,1,n);    fprintf(ficlog,"\nEnter the parameter file name: \n");
   num=lvector(1,n);    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
   moisnais=vector(1,n);   path=%s \n\
   annais=vector(1,n);   optionfile=%s\n\
   moisdc=vector(1,n);   optionfilext=%s\n\
   andc=vector(1,n);   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
   agedc=vector(1,n);  
   cod=ivector(1,n);    printf("Local time (at start):%s",strstart);
   weight=vector(1,n);    fprintf(ficlog,"Local time (at start): %s",strstart);
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */    fflush(ficlog);
   mint=matrix(1,maxwav,1,n);  /*   (void) gettimeofday(&curr_time,&tzp); */
   anint=matrix(1,maxwav,1,n);  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   s=imatrix(1,maxwav+1,1,n);  
   tab=ivector(1,NCOVMAX);    /* */
   ncodemax=ivector(1,8);    strcpy(fileres,"r");
     strcat(fileres, optionfilefiname);
   i=1;    strcat(fileres,".txt");    /* Other files have txt extension */
   linei=0;  
   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {    /*---------arguments file --------*/
     linei=linei+1;  
     for(j=strlen(line); j>=0;j--){  /* Untabifies line */    if((ficpar=fopen(optionfile,"r"))==NULL)    {
       if(line[j] == '\t')      printf("Problem with optionfile %s\n",optionfile);
         line[j] = ' ';      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
     }      fflush(ficlog);
     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){      goto end;
       ;    }
     };  
     line[j+1]=0;  /* Trims blanks at end of line */  
     if(line[0]=='#'){  
       fprintf(ficlog,"Comment line\n%s\n",line);    strcpy(filereso,"o");
       printf("Comment line\n%s\n",line);    strcat(filereso,fileres);
       continue;    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
     }      printf("Problem with Output resultfile: %s\n", filereso);
       fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
     for (j=maxwav;j>=1;j--){      fflush(ficlog);
       cutv(stra, strb,line,' ');       goto end;
       errno=0;    }
       lval=strtol(strb,&endptr,10);   
       /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/    /* Reads comments: lines beginning with '#' */
       if( strb[0]=='\0' || (*endptr != '\0')){    numlinepar=0;
         printf("Error reading data around '%d' at line number %d %s for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);    while((c=getc(ficpar))=='#' && c!= EOF){
         exit(1);      ungetc(c,ficpar);
       }      fgets(line, MAXLINE, ficpar);
       s[j][i]=lval;      numlinepar++;
             puts(line);
       strcpy(line,stra);      fputs(line,ficparo);
       cutv(stra, strb,line,' ');      fputs(line,ficlog);
       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){    }
       }    ungetc(c,ficpar);
       else  if(iout=sscanf(strb,"%s.") != 0){  
         month=99;    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);
         year=9999;    numlinepar++;
       }else{    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);
         printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);    fprintf(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);
         exit(1);    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);
       anint[j][i]= (double) year;     while((c=getc(ficpar))=='#' && c!= EOF){
       mint[j][i]= (double)month;       ungetc(c,ficpar);
       strcpy(line,stra);      fgets(line, MAXLINE, ficpar);
     } /* ENd Waves */      numlinepar++;
           puts(line);
     cutv(stra, strb,line,' ');       fputs(line,ficparo);
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){      fputs(line,ficlog);
     }    }
     else  if(iout=sscanf(strb,"%s.",dummy) != 0){    ungetc(c,ficpar);
       month=99;  
       year=9999;     
     }else{    covar=matrix(0,NCOVMAX,1,n);
       printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
       exit(1);    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
     }  
     andc[i]=(double) year;     ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
     moisdc[i]=(double) month;     nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
     strcpy(line,stra);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
       
     cutv(stra, strb,line,' ');     delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){    delti=delti3[1][1];
     }    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
     else  if(iout=sscanf(strb,"%s.") != 0){    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
       month=99;      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
       year=9999;      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
     }else{      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
       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);      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
       exit(1);      fclose (ficparo);
     }      fclose (ficlog);
     annais[i]=(double)(year);      goto end;
     moisnais[i]=(double)(month);       exit(0);
     strcpy(line,stra);    }
         else if(mle==-3) {
     cutv(stra, strb,line,' ');       prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
     errno=0;      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     lval=strtol(strb,&endptr,10);       fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     if( strb[0]=='\0' || (*endptr != '\0')){      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
       printf("Error reading data around '%d' at line number %ld %s for individual %d\nShould be a weight.  Exiting.\n",lval, i,line,linei);      matcov=matrix(1,npar,1,npar);
       exit(1);    }
     }    else{
     weight[i]=(double)(lval);       /* Read guess parameters */
     strcpy(line,stra);      /* Reads comments: lines beginning with '#' */
           while((c=getc(ficpar))=='#' && c!= EOF){
     for (j=ncovcol;j>=1;j--){        ungetc(c,ficpar);
       cutv(stra, strb,line,' ');         fgets(line, MAXLINE, ficpar);
       errno=0;        numlinepar++;
       lval=strtol(strb,&endptr,10);         puts(line);
       if( strb[0]=='\0' || (*endptr != '\0')){        fputs(line,ficparo);
         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);        fputs(line,ficlog);
         exit(1);      }
       }      ungetc(c,ficpar);
       if(lval <-1 || lval >1){     
         printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a value of the %d covar (meaning 0 for the reference or 1. IMaCh does not build design variables, do it your self).  Exiting.\n",lval,linei, i,line,j);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         exit(1);      for(i=1; i <=nlstate; i++){
       }        j=0;
       covar[j][i]=(double)(lval);        for(jj=1; jj <=nlstate+ndeath; jj++){
       strcpy(line,stra);          if(jj==i) continue;
     }           j++;
     lstra=strlen(stra);          fscanf(ficpar,"%1d%1d",&i1,&j1);
               if ((i1 != i) && (j1 != j)){
     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
       stratrunc = &(stra[lstra-9]);  It might be a problem of design; if ncovcol and the model are correct\n \
       num[i]=atol(stratrunc);  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
     }            exit(1);
     else          }
       num[i]=atol(stra);          fprintf(ficparo,"%1d%1d",i1,j1);
     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){          if(mle==1)
       printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/            printf("%1d%1d",i,j);
               fprintf(ficlog,"%1d%1d",i,j);
     i=i+1;          for(k=1; k<=ncovmodel;k++){
   } /* End loop reading  data */            fscanf(ficpar," %lf",&param[i][j][k]);
   fclose(fic);            if(mle==1){
   /* printf("ii=%d", ij);              printf(" %lf",param[i][j][k]);
      scanf("%d",i);*/              fprintf(ficlog," %lf",param[i][j][k]);
   imx=i-1; /* Number of individuals */            }
             else
   /* for (i=1; i<=imx; i++){              fprintf(ficlog," %lf",param[i][j][k]);
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;            fprintf(ficparo," %lf",param[i][j][k]);
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;          }
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;          fscanf(ficpar,"\n");
     }*/          numlinepar++;
    /*  for (i=1; i<=imx; i++){          if(mle==1)
      if (s[4][i]==9)  s[4][i]=-1;             printf("\n");
      printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/          fprintf(ficlog,"\n");
             fprintf(ficparo,"\n");
   /* for (i=1; i<=imx; i++) */        }
        }  
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;      fflush(ficlog);
      else weight[i]=1;*/  
       p=param[1][1];
   /* Calculation of the number of parameters from char model */     
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */      /* Reads comments: lines beginning with '#' */
   Tprod=ivector(1,15);       while((c=getc(ficpar))=='#' && c!= EOF){
   Tvaraff=ivector(1,15);         ungetc(c,ficpar);
   Tvard=imatrix(1,15,1,2);        fgets(line, MAXLINE, ficpar);
   Tage=ivector(1,15);              numlinepar++;
            puts(line);
   if (strlen(model) >1){ /* If there is at least 1 covariate */        fputs(line,ficparo);
     j=0, j1=0, k1=1, k2=1;        fputs(line,ficlog);
     j=nbocc(model,'+'); /* j=Number of '+' */      }
     j1=nbocc(model,'*'); /* j1=Number of '*' */      ungetc(c,ficpar);
     cptcovn=j+1;   
     cptcovprod=j1; /*Number of products */      for(i=1; i <=nlstate; i++){
             for(j=1; j <=nlstate+ndeath-1; j++){
     strcpy(modelsav,model);           fscanf(ficpar,"%1d%1d",&i1,&j1);
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){          if ((i1-i)*(j1-j)!=0){
       printf("Error. Non available option model=%s ",model);            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
       fprintf(ficlog,"Error. Non available option model=%s ",model);            exit(1);
       goto end;          }
     }          printf("%1d%1d",i,j);
               fprintf(ficparo,"%1d%1d",i1,j1);
     /* This loop fills the array Tvar from the string 'model'.*/          fprintf(ficlog,"%1d%1d",i1,j1);
           for(k=1; k<=ncovmodel;k++){
     for(i=(j+1); i>=1;i--){            fscanf(ficpar,"%le",&delti3[i][j][k]);
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */             printf(" %le",delti3[i][j][k]);
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */            fprintf(ficparo," %le",delti3[i][j][k]);
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/            fprintf(ficlog," %le",delti3[i][j][k]);
       /*scanf("%d",i);*/          }
       if (strchr(strb,'*')) {  /* Model includes a product */          fscanf(ficpar,"\n");
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/          numlinepar++;
         if (strcmp(strc,"age")==0) { /* Vn*age */          printf("\n");
           cptcovprod--;          fprintf(ficparo,"\n");
           cutv(strb,stre,strd,'V');          fprintf(ficlog,"\n");
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/        }
           cptcovage++;      }
             Tage[cptcovage]=i;      fflush(ficlog);
             /*printf("stre=%s ", stre);*/  
         }      delti=delti3[1][1];
         else if (strcmp(strd,"age")==0) { /* or age*Vn */  
           cptcovprod--;  
           cutv(strb,stre,strc,'V');      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
           Tvar[i]=atoi(stre);   
           cptcovage++;      /* Reads comments: lines beginning with '#' */
           Tage[cptcovage]=i;      while((c=getc(ficpar))=='#' && c!= EOF){
         }        ungetc(c,ficpar);
         else {  /* Age is not in the model */        fgets(line, MAXLINE, ficpar);
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/        numlinepar++;
           Tvar[i]=ncovcol+k1;        puts(line);
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */        fputs(line,ficparo);
           Tprod[k1]=i;        fputs(line,ficlog);
           Tvard[k1][1]=atoi(strc); /* m*/      }
           Tvard[k1][2]=atoi(stre); /* n */      ungetc(c,ficpar);
           Tvar[cptcovn+k2]=Tvard[k1][1];   
           Tvar[cptcovn+k2+1]=Tvard[k1][2];       matcov=matrix(1,npar,1,npar);
           for (k=1; k<=lastobs;k++)       for(i=1; i <=npar; i++){
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];        fscanf(ficpar,"%s",&str);
           k1++;        if(mle==1)
           k2=k2+2;          printf("%s",str);
         }        fprintf(ficlog,"%s",str);
       }        fprintf(ficparo,"%s",str);
       else { /* no more sum */        for(j=1; j <=i; j++){
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/          fscanf(ficpar," %le",&matcov[i][j]);
        /*  scanf("%d",i);*/          if(mle==1){
       cutv(strd,strc,strb,'V');            printf(" %.5le",matcov[i][j]);
       Tvar[i]=atoi(strc);          }
       }          fprintf(ficlog," %.5le",matcov[i][j]);
       strcpy(modelsav,stra);            fprintf(ficparo," %.5le",matcov[i][j]);
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);        }
         scanf("%d",i);*/        fscanf(ficpar,"\n");
     } /* end of loop + */        numlinepar++;
   } /* end model */        if(mle==1)
             printf("\n");
   /*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,"\n");
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/        fprintf(ficparo,"\n");
       }
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);      for(i=1; i <=npar; i++)
   printf("cptcovprod=%d ", cptcovprod);        for(j=i+1;j<=npar;j++)
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);          matcov[i][j]=matcov[j][i];
      
   scanf("%d ",i);*/      if(mle==1)
         printf("\n");
     /*  if(mle==1){*/      fprintf(ficlog,"\n");
   if (weightopt != 1) { /* Maximisation without weights*/     
     for(i=1;i<=n;i++) weight[i]=1.0;      fflush(ficlog);
   }     
     /*-calculation of age at interview from date of interview and age at death -*/      /*-------- Rewriting parameter file ----------*/
   agev=matrix(1,maxwav,1,imx);      strcpy(rfileres,"r");    /* "Rparameterfile */
       strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
   for (i=1; i<=imx; i++) {      strcat(rfileres,".");    /* */
     for(m=2; (m<= maxwav); m++) {      strcat(rfileres,optionfilext);    /* Other files have txt extension */
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){      if((ficres =fopen(rfileres,"w"))==NULL) {
         anint[m][i]=9999;        printf("Problem writing new parameter file: %s\n", fileres);goto end;
         s[m][i]=-1;        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
       }      }
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){      fprintf(ficres,"#%s\n",version);
         nberr++;    }    /* End of mle != -3 */
         printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);  
         fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);    /*-------- data file ----------*/
         s[m][i]=-1;    if((fic=fopen(datafile,"r"))==NULL)    {
       }      printf("Problem while opening datafile: %s\n", datafile);goto end;
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
         nberr++;    }
         printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]);   
         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]);     n= lastobs;
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */    severity = vector(1,maxwav);
       }    outcome=imatrix(1,maxwav+1,1,n);
     }    num=lvector(1,n);
   }    moisnais=vector(1,n);
     annais=vector(1,n);
   for (i=1; i<=imx; i++)  {    moisdc=vector(1,n);
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);    andc=vector(1,n);
     for(m=firstpass; (m<= lastpass); m++){    agedc=vector(1,n);
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){    cod=ivector(1,n);
         if (s[m][i] >= nlstate+1) {    weight=vector(1,n);
           if(agedc[i]>0)    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)    mint=matrix(1,maxwav,1,n);
               agev[m][i]=agedc[i];    anint=matrix(1,maxwav,1,n);
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/    s=imatrix(1,maxwav+1,1,n);
             else {    tab=ivector(1,NCOVMAX);
               if ((int)andc[i]!=9999){    ncodemax=ivector(1,8);
                 nbwarn++;  
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);    i=1;
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);    linei=0;
                 agev[m][i]=-1;    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
               }      linei=linei+1;
             }      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
         }        if(line[j] == '\t')
         else if(s[m][i] !=9){ /* Standard case, age in fractional          line[j] = ' ';
                                  years but with the precision of a month */      }
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)        ;
             agev[m][i]=1;      };
           else if(agev[m][i] <agemin){       line[j+1]=0;  /* Trims blanks at end of line */
             agemin=agev[m][i];      if(line[0]=='#'){
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/        fprintf(ficlog,"Comment line\n%s\n",line);
           }        printf("Comment line\n%s\n",line);
           else if(agev[m][i] >agemax){        continue;
             agemax=agev[m][i];      }
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/  
           }      for (j=maxwav;j>=1;j--){
           /*agev[m][i]=anint[m][i]-annais[i];*/        cutv(stra, strb,line,' ');
           /*     agev[m][i] = age[i]+2*m;*/        errno=0;
         }        lval=strtol(strb,&endptr,10);
         else { /* =9 */        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
           agev[m][i]=1;        if( strb[0]=='\0' || (*endptr != '\0')){
           s[m][i]=-1;          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);
         }          exit(1);
       }        }
       else /*= 0 Unknown */        s[j][i]=lval;
         agev[m][i]=1;       
     }        strcpy(line,stra);
             cutv(stra, strb,line,' ');
   }        if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
   for (i=1; i<=imx; i++)  {        }
     for(m=firstpass; (m<=lastpass); m++){        else  if(iout=sscanf(strb,"%s.") != 0){
       if (s[m][i] > (nlstate+ndeath)) {          month=99;
         nberr++;          year=9999;
         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);             }else{
         fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);               printf("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);
         goto end;          exit(1);
       }        }
     }        anint[j][i]= (double) year;
   }        mint[j][i]= (double)month;
         strcpy(line,stra);
   /*for (i=1; i<=imx; i++){      } /* ENd Waves */
   for (m=firstpass; (m<lastpass); m++){     
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);      cutv(stra, strb,line,' ');
 }      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
       }
 }*/      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
         month=99;
         year=9999;
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);      }else{
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);         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);
         exit(1);
   agegomp=(int)agemin;      }
   free_vector(severity,1,maxwav);      andc[i]=(double) year;
   free_imatrix(outcome,1,maxwav+1,1,n);      moisdc[i]=(double) month;
   free_vector(moisnais,1,n);      strcpy(line,stra);
   free_vector(annais,1,n);     
   /* free_matrix(mint,1,maxwav,1,n);      cutv(stra, strb,line,' ');
      free_matrix(anint,1,maxwav,1,n);*/      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
   free_vector(moisdc,1,n);      }
   free_vector(andc,1,n);      else  if(iout=sscanf(strb,"%s.") != 0){
         month=99;
            year=9999;
   wav=ivector(1,imx);      }else{
   dh=imatrix(1,lastpass-firstpass+1,1,imx);        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);
   bh=imatrix(1,lastpass-firstpass+1,1,imx);        exit(1);
   mw=imatrix(1,lastpass-firstpass+1,1,imx);      }
          annais[i]=(double)(year);
   /* Concatenates waves */      moisnais[i]=(double)(month);
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);      strcpy(line,stra);
      
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */      cutv(stra, strb,line,' ');
       errno=0;
   Tcode=ivector(1,100);      dval=strtod(strb,&endptr);
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);       if( strb[0]=='\0' || (*endptr != '\0')){
   ncodemax[1]=1;        printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);        exit(1);
             }
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of       weight[i]=dval;
                                  the estimations*/      strcpy(line,stra);
   h=0;     
   m=pow(2,cptcoveff);      for (j=ncovcol;j>=1;j--){
          cutv(stra, strb,line,' ');
   for(k=1;k<=cptcoveff; k++){        errno=0;
     for(i=1; i <=(m/pow(2,k));i++){        lval=strtol(strb,&endptr,10);
       for(j=1; j <= ncodemax[k]; j++){        if( strb[0]=='\0' || (*endptr != '\0')){
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){          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);
           h++;          exit(1);
           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]);*/        if(lval <-1 || lval >1){
         }           printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
       }   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
     }   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 \
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);    build V1=0 V2=0 for the reference value (1),\n \
      codtab[1][2]=1;codtab[2][2]=2; */          V1=1 V2=0 for (2) \n \
   /* for(i=1; i <=m ;i++){    and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
      for(k=1; k <=cptcovn; k++){   output of IMaCh is often meaningless.\n \
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);   Exiting.\n",lval,linei, i,line,j);
      }          exit(1);
      printf("\n");        }
      }        covar[j][i]=(double)(lval);
      scanf("%d",i);*/        strcpy(line,stra);
           }
   /*------------ gnuplot -------------*/      lstra=strlen(stra);
   strcpy(optionfilegnuplot,optionfilefiname);     
   if(mle==-3)      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
     strcat(optionfilegnuplot,"-mort");        stratrunc = &(stra[lstra-9]);
   strcat(optionfilegnuplot,".gp");        num[i]=atol(stratrunc);
       }
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {      else
     printf("Problem with file %s",optionfilegnuplot);        num[i]=atol(stra);
   }      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
   else{        printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/
     fprintf(ficgp,"\n# %s\n", version);      
     fprintf(ficgp,"# %s\n", optionfilegnuplot);       i=i+1;
     fprintf(ficgp,"set missing 'NaNq'\n");    } /* End loop reading  data */
   }    fclose(fic);
   /*  fclose(ficgp);*/    /* printf("ii=%d", ij);
   /*--------- index.htm --------*/       scanf("%d",i);*/
     imx=i-1; /* Number of individuals */
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */  
   if(mle==-3)    /* for (i=1; i<=imx; i++){
     strcat(optionfilehtm,"-mort");      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
   strcat(optionfilehtm,".htm");      if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
     printf("Problem with %s \n",optionfilehtm), exit(0);      }*/
   }     /*  for (i=1; i<=imx; i++){
        if (s[4][i]==9)  s[4][i]=-1;
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */       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]));}*/
   strcat(optionfilehtmcov,"-cov.htm");   
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {    /* for (i=1; i<=imx; i++) */
     printf("Problem with %s \n",optionfilehtmcov), exit(0);   
   }     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
   else{       else weight[i]=1;*/
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \  
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    /* Calculation of the number of parameters from char model */
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);    Tprod=ivector(1,15);
   }    Tvaraff=ivector(1,15);
     Tvard=imatrix(1,15,1,2);
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \    Tage=ivector(1,15);      
 <hr size=\"2\" color=\"#EC5E5E\"> \n\     
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\    if (strlen(model) >1){ /* If there is at least 1 covariate */
 \n\      j=0, j1=0, k1=1, k2=1;
 <hr  size=\"2\" color=\"#EC5E5E\">\      j=nbocc(model,'+'); /* j=Number of '+' */
  <ul><li><h4>Parameter files</h4>\n\      j1=nbocc(model,'*'); /* j1=Number of '*' */
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\      cptcovn=j+1;
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\      cptcovprod=j1; /*Number of products */
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\     
  - Date and time at start: %s</ul>\n",\      strcpy(modelsav,model);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
           fileres,fileres,\        printf("Error. Non available option model=%s ",model);
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);        fprintf(ficlog,"Error. Non available option model=%s ",model);
   fflush(fichtm);        goto end;
       }
   strcpy(pathr,path);     
   strcat(pathr,optionfilefiname);      /* This loop fills the array Tvar from the string 'model'.*/
   chdir(optionfilefiname); /* Move to directory named optionfile */  
         for(i=(j+1); i>=1;i--){
   /* Calculates basic frequencies. Computes observed prevalence at single age        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
      and prints on file fileres'p'. */        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
         /*scanf("%d",i);*/
   fprintf(fichtm,"\n");        if (strchr(strb,'*')) {  /* Model includes a product */
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\          if (strcmp(strc,"age")==0) { /* Vn*age */
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\            cptcovprod--;
           imx,agemin,agemax,jmin,jmax,jmean);            cutv(strb,stre,strd,'V');
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */            cptcovage++;
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */              Tage[cptcovage]=i;
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */              /*printf("stre=%s ", stre);*/
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */          }
               else if (strcmp(strd,"age")==0) { /* or age*Vn */
                cptcovprod--;
   /* For Powell, parameters are in a vector p[] starting at p[1]            cutv(strb,stre,strc,'V');
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */            Tvar[i]=atoi(stre);
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */            cptcovage++;
             Tage[cptcovage]=i;
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/          }
           else {  /* Age is not in the model */
   if (mle==-3){            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
     ximort=matrix(1,NDIM,1,NDIM);            Tvar[i]=ncovcol+k1;
     cens=ivector(1,n);            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
     ageexmed=vector(1,n);            Tprod[k1]=i;
     agecens=vector(1,n);            Tvard[k1][1]=atoi(strc); /* m*/
     dcwave=ivector(1,n);            Tvard[k1][2]=atoi(stre); /* n */
              Tvar[cptcovn+k2]=Tvard[k1][1];
     for (i=1; i<=imx; i++){            Tvar[cptcovn+k2+1]=Tvard[k1][2];
       dcwave[i]=-1;            for (k=1; k<=lastobs;k++)
       for (m=firstpass; m<=lastpass; m++)              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
         if (s[m][i]>nlstate) {            k1++;
           dcwave[i]=m;            k2=k2+2;
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/          }
           break;        }
         }        else { /* no more sum */
     }          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
          /*  scanf("%d",i);*/
     for (i=1; i<=imx; i++) {        cutv(strd,strc,strb,'V');
       if (wav[i]>0){        Tvar[i]=atoi(strc);
         ageexmed[i]=agev[mw[1][i]][i];        }
         j=wav[i];        strcpy(modelsav,stra);  
         agecens[i]=1.;         /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
           scanf("%d",i);*/
         if (ageexmed[i]> 1 && wav[i] > 0){      } /* end of loop + */
           agecens[i]=agev[mw[j][i]][i];    } /* end model */
           cens[i]= 1;   
         }else if (ageexmed[i]< 1)     /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
           cens[i]= -1;      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
         if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)  
           cens[i]=0 ;    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
       }    printf("cptcovprod=%d ", cptcovprod);
       else cens[i]=-1;    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
     }  
         scanf("%d ",i);*/
     for (i=1;i<=NDIM;i++) {  
       for (j=1;j<=NDIM;j++)      /*  if(mle==1){*/
         ximort[i][j]=(i == j ? 1.0 : 0.0);    if (weightopt != 1) { /* Maximisation without weights*/
     }      for(i=1;i<=n;i++) weight[i]=1.0;
         }
     p[1]=0.0268; p[NDIM]=0.083;      /*-calculation of age at interview from date of interview and age at death -*/
     /*printf("%lf %lf", p[1], p[2]);*/    agev=matrix(1,maxwav,1,imx);
       
         for (i=1; i<=imx; i++) {
     printf("Powell\n");  fprintf(ficlog,"Powell\n");      for(m=2; (m<= maxwav); m++) {
     strcpy(filerespow,"pow-mort");         if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
     strcat(filerespow,fileres);          anint[m][i]=9999;
     if((ficrespow=fopen(filerespow,"w"))==NULL) {          s[m][i]=-1;
       printf("Problem with resultfile: %s\n", filerespow);        }
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
     }          nberr++;
     fprintf(ficrespow,"# Powell\n# iter -2*LL");          printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
     /*  for (i=1;i<=nlstate;i++)          fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
         for(j=1;j<=nlstate+ndeath;j++)          s[m][i]=-1;
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);        }
     */        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
     fprintf(ficrespow,"\n");          nberr++;
               printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]);
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);          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]);
     fclose(ficrespow);          s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
             }
     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);       }
     }
     for(i=1; i <=NDIM; i++)  
       for(j=i+1;j<=NDIM;j++)    for (i=1; i<=imx; i++)  {
         matcov[i][j]=matcov[j][i];      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
           for(m=firstpass; (m<= lastpass); m++){
     printf("\nCovariance matrix\n ");        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
     for(i=1; i <=NDIM; i++) {          if (s[m][i] >= nlstate+1) {
       for(j=1;j<=NDIM;j++){             if(agedc[i]>0)
         printf("%f ",matcov[i][j]);              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
       }                agev[m][i]=agedc[i];
       printf("\n ");            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
     }              else {
                     if ((int)andc[i]!=9999){
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);                  nbwarn++;
     for (i=1;i<=NDIM;i++)                   printf("Warning negative age at death: %ld line:%d\n",num[i],i);
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   agev[m][i]=-1;
     lsurv=vector(1,AGESUP);                }
     lpop=vector(1,AGESUP);              }
     tpop=vector(1,AGESUP);          }
     lsurv[agegomp]=100000;          else if(s[m][i] !=9){ /* Standard case, age in fractional
                                        years but with the precision of a month */
     for (k=agegomp;k<=AGESUP;k++) {            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
       agemortsup=k;            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;              agev[m][i]=1;
     }            else if(agev[m][i] <agemin){
                   agemin=agev[m][i];
     for (k=agegomp;k<agemortsup;k++)              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));            }
                 else if(agev[m][i] >agemax){
     for (k=agegomp;k<agemortsup;k++){              agemax=agev[m][i];
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
       sumlpop=sumlpop+lpop[k];            }
     }            /*agev[m][i]=anint[m][i]-annais[i];*/
                 /*     agev[m][i] = age[i]+2*m;*/
     tpop[agegomp]=sumlpop;          }
     for (k=agegomp;k<(agemortsup-3);k++){          else { /* =9 */
       /*  tpop[k+1]=2;*/            agev[m][i]=1;
       tpop[k+1]=tpop[k]-lpop[k];            s[m][i]=-1;
     }          }
             }
             else /*= 0 Unknown */
     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");          agev[m][i]=1;
     for (k=agegomp;k<(agemortsup-2);k++)       }
       printf("%d %.0lf %lf %.0lf %.0lf %.0lf %lf\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);     
         }
         for (i=1; i<=imx; i++)  {
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */      for(m=firstpass; (m<=lastpass); m++){
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);        if (s[m][i] > (nlstate+ndeath)) {
               nberr++;
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \          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);    
                      stepm, weightopt,\          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);    
                      model,imx,p,matcov,agemortsup);          goto end;
             }
     free_vector(lsurv,1,AGESUP);      }
     free_vector(lpop,1,AGESUP);    }
     free_vector(tpop,1,AGESUP);  
   } /* Endof if mle==-3 */    /*for (i=1; i<=imx; i++){
       for (m=firstpass; (m<lastpass); m++){
   else{ /* For mle >=1 */       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
     }
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */  
     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);  }*/
     for (k=1; k<=npar;k++)  
       printf(" %d %8.5f",k,p[k]);  
     printf("\n");    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
     globpr=1; /* to print the contributions */    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */  
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);    agegomp=(int)agemin;
     for (k=1; k<=npar;k++)    free_vector(severity,1,maxwav);
       printf(" %d %8.5f",k,p[k]);    free_imatrix(outcome,1,maxwav+1,1,n);
     printf("\n");    free_vector(moisnais,1,n);
     if(mle>=1){ /* Could be 1 or 2 */    free_vector(annais,1,n);
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);    /* free_matrix(mint,1,maxwav,1,n);
     }       free_matrix(anint,1,maxwav,1,n);*/
         free_vector(moisdc,1,n);
     /*--------- results files --------------*/    free_vector(andc,1,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);  
          
         wav=ivector(1,imx);
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    dh=imatrix(1,lastpass-firstpass+1,1,imx);
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    bh=imatrix(1,lastpass-firstpass+1,1,imx);
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    mw=imatrix(1,lastpass-firstpass+1,1,imx);
     for(i=1,jk=1; i <=nlstate; i++){     
       for(k=1; k <=(nlstate+ndeath); k++){    /* Concatenates waves */
         if (k != i) {    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
           printf("%d%d ",i,k);  
           fprintf(ficlog,"%d%d ",i,k);    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
           fprintf(ficres,"%1d%1d ",i,k);  
           for(j=1; j <=ncovmodel; j++){    Tcode=ivector(1,100);
             printf("%f ",p[jk]);    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
             fprintf(ficlog,"%f ",p[jk]);    ncodemax[1]=1;
             fprintf(ficres,"%f ",p[jk]);    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
             jk++;        
           }    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
           printf("\n");                                   the estimations*/
           fprintf(ficlog,"\n");    h=0;
           fprintf(ficres,"\n");    m=pow(2,cptcoveff);
         }   
       }    for(k=1;k<=cptcoveff; k++){
     }      for(i=1; i <=(m/pow(2,k));i++){
     if(mle!=0){        for(j=1; j <= ncodemax[k]; j++){
       /* Computing hessian and covariance matrix */          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
       ftolhess=ftol; /* Usually correct */            h++;
       hesscov(matcov, p, npar, delti, ftolhess, func);            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]);*/
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");          }
     printf("# Scales (for hessian or gradient estimation)\n");        }
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");      }
     for(i=1,jk=1; i <=nlstate; i++){    }
       for(j=1; j <=nlstate+ndeath; j++){    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
         if (j!=i) {       codtab[1][2]=1;codtab[2][2]=2; */
           fprintf(ficres,"%1d%1d",i,j);    /* for(i=1; i <=m ;i++){
           printf("%1d%1d",i,j);       for(k=1; k <=cptcovn; k++){
           fprintf(ficlog,"%1d%1d",i,j);       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
           for(k=1; k<=ncovmodel;k++){       }
             printf(" %.5e",delti[jk]);       printf("\n");
             fprintf(ficlog," %.5e",delti[jk]);       }
             fprintf(ficres," %.5e",delti[jk]);       scanf("%d",i);*/
             jk++;     
           }    /*------------ gnuplot -------------*/
           printf("\n");    strcpy(optionfilegnuplot,optionfilefiname);
           fprintf(ficlog,"\n");    if(mle==-3)
           fprintf(ficres,"\n");      strcat(optionfilegnuplot,"-mort");
         }    strcat(optionfilegnuplot,".gp");
       }  
     }    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
           printf("Problem with file %s",optionfilegnuplot);
     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)    else{
       printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");      fprintf(ficgp,"\n# %s\n", version);
     fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");      fprintf(ficgp,"# %s\n", optionfilegnuplot);
     /* # 121 Var(a12)\n\ */      fprintf(ficgp,"set missing 'NaNq'\n");
     /* # 122 Cov(b12,a12) Var(b12)\n\ */    }
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */    /*  fclose(ficgp);*/
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */    /*--------- index.htm --------*/
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */  
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */    if(mle==-3)
     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */      strcat(optionfilehtm,"-mort");
         strcat(optionfilehtm,".htm");
         if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
     /* Just to have a covariance matrix which will be more understandable      printf("Problem with %s \n",optionfilehtm), exit(0);
        even is we still don't want to manage dictionary of variables    }
     */  
     for(itimes=1;itimes<=2;itimes++){    strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
       jj=0;    strcat(optionfilehtmcov,"-cov.htm");
       for(i=1; i <=nlstate; i++){    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
         for(j=1; j <=nlstate+ndeath; j++){      printf("Problem with %s \n",optionfilehtmcov), exit(0);
           if(j==i) continue;    }
           for(k=1; k<=ncovmodel;k++){    else{
             jj++;    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
             ca[0]= k+'a'-1;ca[1]='\0';  <hr size=\"2\" color=\"#EC5E5E\"> \n\
             if(itimes==1){  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
               if(mle>=1)            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                 printf("#%1d%1d%d",i,j,k);    }
               fprintf(ficlog,"#%1d%1d%d",i,j,k);  
               fprintf(ficres,"#%1d%1d%d",i,j,k);    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
             }else{  <hr size=\"2\" color=\"#EC5E5E\"> \n\
               if(mle>=1)  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                 printf("%1d%1d%d",i,j,k);  \n\
               fprintf(ficlog,"%1d%1d%d",i,j,k);  <hr  size=\"2\" color=\"#EC5E5E\">\
               fprintf(ficres,"%1d%1d%d",i,j,k);   <ul><li><h4>Parameter files</h4>\n\
             }   - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
             ll=0;   - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
             for(li=1;li <=nlstate; li++){   - Log file of the run: <a href=\"%s\">%s</a><br>\n\
               for(lj=1;lj <=nlstate+ndeath; lj++){   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                 if(lj==li) continue;   - Date and time at start: %s</ul>\n",\
                 for(lk=1;lk<=ncovmodel;lk++){            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   ll++;            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   if(ll<=jj){            fileres,fileres,\
                     cb[0]= lk +'a'-1;cb[1]='\0';            filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                     if(ll<jj){    fflush(fichtm);
                       if(itimes==1){  
                         if(mle>=1)    strcpy(pathr,path);
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);    strcat(pathr,optionfilefiname);
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);    chdir(optionfilefiname); /* Move to directory named optionfile */
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);   
                       }else{    /* Calculates basic frequencies. Computes observed prevalence at single age
                         if(mle>=1)       and prints on file fileres'p'. */
                           printf(" %.5e",matcov[jj][ll]);     freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                         fprintf(ficlog," %.5e",matcov[jj][ll]);   
                         fprintf(ficres," %.5e",matcov[jj][ll]);     fprintf(fichtm,"\n");
                       }    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                     }else{  Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                       if(itimes==1){  Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                         if(mle>=1)            imx,agemin,agemax,jmin,jmax,jmean);
                           printf(" Var(%s%1d%1d)",ca,i,j);    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);      oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                       }else{      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                         if(mle>=1)      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                           printf(" %.5e",matcov[jj][ll]);      
                         fprintf(ficlog," %.5e",matcov[jj][ll]);      
                         fprintf(ficres," %.5e",matcov[jj][ll]);     /* For Powell, parameters are in a vector p[] starting at p[1]
                       }       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                     }    p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   }  
                 } /* end lk */    globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
               } /* end lj */  
             } /* end li */    if (mle==-3){
             if(mle>=1)      ximort=matrix(1,NDIM,1,NDIM);
               printf("\n");      cens=ivector(1,n);
             fprintf(ficlog,"\n");      ageexmed=vector(1,n);
             fprintf(ficres,"\n");      agecens=vector(1,n);
             numlinepar++;      dcwave=ivector(1,n);
           } /* end k*/   
         } /*end j */      for (i=1; i<=imx; i++){
       } /* end i */        dcwave[i]=-1;
     } /* end itimes */        for (m=firstpass; m<=lastpass; m++)
               if (s[m][i]>nlstate) {
     fflush(ficlog);            dcwave[i]=m;
     fflush(ficres);            /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                 break;
     while((c=getc(ficpar))=='#' && c!= EOF){          }
       ungetc(c,ficpar);      }
       fgets(line, MAXLINE, ficpar);  
       puts(line);      for (i=1; i<=imx; i++) {
       fputs(line,ficparo);        if (wav[i]>0){
     }          ageexmed[i]=agev[mw[1][i]][i];
     ungetc(c,ficpar);          j=wav[i];
               agecens[i]=1.;
     estepm=0;  
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);          if (ageexmed[i]> 1 && wav[i] > 0){
     if (estepm==0 || estepm < stepm) estepm=stepm;            agecens[i]=agev[mw[j][i]][i];
     if (fage <= 2) {            cens[i]= 1;
       bage = ageminpar;          }else if (ageexmed[i]< 1)
       fage = agemaxpar;            cens[i]= -1;
     }          if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                 cens[i]=0 ;
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");        }
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);        else cens[i]=-1;
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);      }
          
     while((c=getc(ficpar))=='#' && c!= EOF){      for (i=1;i<=NDIM;i++) {
       ungetc(c,ficpar);        for (j=1;j<=NDIM;j++)
       fgets(line, MAXLINE, ficpar);          ximort[i][j]=(i == j ? 1.0 : 0.0);
       puts(line);      }
       fputs(line,ficparo);     
     }      p[1]=0.0268; p[NDIM]=0.083;
     ungetc(c,ficpar);      /*printf("%lf %lf", p[1], p[2]);*/
          
     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);     
     fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);      printf("Powell\n");  fprintf(ficlog,"Powell\n");
     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);      strcpy(filerespow,"pow-mort");
     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(filerespow,fileres);
     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);      if((ficrespow=fopen(filerespow,"w"))==NULL) {
             printf("Problem with resultfile: %s\n", filerespow);
     while((c=getc(ficpar))=='#' && c!= EOF){        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
       ungetc(c,ficpar);      }
       fgets(line, MAXLINE, ficpar);      fprintf(ficrespow,"# Powell\n# iter -2*LL");
       puts(line);      /*  for (i=1;i<=nlstate;i++)
       fputs(line,ficparo);          for(j=1;j<=nlstate+ndeath;j++)
     }          if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
     ungetc(c,ficpar);      */
           fprintf(ficrespow,"\n");
          
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;      fclose(ficrespow);
          
     fscanf(ficpar,"pop_based=%d\n",&popbased);      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
     fprintf(ficparo,"pop_based=%d\n",popbased);     
     fprintf(ficres,"pop_based=%d\n",popbased);         for(i=1; i <=NDIM; i++)
             for(j=i+1;j<=NDIM;j++)
     while((c=getc(ficpar))=='#' && c!= EOF){          matcov[i][j]=matcov[j][i];
       ungetc(c,ficpar);     
       fgets(line, MAXLINE, ficpar);      printf("\nCovariance matrix\n ");
       puts(line);      for(i=1; i <=NDIM; i++) {
       fputs(line,ficparo);        for(j=1;j<=NDIM;j++){
     }          printf("%f ",matcov[i][j]);
     ungetc(c,ficpar);        }
             printf("\n ");
     fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);      }
     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);      printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
     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);      for (i=1;i<=NDIM;i++)
     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);        printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
     /* day and month of proj2 are not used but only year anproj2.*/  
           lsurv=vector(1,AGESUP);
           lpop=vector(1,AGESUP);
           tpop=vector(1,AGESUP);
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/      lsurv[agegomp]=100000;
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/     
           for (k=agegomp;k<=AGESUP;k++) {
     replace_back_to_slash(pathc,path); /* Even gnuplot wants a / */        agemortsup=k;
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
           }
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\     
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\      for (k=agegomp;k<agemortsup;k++)
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
            
    /*------------ free_vector  -------------*/      for (k=agegomp;k<agemortsup;k++){
    /*  chdir(path); */        lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
          sumlpop=sumlpop+lpop[k];
     free_ivector(wav,1,imx);      }
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);     
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);      tpop[agegomp]=sumlpop;
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);         for (k=agegomp;k<(agemortsup-3);k++){
     free_lvector(num,1,n);        /*  tpop[k+1]=2;*/
     free_vector(agedc,1,n);        tpop[k+1]=tpop[k]-lpop[k];
     /*free_matrix(covar,0,NCOVMAX,1,n);*/      }
     /*free_matrix(covar,1,NCOVMAX,1,n);*/     
     fclose(ficparo);     
     fclose(ficres);      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
       for (k=agegomp;k<(agemortsup-2);k++)
         printf("%d %.0lf %lf %.0lf %.0lf %.0lf %lf\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);
     /*--------------- Prevalence limit  (stable prevalence) --------------*/     
        
     strcpy(filerespl,"pl");      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     strcat(filerespl,fileres);      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     if((ficrespl=fopen(filerespl,"w"))==NULL) {     
       printf("Problem with stable prevalence resultfile: %s\n", filerespl);goto end;      printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
       fprintf(ficlog,"Problem with stable prevalence resultfile: %s\n", filerespl);goto end;                       stepm, weightopt,\
     }                       model,imx,p,matcov,agemortsup);
     printf("Computing stable prevalence: result on file '%s' \n", filerespl);     
     fprintf(ficlog,"Computing stable prevalence: result on file '%s' \n", filerespl);      free_vector(lsurv,1,AGESUP);
     fprintf(ficrespl, "#Local time at start: %s", strstart);      free_vector(lpop,1,AGESUP);
     fprintf(ficrespl,"#Stable prevalence \n");      free_vector(tpop,1,AGESUP);
     fprintf(ficrespl,"#Age ");    } /* Endof if mle==-3 */
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);   
     fprintf(ficrespl,"\n");    else{ /* For mle >=1 */
      
     prlim=matrix(1,nlstate,1,nlstate);      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);
     agebase=ageminpar;      for (k=1; k<=npar;k++)
     agelim=agemaxpar;        printf(" %d %8.5f",k,p[k]);
     ftolpl=1.e-10;      printf("\n");
     i1=cptcoveff;      globpr=1; /* to print the contributions */
     if (cptcovn < 1){i1=1;}      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
       printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      for (k=1; k<=npar;k++)
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){        printf(" %d %8.5f",k,p[k]);
         k=k+1;      printf("\n");
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/      if(mle>=1){ /* Could be 1 or 2 */
         fprintf(ficrespl,"\n#******");        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
         printf("\n#******");      }
         fprintf(ficlog,"\n#******");     
         for(j=1;j<=cptcoveff;j++) {      /*--------- results files --------------*/
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
           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(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         fprintf(ficrespl,"******\n");      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         printf("******\n");      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         fprintf(ficlog,"******\n");      for(i=1,jk=1; i <=nlstate; i++){
                 for(k=1; k <=(nlstate+ndeath); k++){
         for (age=agebase; age<=agelim; age++){          if (k != i) {
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);            printf("%d%d ",i,k);
           fprintf(ficrespl,"%.0f ",age );            fprintf(ficlog,"%d%d ",i,k);
           for(j=1;j<=cptcoveff;j++)            fprintf(ficres,"%1d%1d ",i,k);
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            for(j=1; j <=ncovmodel; j++){
           for(i=1; i<=nlstate;i++)              printf("%lf ",p[jk]);
             fprintf(ficrespl," %.5f", prlim[i][i]);              fprintf(ficlog,"%lf ",p[jk]);
           fprintf(ficrespl,"\n");              fprintf(ficres,"%lf ",p[jk]);
         }              jk++;
       }            }
     }            printf("\n");
     fclose(ficrespl);            fprintf(ficlog,"\n");
             fprintf(ficres,"\n");
     /*------------- h Pij x at various ages ------------*/          }
           }
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);      }
     if((ficrespij=fopen(filerespij,"w"))==NULL) {      if(mle!=0){
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;        /* Computing hessian and covariance matrix */
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;        ftolhess=ftol; /* Usually correct */
     }        hesscov(matcov, p, npar, delti, ftolhess, func);
     printf("Computing pij: result on file '%s' \n", filerespij);      }
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
         printf("# Scales (for hessian or gradient estimation)\n");
     stepsize=(int) (stepm+YEARM-1)/YEARM;      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
     /*if (stepm<=24) stepsize=2;*/      for(i=1,jk=1; i <=nlstate; i++){
         for(j=1; j <=nlstate+ndeath; j++){
     agelim=AGESUP;          if (j!=i) {
     hstepm=stepsize*YEARM; /* Every year of age */            fprintf(ficres,"%1d%1d",i,j);
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */             printf("%1d%1d",i,j);
             fprintf(ficlog,"%1d%1d",i,j);
     /* hstepm=1;   aff par mois*/            for(k=1; k<=ncovmodel;k++){
     fprintf(ficrespij, "#Local time at start: %s", strstart);              printf(" %.5e",delti[jk]);
     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");              fprintf(ficlog," %.5e",delti[jk]);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){              fprintf(ficres," %.5e",delti[jk]);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){              jk++;
         k=k+1;            }
         fprintf(ficrespij,"\n#****** ");            printf("\n");
         for(j=1;j<=cptcoveff;j++)             fprintf(ficlog,"\n");
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            fprintf(ficres,"\n");
         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 */      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)
           /*      nhstepm=nhstepm*YEARM; aff par mois*/        printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
       fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      /* # 121 Var(a12)\n\ */
           oldm=oldms;savm=savms;      /* # 122 Cov(b12,a12) Var(b12)\n\ */
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");      /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
           for(i=1; i<=nlstate;i++)      /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
             for(j=1; j<=nlstate+ndeath;j++)      /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
               fprintf(ficrespij," %1d-%1d",i,j);      /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
           fprintf(ficrespij,"\n");      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\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++)      /* Just to have a covariance matrix which will be more understandable
               for(j=1; j<=nlstate+ndeath;j++)         even is we still don't want to manage dictionary of variables
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);      */
             fprintf(ficrespij,"\n");      for(itimes=1;itimes<=2;itimes++){
           }        jj=0;
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        for(i=1; i <=nlstate; i++){
           fprintf(ficrespij,"\n");          for(j=1; j <=nlstate+ndeath; j++){
         }            if(j==i) continue;
       }            for(k=1; k<=ncovmodel;k++){
     }              jj++;
               ca[0]= k+'a'-1;ca[1]='\0';
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);              if(itimes==1){
                 if(mle>=1)
     fclose(ficrespij);                  printf("#%1d%1d%d",i,j,k);
                 fprintf(ficlog,"#%1d%1d%d",i,j,k);
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);                fprintf(ficres,"#%1d%1d%d",i,j,k);
     for(i=1;i<=AGESUP;i++)              }else{
       for(j=1;j<=NCOVMAX;j++)                if(mle>=1)
         for(k=1;k<=NCOVMAX;k++)                  printf("%1d%1d%d",i,j,k);
           probs[i][j][k]=0.;                fprintf(ficlog,"%1d%1d%d",i,j,k);
                 fprintf(ficres,"%1d%1d%d",i,j,k);
     /*---------- Forecasting ------------------*/              }
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/              ll=0;
     if(prevfcast==1){              for(li=1;li <=nlstate; li++){
       /*    if(stepm ==1){*/                for(lj=1;lj <=nlstate+ndeath; lj++){
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);                  if(lj==li) continue;
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/                  for(lk=1;lk<=ncovmodel;lk++){
       /*      }  */                    ll++;
       /*      else{ */                    if(ll<=jj){
       /*        erreur=108; */                      cb[0]= lk +'a'-1;cb[1]='\0';
       /*        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(ll<jj){
       /*        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); */                        if(itimes==1){
       /*      } */                          if(mle>=1)
     }                            printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                             fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                           fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     /*---------- Health expectancies and variances ------------*/                        }else{
                           if(mle>=1)
     strcpy(filerest,"t");                            printf(" %.5e",matcov[jj][ll]);
     strcat(filerest,fileres);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
     if((ficrest=fopen(filerest,"w"))==NULL) {                          fprintf(ficres," %.5e",matcov[jj][ll]);
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;                        }
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;                      }else{
     }                        if(itimes==1){
     printf("Computing Total LEs with variances: file '%s' \n", filerest);                           if(mle>=1)
     fprintf(ficlog,"Computing Total LEs with variances: file '%s' \n", filerest);                             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);
     strcpy(filerese,"e");                        }else{
     strcat(filerese,fileres);                          if(mle>=1)
     if((ficreseij=fopen(filerese,"w"))==NULL) {                            printf(" %.5e",matcov[jj][ll]);
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);                          fprintf(ficres," %.5e",matcov[jj][ll]);
     }                        }
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);                      }
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);                    }
                   } /* end lk */
     strcpy(fileresv,"v");                } /* end lj */
     strcat(fileresv,fileres);              } /* end li */
     if((ficresvij=fopen(fileresv,"w"))==NULL) {              if(mle>=1)
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);                printf("\n");
       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);              fprintf(ficlog,"\n");
     }              fprintf(ficres,"\n");
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);              numlinepar++;
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);            } /* end k*/
           } /*end j */
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */        } /* end i */
     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);      } /* end itimes */
     /*  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);      fflush(ficlog);
     */      fflush(ficres);
      
     if (mobilav!=0) {      while((c=getc(ficpar))=='#' && c!= EOF){
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        ungetc(c,ficpar);
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){        fgets(line, MAXLINE, ficpar);
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);        puts(line);
         printf(" Error in movingaverage mobilav=%d\n",mobilav);        fputs(line,ficparo);
       }      }
     }      ungetc(c,ficpar);
      
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      estepm=0;
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
         k=k+1;       if (estepm==0 || estepm < stepm) estepm=stepm;
         fprintf(ficrest,"\n#****** ");      if (fage <= 2) {
         for(j=1;j<=cptcoveff;j++)         bage = ageminpar;
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        fage = agemaxpar;
         fprintf(ficrest,"******\n");      }
      
         fprintf(ficreseij,"\n#****** ");      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
         for(j=1;j<=cptcoveff;j++)       fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
           fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
         fprintf(ficreseij,"******\n");     
       while((c=getc(ficpar))=='#' && c!= EOF){
         fprintf(ficresvij,"\n#****** ");        ungetc(c,ficpar);
         for(j=1;j<=cptcoveff;j++)         fgets(line, MAXLINE, ficpar);
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        puts(line);
         fprintf(ficresvij,"******\n");        fputs(line,ficparo);
       }
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      ungetc(c,ficpar);
         oldm=oldms;savm=savms;     
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);        fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
        fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      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);
         oldm=oldms;savm=savms;      printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
         varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);      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);
         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);      while((c=getc(ficpar))=='#' && c!= EOF){
         }        ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
         fprintf(ficrest, "#Local time at start: %s", strstart);        puts(line);
         fprintf(ficrest,"#Total LEs with variances: e.. (std) ");        fputs(line,ficparo);
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);      }
         fprintf(ficrest,"\n");      ungetc(c,ficpar);
      
         epj=vector(1,nlstate+1);     
         for(age=bage; age <=fage ;age++){      dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
           if (popbased==1) {     
             if(mobilav ==0){      fscanf(ficpar,"pop_based=%d\n",&popbased);
               for(i=1; i<=nlstate;i++)      fprintf(ficparo,"pop_based=%d\n",popbased);  
                 prlim[i][i]=probs[(int)age][i][k];      fprintf(ficres,"pop_based=%d\n",popbased);  
             }else{ /* mobilav */      
               for(i=1; i<=nlstate;i++)      while((c=getc(ficpar))=='#' && c!= EOF){
                 prlim[i][i]=mobaverage[(int)age][i][k];        ungetc(c,ficpar);
             }        fgets(line, MAXLINE, ficpar);
           }        puts(line);
                 fputs(line,ficparo);
           fprintf(ficrest," %4.0f",age);      }
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){      ungetc(c,ficpar);
             for(i=1, epj[j]=0.;i <=nlstate;i++) {     
               epj[j] += prlim[i][i]*eij[i][j][(int)age];      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);
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/      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);
             epj[nlstate+1] +=epj[j];      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.*/
           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));      /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
           for(j=1;j <=nlstate;j++){      /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));     
           }      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
           fprintf(ficrest,"\n");      printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
         }     
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);      printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);                   model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
         free_vector(epj,1,nlstate+1);                   jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
       }       
     }     /*------------ free_vector  -------------*/
     free_vector(weight,1,n);     /*  chdir(path); */
     free_imatrix(Tvard,1,15,1,2);   
     free_imatrix(s,1,maxwav+1,1,n);      free_ivector(wav,1,imx);
     free_matrix(anint,1,maxwav,1,n);       free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
     free_matrix(mint,1,maxwav,1,n);      free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
     free_ivector(cod,1,n);      free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
     free_ivector(tab,1,NCOVMAX);      free_lvector(num,1,n);
     fclose(ficreseij);      free_vector(agedc,1,n);
     fclose(ficresvij);      /*free_matrix(covar,0,NCOVMAX,1,n);*/
     fclose(ficrest);      /*free_matrix(covar,1,NCOVMAX,1,n);*/
     fclose(ficpar);      fclose(ficparo);
         fclose(ficres);
     /*------- Variance of stable prevalence------*/     
   
     strcpy(fileresvpl,"vpl");      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
     strcat(fileresvpl,fileres);   
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {      strcpy(filerespl,"pl");
       printf("Problem with variance of stable prevalence  resultfile: %s\n", fileresvpl);      strcat(filerespl,fileres);
       exit(0);      if((ficrespl=fopen(filerespl,"w"))==NULL) {
     }        printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     printf("Computing Variance-covariance of stable prevalence: file '%s' \n", fileresvpl);        fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
       }
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
         k=k+1;      pstamp(ficrespl);
         fprintf(ficresvpl,"\n#****** ");      fprintf(ficrespl,"# Period (stable) prevalence \n");
         for(j=1;j<=cptcoveff;j++)       fprintf(ficrespl,"#Age ");
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
         fprintf(ficresvpl,"******\n");      fprintf(ficrespl,"\n");
          
         varpl=matrix(1,nlstate,(int) bage, (int) fage);      prlim=matrix(1,nlstate,1,nlstate);
         oldm=oldms;savm=savms;  
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);      agebase=ageminpar;
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);      agelim=agemaxpar;
       }      ftolpl=1.e-10;
     }      i1=cptcoveff;
       if (cptcovn < 1){i1=1;}
     fclose(ficresvpl);  
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
     /*---------- End : free ----------------*/        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          k=k+1;
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);          /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
           fprintf(ficrespl,"\n#******");
   }  /* mle==-3 arrives here for freeing */          printf("\n#******");
   free_matrix(prlim,1,nlstate,1,nlstate);          fprintf(ficlog,"\n#******");
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);          for(j=1;j<=cptcoveff;j++) {
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);            fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);            printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);            fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_matrix(covar,0,NCOVMAX,1,n);          }
     free_matrix(matcov,1,npar,1,npar);          fprintf(ficrespl,"******\n");
     /*free_vector(delti,1,npar);*/          printf("******\n");
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);           fprintf(ficlog,"******\n");
     free_matrix(agev,1,maxwav,1,imx);         
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);          for (age=agebase; age<=agelim; age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
     free_ivector(ncodemax,1,8);            fprintf(ficrespl,"%.0f ",age );
     free_ivector(Tvar,1,15);            for(j=1;j<=cptcoveff;j++)
     free_ivector(Tprod,1,15);              fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_ivector(Tvaraff,1,15);            for(i=1; i<=nlstate;i++)
     free_ivector(Tage,1,15);              fprintf(ficrespl," %.5f", prlim[i][i]);
     free_ivector(Tcode,1,100);            fprintf(ficrespl,"\n");
           }
     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);        }
     free_imatrix(codtab,1,100,1,10);      }
   fflush(fichtm);      fclose(ficrespl);
   fflush(ficgp);  
         /*------------- h Pij x at various ages ------------*/
    
   if((nberr >0) || (nbwarn>0)){      strcpy(filerespij,"pij");  strcat(filerespij,fileres);
     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);      if((ficrespij=fopen(filerespij,"w"))==NULL) {
     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);        printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
   }else{        fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
     printf("End of Imach\n");      }
     fprintf(ficlog,"End of Imach\n");      printf("Computing pij: result on file '%s' \n", filerespij);
   }      fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
   printf("See log file on %s\n",filelog);   
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */      stepsize=(int) (stepm+YEARM-1)/YEARM;
   (void) gettimeofday(&end_time,&tzp);      /*if (stepm<=24) stepsize=2;*/
   tm = *localtime(&end_time.tv_sec);  
   tmg = *gmtime(&end_time.tv_sec);      agelim=AGESUP;
   strcpy(strtend,asctime(&tm));      hstepm=stepsize*YEARM; /* Every year of age */
   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);       hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
   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));      /* hstepm=1;   aff par mois*/
       pstamp(ficrespij);
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
   /*  printf("Total time was %d uSec.\n", total_usecs);*/          k=k+1;
 /*   if(fileappend(fichtm,optionfilehtm)){ */          fprintf(ficrespij,"\n#****** ");
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);          for(j=1;j<=cptcoveff;j++)
   fclose(fichtm);            fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   fclose(fichtmcov);          fprintf(ficrespij,"******\n");
   fclose(ficgp);         
   fclose(ficlog);          for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
   /*------ End -----------*/            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
             nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
   chdir(path);  
   /*strcat(plotcmd,CHARSEPARATOR);*/            /*      nhstepm=nhstepm*YEARM; aff par mois*/
   sprintf(plotcmd,"gnuplot");  
 #ifndef UNIX            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);            oldm=oldms;savm=savms;
 #endif            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   if(!stat(plotcmd,&info)){            fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);            for(i=1; i<=nlstate;i++)
     if(!stat(getenv("GNUPLOTBIN"),&info)){              for(j=1; j<=nlstate+ndeath;j++)
       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);                fprintf(ficrespij," %1d-%1d",i,j);
     }else            fprintf(ficrespij,"\n");
       strcpy(pplotcmd,plotcmd);            for (h=0; h<=nhstepm; h++){
 #ifdef UNIX              fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
     strcpy(plotcmd,GNUPLOTPROGRAM);              for(i=1; i<=nlstate;i++)
     if(!stat(plotcmd,&info)){                for(j=1; j<=nlstate+ndeath;j++)
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);                  fprintf(ficrespij," %.5f", p3mat[i][j][h]);
     }else              fprintf(ficrespij,"\n");
       strcpy(pplotcmd,plotcmd);            }
 #endif            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   }else            fprintf(ficrespij,"\n");
     strcpy(pplotcmd,plotcmd);          }
           }
   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);      }
   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);  
       varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
   if((outcmd=system(plotcmd)) != 0){  
     printf("\n Problem with gnuplot\n");      fclose(ficrespij);
   }  
   printf(" Wait...");      probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
   while (z[0] != 'q') {      for(i=1;i<=AGESUP;i++)
     /* chdir(path); */        for(j=1;j<=NCOVMAX;j++)
     printf("\nType e to edit output files, g to graph again and q for exiting: ");          for(k=1;k<=NCOVMAX;k++)
     scanf("%s",z);            probs[i][j][k]=0.;
 /*     if (z[0] == 'c') system("./imach"); */  
     if (z[0] == 'e') {      /*---------- Forecasting ------------------*/
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);      /*if((stepm == 1) && (strcmp(model,".")==0)){*/
       system(optionfilehtm);      if(prevfcast==1){
     }        /*    if(stepm ==1){*/
     else if (z[0] == 'g') system(plotcmd);        prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
     else if (z[0] == 'q') exit(0);        /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
   }        /*      }  */
   end:        /*      else{ */
   while (z[0] != 'q') {        /*        erreur=108; */
     printf("\nType  q for exiting: ");        /*        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); */
     scanf("%s",z);        /*        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.113  
changed lines
  Added in v.1.125


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