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

version 1.121, 2006/03/16 17:45:01 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.121  2006/03/16 17:45:01  lievre    Revision 1.125  2006/04/04 15:20:31  lievre
   * imach.c (Module): Comments concerning covariates added    Errors in calculation of health expectancies. Age was not initialized.
     Forecasting file added.
   * imach.c (Module): refinements in the computation of lli if  
   status=-2 in order to have more reliable computation if stepm is    Revision 1.124  2006/03/22 17:13:53  lievre
   not 1 month. Version 0.98f    Parameters are printed with %lf instead of %f (more numbers after the comma).
     The log-likelihood is printed in the log file
   Revision 1.120  2006/03/16 15:10:38  lievre  
   (Module): refinements in the computation of lli if    Revision 1.123  2006/03/20 10:52:43  brouard
   status=-2 in order to have more reliable computation if stepm is    * imach.c (Module): <title> changed, corresponds to .htm file
   not 1 month. Version 0.98f    name. <head> headers where missing.
   
   Revision 1.119  2006/03/15 17:42:26  brouard    * imach.c (Module): Weights can have a decimal point as for
   (Module): Bug if status = -2, the loglikelihood was    English (a comma might work with a correct LC_NUMERIC environment,
   computed as likelihood omitting the logarithm. Version O.98e    otherwise the weight is truncated).
     Modification of warning when the covariates values are not 0 or
   Revision 1.118  2006/03/14 18:20:07  brouard    1.
   (Module): varevsij Comments added explaining the second    Version 0.98g
   table of variances if popbased=1 .  
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.    Revision 1.122  2006/03/20 09:45:41  brouard
   (Module): Function pstamp added    (Module): Weights can have a decimal point as for
   (Module): Version 0.98d    English (a comma might work with a correct LC_NUMERIC environment,
     otherwise the weight is truncated).
   Revision 1.117  2006/03/14 17:16:22  brouard    Modification of warning when the covariates values are not 0 or
   (Module): varevsij Comments added explaining the second    1.
   table of variances if popbased=1 .    Version 0.98g
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.  
   (Module): Function pstamp added    Revision 1.121  2006/03/16 17:45:01  lievre
   (Module): Version 0.98d    * imach.c (Module): Comments concerning covariates added
   
   Revision 1.116  2006/03/06 10:29:27  brouard    * imach.c (Module): refinements in the computation of lli if
   (Module): Variance-covariance wrong links and    status=-2 in order to have more reliable computation if stepm is
   varian-covariance of ej. is needed (Saito).    not 1 month. Version 0.98f
   
   Revision 1.115  2006/02/27 12:17:45  brouard    Revision 1.120  2006/03/16 15:10:38  lievre
   (Module): One freematrix added in mlikeli! 0.98c    (Module): refinements in the computation of lli if
     status=-2 in order to have more reliable computation if stepm is
   Revision 1.114  2006/02/26 12:57:58  brouard    not 1 month. Version 0.98f
   (Module): Some improvements in processing parameter  
   filename with strsep.    Revision 1.119  2006/03/15 17:42:26  brouard
     (Module): Bug if status = -2, the loglikelihood was
   Revision 1.113  2006/02/24 14:20:24  brouard    computed as likelihood omitting the logarithm. Version O.98e
   (Module): Memory leaks checks with valgrind and:  
   datafile was not closed, some imatrix were not freed and on matrix    Revision 1.118  2006/03/14 18:20:07  brouard
   allocation too.    (Module): varevsij Comments added explaining the second
     table of variances if popbased=1 .
   Revision 1.112  2006/01/30 09:55:26  brouard    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   (Module): Back to gnuplot.exe instead of wgnuplot.exe    (Module): Function pstamp added
     (Module): Version 0.98d
   Revision 1.111  2006/01/25 20:38:18  brouard  
   (Module): Lots of cleaning and bugs added (Gompertz)    Revision 1.117  2006/03/14 17:16:22  brouard
   (Module): Comments can be added in data file. Missing date values    (Module): varevsij Comments added explaining the second
   can be a simple dot '.'.    table of variances if popbased=1 .
     (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   Revision 1.110  2006/01/25 00:51:50  brouard    (Module): Function pstamp added
   (Module): Lots of cleaning and bugs added (Gompertz)    (Module): Version 0.98d
   
   Revision 1.109  2006/01/24 19:37:15  brouard    Revision 1.116  2006/03/06 10:29:27  brouard
   (Module): Comments (lines starting with a #) are allowed in data.    (Module): Variance-covariance wrong links and
     varian-covariance of ej. is needed (Saito).
   Revision 1.108  2006/01/19 18:05:42  lievre  
   Gnuplot problem appeared...    Revision 1.115  2006/02/27 12:17:45  brouard
   To be fixed    (Module): One freematrix added in mlikeli! 0.98c
   
   Revision 1.107  2006/01/19 16:20:37  brouard    Revision 1.114  2006/02/26 12:57:58  brouard
   Test existence of gnuplot in imach path    (Module): Some improvements in processing parameter
     filename with strsep.
   Revision 1.106  2006/01/19 13:24:36  brouard  
   Some cleaning and links added in html output    Revision 1.113  2006/02/24 14:20:24  brouard
     (Module): Memory leaks checks with valgrind and:
   Revision 1.105  2006/01/05 20:23:19  lievre    datafile was not closed, some imatrix were not freed and on matrix
   *** empty log message ***    allocation too.
   
   Revision 1.104  2005/09/30 16:11:43  lievre    Revision 1.112  2006/01/30 09:55:26  brouard
   (Module): sump fixed, loop imx fixed, and simplifications.    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   (Module): If the status is missing at the last wave but we know  
   that the person is alive, then we can code his/her status as -2    Revision 1.111  2006/01/25 20:38:18  brouard
   (instead of missing=-1 in earlier versions) and his/her    (Module): Lots of cleaning and bugs added (Gompertz)
   contributions to the likelihood is 1 - Prob of dying from last    (Module): Comments can be added in data file. Missing date values
   health status (= 1-p13= p11+p12 in the easiest case of somebody in    can be a simple dot '.'.
   the healthy state at last known wave). Version is 0.98  
     Revision 1.110  2006/01/25 00:51:50  brouard
   Revision 1.103  2005/09/30 15:54:49  lievre    (Module): Lots of cleaning and bugs added (Gompertz)
   (Module): sump fixed, loop imx fixed, and simplifications.  
     Revision 1.109  2006/01/24 19:37:15  brouard
   Revision 1.102  2004/09/15 17:31:30  brouard    (Module): Comments (lines starting with a #) are allowed in data.
   Add the possibility to read data file including tab characters.  
     Revision 1.108  2006/01/19 18:05:42  lievre
   Revision 1.101  2004/09/15 10:38:38  brouard    Gnuplot problem appeared...
   Fix on curr_time    To be fixed
   
   Revision 1.100  2004/07/12 18:29:06  brouard    Revision 1.107  2006/01/19 16:20:37  brouard
   Add version for Mac OS X. Just define UNIX in Makefile    Test existence of gnuplot in imach path
   
   Revision 1.99  2004/06/05 08:57:40  brouard    Revision 1.106  2006/01/19 13:24:36  brouard
   *** empty log message ***    Some cleaning and links added in html output
   
   Revision 1.98  2004/05/16 15:05:56  brouard    Revision 1.105  2006/01/05 20:23:19  lievre
   New version 0.97 . First attempt to estimate force of mortality    *** empty log message ***
   directly from the data i.e. without the need of knowing the health  
   state at each age, but using a Gompertz model: log u =a + b*age .    Revision 1.104  2005/09/30 16:11:43  lievre
   This is the basic analysis of mortality and should be done before any    (Module): sump fixed, loop imx fixed, and simplifications.
   other analysis, in order to test if the mortality estimated from the    (Module): If the status is missing at the last wave but we know
   cross-longitudinal survey is different from the mortality estimated    that the person is alive, then we can code his/her status as -2
   from other sources like vital statistic data.    (instead of missing=-1 in earlier versions) and his/her
     contributions to the likelihood is 1 - Prob of dying from last
   The same imach parameter file can be used but the option for mle should be -3.    health status (= 1-p13= p11+p12 in the easiest case of somebody in
     the healthy state at last known wave). Version is 0.98
   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.103  2005/09/30 15:54:49  lievre
     (Module): sump fixed, loop imx fixed, and simplifications.
   The output is very simple: only an estimate of the intercept and of  
   the slope with 95% confident intervals.    Revision 1.102  2004/09/15 17:31:30  brouard
     Add the possibility to read data file including tab characters.
   Current limitations:  
   A) Even if you enter covariates, i.e. with the    Revision 1.101  2004/09/15 10:38:38  brouard
   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.    Fix on curr_time
   B) There is no computation of Life Expectancy nor Life Table.  
     Revision 1.100  2004/07/12 18:29:06  brouard
   Revision 1.97  2004/02/20 13:25:42  lievre    Add version for Mac OS X. Just define UNIX in Makefile
   Version 0.96d. Population forecasting command line is (temporarily)  
   suppressed.    Revision 1.99  2004/06/05 08:57:40  brouard
     *** empty log message ***
   Revision 1.96  2003/07/15 15:38:55  brouard  
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is    Revision 1.98  2004/05/16 15:05:56  brouard
   rewritten within the same printf. Workaround: many printfs.    New version 0.97 . First attempt to estimate force of mortality
     directly from the data i.e. without the need of knowing the health
   Revision 1.95  2003/07/08 07:54:34  brouard    state at each age, but using a Gompertz model: log u =a + b*age .
   * imach.c (Repository):    This is the basic analysis of mortality and should be done before any
   (Repository): Using imachwizard code to output a more meaningful covariance    other analysis, in order to test if the mortality estimated from the
   matrix (cov(a12,c31) instead of numbers.    cross-longitudinal survey is different from the mortality estimated
     from other sources like vital statistic data.
   Revision 1.94  2003/06/27 13:00:02  brouard  
   Just cleaning    The same imach parameter file can be used but the option for mle should be -3.
   
   Revision 1.93  2003/06/25 16:33:55  brouard    Agnès, who wrote this part of the code, tried to keep most of the
   (Module): On windows (cygwin) function asctime_r doesn't    former routines in order to include the new code within the former code.
   exist so I changed back to asctime which exists.  
   (Module): Version 0.96b    The output is very simple: only an estimate of the intercept and of
     the slope with 95% confident intervals.
   Revision 1.92  2003/06/25 16:30:45  brouard  
   (Module): On windows (cygwin) function asctime_r doesn't    Current limitations:
   exist so I changed back to asctime which exists.    A) Even if you enter covariates, i.e. with the
     model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   Revision 1.91  2003/06/25 15:30:29  brouard    B) There is no computation of Life Expectancy nor Life Table.
   * imach.c (Repository): Duplicated warning errors corrected.  
   (Repository): Elapsed time after each iteration is now output. It    Revision 1.97  2004/02/20 13:25:42  lievre
   helps to forecast when convergence will be reached. Elapsed time    Version 0.96d. Population forecasting command line is (temporarily)
   is stamped in powell.  We created a new html file for the graphs    suppressed.
   concerning matrix of covariance. It has extension -cov.htm.  
     Revision 1.96  2003/07/15 15:38:55  brouard
   Revision 1.90  2003/06/24 12:34:15  brouard    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   (Module): Some bugs corrected for windows. Also, when    rewritten within the same printf. Workaround: many printfs.
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.95  2003/07/08 07:54:34  brouard
     * imach.c (Repository):
   Revision 1.89  2003/06/24 12:30:52  brouard    (Repository): Using imachwizard code to output a more meaningful covariance
   (Module): Some bugs corrected for windows. Also, when    matrix (cov(a12,c31) instead of numbers.
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.94  2003/06/27 13:00:02  brouard
     Just cleaning
   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.93  2003/06/25 16:33:55  brouard
     (Module): On windows (cygwin) function asctime_r doesn't
   Revision 1.87  2003/06/18 12:26:01  brouard    exist so I changed back to asctime which exists.
   Version 0.96    (Module): Version 0.96b
   
   Revision 1.86  2003/06/17 20:04:08  brouard    Revision 1.92  2003/06/25 16:30:45  brouard
   (Module): Change position of html and gnuplot routines and added    (Module): On windows (cygwin) function asctime_r doesn't
   routine fileappend.    exist so I changed back to asctime which exists.
   
   Revision 1.85  2003/06/17 13:12:43  brouard    Revision 1.91  2003/06/25 15:30:29  brouard
   * imach.c (Repository): Check when date of death was earlier that    * imach.c (Repository): Duplicated warning errors corrected.
   current date of interview. It may happen when the death was just    (Repository): Elapsed time after each iteration is now output. It
   prior to the death. In this case, dh was negative and likelihood    helps to forecast when convergence will be reached. Elapsed time
   was wrong (infinity). We still send an "Error" but patch by    is stamped in powell.  We created a new html file for the graphs
   assuming that the date of death was just one stepm after the    concerning matrix of covariance. It has extension -cov.htm.
   interview.  
   (Repository): Because some people have very long ID (first column)    Revision 1.90  2003/06/24 12:34:15  brouard
   we changed int to long in num[] and we added a new lvector for    (Module): Some bugs corrected for windows. Also, when
   memory allocation. But we also truncated to 8 characters (left    mle=-1 a template is output in file "or"mypar.txt with the design
   truncation)    of the covariance matrix to be input.
   (Repository): No more line truncation errors.  
     Revision 1.89  2003/06/24 12:30:52  brouard
   Revision 1.84  2003/06/13 21:44:43  brouard    (Module): Some bugs corrected for windows. Also, when
   * imach.c (Repository): Replace "freqsummary" at a correct    mle=-1 a template is output in file "or"mypar.txt with the design
   place. It differs from routine "prevalence" which may be called    of the covariance matrix to be input.
   many times. Probs is memory consuming and must be used with  
   parcimony.    Revision 1.88  2003/06/23 17:54:56  brouard
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    * 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.83  2003/06/10 13:39:11  lievre    Revision 1.87  2003/06/18 12:26:01  brouard
   *** empty log message ***    Version 0.96
   
   Revision 1.82  2003/06/05 15:57:20  brouard    Revision 1.86  2003/06/17 20:04:08  brouard
   Add log in  imach.c and  fullversion number is now printed.    (Module): Change position of html and gnuplot routines and added
     routine fileappend.
 */  
 /*    Revision 1.85  2003/06/17 13:12:43  brouard
    Interpolated Markov Chain    * imach.c (Repository): Check when date of death was earlier that
     current date of interview. It may happen when the death was just
   Short summary of the programme:    prior to the death. In this case, dh was negative and likelihood
       was wrong (infinity). We still send an "Error" but patch by
   This program computes Healthy Life Expectancies from    assuming that the date of death was just one stepm after the
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    interview.
   first survey ("cross") where individuals from different ages are    (Repository): Because some people have very long ID (first column)
   interviewed on their health status or degree of disability (in the    we changed int to long in num[] and we added a new lvector for
   case of a health survey which is our main interest) -2- at least a    memory allocation. But we also truncated to 8 characters (left
   second wave of interviews ("longitudinal") which measure each change    truncation)
   (if any) in individual health status.  Health expectancies are    (Repository): No more line truncation errors.
   computed from the time spent in each health state according to a  
   model. More health states you consider, more time is necessary to reach the    Revision 1.84  2003/06/13 21:44:43  brouard
   Maximum Likelihood of the parameters involved in the model.  The    * imach.c (Repository): Replace "freqsummary" at a correct
   simplest model is the multinomial logistic model where pij is the    place. It differs from routine "prevalence" which may be called
   probability to be observed in state j at the second wave    many times. Probs is memory consuming and must be used with
   conditional to be observed in state i at the first wave. Therefore    parcimony.
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
   'age' is age and 'sex' is a covariate. If you want to have a more  
   complex model than "constant and age", you should modify the program    Revision 1.83  2003/06/10 13:39:11  lievre
   where the markup *Covariates have to be included here again* invites    *** empty log message ***
   you to do it.  More covariates you add, slower the  
   convergence.    Revision 1.82  2003/06/05 15:57:20  brouard
     Add log in  imach.c and  fullversion number is now printed.
   The advantage of this computer programme, compared to a simple  
   multinomial logistic model, is clear when the delay between waves is not  */
   identical for each individual. Also, if a individual missed an  /*
   intermediate interview, the information is lost, but taken into     Interpolated Markov Chain
   account using an interpolation or extrapolation.    
     Short summary of the programme:
   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    This program computes Healthy Life Expectancies from
   split into an exact number (nh*stepm) of unobserved intermediate    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
   states. This elementary transition (by month, quarter,    first survey ("cross") where individuals from different ages are
   semester or year) is modelled as a multinomial logistic.  The hPx    interviewed on their health status or degree of disability (in the
   matrix is simply the matrix product of nh*stepm elementary matrices    case of a health survey which is our main interest) -2- at least a
   and the contribution of each individual to the likelihood is simply    second wave of interviews ("longitudinal") which measure each change
   hPijx.    (if any) in individual health status.  Health expectancies are
     computed from the time spent in each health state according to a
   Also this programme outputs the covariance matrix of the parameters but also    model. More health states you consider, more time is necessary to reach the
   of the life expectancies. It also computes the period (stable) prevalence.     Maximum Likelihood of the parameters involved in the model.  The
       simplest model is the multinomial logistic model where pij is the
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    probability to be observed in state j at the second wave
            Institut national d'études démographiques, Paris.    conditional to be observed in state i at the first wave. Therefore
   This software have been partly granted by Euro-REVES, a concerted action    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
   from the European Union.    'age' is age and 'sex' is a covariate. If you want to have a more
   It is copyrighted identically to a GNU software product, ie programme and    complex model than "constant and age", you should modify the program
   software can be distributed freely for non commercial use. Latest version    where the markup *Covariates have to be included here again* invites
   can be accessed at http://euroreves.ined.fr/imach .    you to do it.  More covariates you add, slower the
     convergence.
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach  
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    The advantage of this computer programme, compared to a simple
       multinomial logistic model, is clear when the delay between waves is not
   **********************************************************************/    identical for each individual. Also, if a individual missed an
 /*    intermediate interview, the information is lost, but taken into
   main    account using an interpolation or extrapolation.  
   read parameterfile  
   read datafile    hPijx is the probability to be observed in state i at age x+h
   concatwav    conditional to the observed state i at age x. The delay 'h' can be
   freqsummary    split into an exact number (nh*stepm) of unobserved intermediate
   if (mle >= 1)    states. This elementary transition (by month, quarter,
     mlikeli    semester or year) is modelled as a multinomial logistic.  The hPx
   print results files    matrix is simply the matrix product of nh*stepm elementary matrices
   if mle==1     and the contribution of each individual to the likelihood is simply
      computes hessian    hPijx.
   read end of parameter file: agemin, agemax, bage, fage, estepm  
       begin-prev-date,...    Also this programme outputs the covariance matrix of the parameters but also
   open gnuplot file    of the life expectancies. It also computes the period (stable) prevalence.
   open html file   
   period (stable) prevalence    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
    for age prevalim()             Institut national d'études démographiques, Paris.
   h Pij x    This software have been partly granted by Euro-REVES, a concerted action
   variance of p varprob    from the European Union.
   forecasting if prevfcast==1 prevforecast call prevalence()    It is copyrighted identically to a GNU software product, ie programme and
   health expectancies    software can be distributed freely for non commercial use. Latest version
   Variance-covariance of DFLE    can be accessed at http://euroreves.ined.fr/imach .
   prevalence()  
    movingaverage()    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
   varevsij()     or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
   if popbased==1 varevsij(,popbased)   
   total life expectancies    **********************************************************************/
   Variance of period (stable) prevalence  /*
  end    main
 */    read parameterfile
     read datafile
     concatwav
     freqsummary
      if (mle >= 1)
 #include <math.h>      mlikeli
 #include <stdio.h>    print results files
 #include <stdlib.h>    if mle==1
 #include <string.h>       computes hessian
 #include <unistd.h>    read end of parameter file: agemin, agemax, bage, fage, estepm
         begin-prev-date,...
 #include <limits.h>    open gnuplot file
 #include <sys/types.h>    open html file
 #include <sys/stat.h>    period (stable) prevalence
 #include <errno.h>     for age prevalim()
 extern int errno;    h Pij x
     variance of p varprob
 /* #include <sys/time.h> */    forecasting if prevfcast==1 prevforecast call prevalence()
 #include <time.h>    health expectancies
 #include "timeval.h"    Variance-covariance of DFLE
     prevalence()
 /* #include <libintl.h> */     movingaverage()
 /* #define _(String) gettext (String) */    varevsij()
     if popbased==1 varevsij(,popbased)
 #define MAXLINE 256    total life expectancies
     Variance of period (stable) prevalence
 #define GNUPLOTPROGRAM "gnuplot"   end
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/  */
 #define FILENAMELENGTH 132  
   
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */  
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */   
   #include <math.h>
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */  #include <stdio.h>
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  #include <stdlib.h>
   #include <string.h>
 #define NINTERVMAX 8  #include <unistd.h>
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */  
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */  #include <limits.h>
 #define NCOVMAX 8 /* Maximum number of covariates */  #include <sys/types.h>
 #define MAXN 20000  #include <sys/stat.h>
 #define YEARM 12. /* Number of months per year */  #include <errno.h>
 #define AGESUP 130  extern int errno;
 #define AGEBASE 40  
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */  /* #include <sys/time.h> */
 #ifdef UNIX  #include <time.h>
 #define DIRSEPARATOR '/'  #include "timeval.h"
 #define CHARSEPARATOR "/"  
 #define ODIRSEPARATOR '\\'  /* #include <libintl.h> */
 #else  /* #define _(String) gettext (String) */
 #define DIRSEPARATOR '\\'  
 #define CHARSEPARATOR "\\"  #define MAXLINE 256
 #define ODIRSEPARATOR '/'  
 #endif  #define GNUPLOTPROGRAM "gnuplot"
   /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 /* $Id$ */  #define FILENAMELENGTH 132
 /* $State$ */  
   #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 char version[]="Imach version 0.98f, March 2006, INED-EUROREVES-Institut de longevite ";  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 char fullversion[]="$Revision$ $Date$";   
 char strstart[80];  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 char optionfilext[10], optionfilefiname[FILENAMELENGTH];  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */  
 int nvar;  #define NINTERVMAX 8
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 int npar=NPARMAX;  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 int nlstate=2; /* Number of live states */  #define NCOVMAX 8 /* Maximum number of covariates */
 int ndeath=1; /* Number of dead states */  #define MAXN 20000
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */  #define YEARM 12. /* Number of months per year */
 int popbased=0;  #define AGESUP 130
   #define AGEBASE 40
 int *wav; /* Number of waves for this individuual 0 is possible */  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 int maxwav; /* Maxim number of waves */  #ifdef UNIX
 int jmin, jmax; /* min, max spacing between 2 waves */  #define DIRSEPARATOR '/'
 int ijmin, ijmax; /* Individuals having jmin and jmax */   #define CHARSEPARATOR "/"
 int gipmx, gsw; /* Global variables on the number of contributions   #define ODIRSEPARATOR '\\'
                    to the likelihood and the sum of weights (done by funcone)*/  #else
 int mle, weightopt;  #define DIRSEPARATOR '\\'
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */  #define CHARSEPARATOR "\\"
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */  #define ODIRSEPARATOR '/'
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between  #endif
            * wave mi and wave mi+1 is not an exact multiple of stepm. */  
 double jmean; /* Mean space between 2 waves */  /* $Id$ */
 double **oldm, **newm, **savm; /* Working pointers to matrices */  /* $State$ */
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */  
 FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
 FILE *ficlog, *ficrespow;  char fullversion[]="$Revision$ $Date$";
 int globpr; /* Global variable for printing or not */  char strstart[80];
 double fretone; /* Only one call to likelihood */  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 long ipmx; /* Number of contributions */  int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 double sw; /* Sum of weights */  int nvar;
 char filerespow[FILENAMELENGTH];  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */  int npar=NPARMAX;
 FILE *ficresilk;  int nlstate=2; /* Number of live states */
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;  int ndeath=1; /* Number of dead states */
 FILE *ficresprobmorprev;  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 FILE *fichtm, *fichtmcov; /* Html File */  int popbased=0;
 FILE *ficreseij;  
 char filerese[FILENAMELENGTH];  int *wav; /* Number of waves for this individuual 0 is possible */
 FILE *ficresstdeij;  int maxwav; /* Maxim number of waves */
 char fileresstde[FILENAMELENGTH];  int jmin, jmax; /* min, max spacing between 2 waves */
 FILE *ficrescveij;  int ijmin, ijmax; /* Individuals having jmin and jmax */
 char filerescve[FILENAMELENGTH];  int gipmx, gsw; /* Global variables on the number of contributions
 FILE  *ficresvij;                     to the likelihood and the sum of weights (done by funcone)*/
 char fileresv[FILENAMELENGTH];  int mle, weightopt;
 FILE  *ficresvpl;  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 char fileresvpl[FILENAMELENGTH];  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 char title[MAXLINE];  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];             * wave mi and wave mi+1 is not an exact multiple of stepm. */
 char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];  double jmean; /* Mean space between 2 waves */
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];   double **oldm, **newm, **savm; /* Working pointers to matrices */
 char command[FILENAMELENGTH];  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 int  outcmd=0;  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
   FILE *ficlog, *ficrespow;
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  int globpr; /* Global variable for printing or not */
   double fretone; /* Only one call to likelihood */
 char filelog[FILENAMELENGTH]; /* Log file */  long ipmx; /* Number of contributions */
 char filerest[FILENAMELENGTH];  double sw; /* Sum of weights */
 char fileregp[FILENAMELENGTH];  char filerespow[FILENAMELENGTH];
 char popfile[FILENAMELENGTH];  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
   FILE *ficresilk;
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
   FILE *ficresprobmorprev;
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  FILE *fichtm, *fichtmcov; /* Html File */
 struct timezone tzp;  FILE *ficreseij;
 extern int gettimeofday();  char filerese[FILENAMELENGTH];
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  FILE *ficresstdeij;
 long time_value;  char fileresstde[FILENAMELENGTH];
 extern long time();  FILE *ficrescveij;
 char strcurr[80], strfor[80];  char filerescve[FILENAMELENGTH];
   FILE  *ficresvij;
 char *endptr;  char fileresv[FILENAMELENGTH];
 long lval;  FILE  *ficresvpl;
   char fileresvpl[FILENAMELENGTH];
 #define NR_END 1  char title[MAXLINE];
 #define FREE_ARG char*  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 #define FTOL 1.0e-10  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
   char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
 #define NRANSI   char command[FILENAMELENGTH];
 #define ITMAX 200   int  outcmd=0;
   
 #define TOL 2.0e-4   char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
   
 #define CGOLD 0.3819660   char filelog[FILENAMELENGTH]; /* Log file */
 #define ZEPS 1.0e-10   char filerest[FILENAMELENGTH];
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   char fileregp[FILENAMELENGTH];
   char popfile[FILENAMELENGTH];
 #define GOLD 1.618034   
 #define GLIMIT 100.0   char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 #define TINY 1.0e-20   
   struct timeval start_time, end_time, curr_time, last_time, forecast_time;
 static double maxarg1,maxarg2;  struct timezone tzp;
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  extern int gettimeofday();
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  struct tm tmg, tm, tmf, *gmtime(), *localtime();
     long time_value;
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  extern long time();
 #define rint(a) floor(a+0.5)  char strcurr[80], strfor[80];
   
 static double sqrarg;  char *endptr;
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  long lval;
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   double dval;
 int agegomp= AGEGOMP;  
   #define NR_END 1
 int imx;   #define FREE_ARG char*
 int stepm=1;  #define FTOL 1.0e-10
 /* Stepm, step in month: minimum step interpolation*/  
   #define NRANSI
 int estepm;  #define ITMAX 200
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  
   #define TOL 2.0e-4
 int m,nb;  
 long *num;  #define CGOLD 0.3819660
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  #define ZEPS 1.0e-10
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
 double **pmmij, ***probs;  
 double *ageexmed,*agecens;  #define GOLD 1.618034
 double dateintmean=0;  #define GLIMIT 100.0
   #define TINY 1.0e-20
 double *weight;  
 int **s; /* Status */  static double maxarg1,maxarg2;
 double *agedc, **covar, idx;  #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 double *lsurv, *lpop, *tpop;   
   #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  #define rint(a) floor(a+0.5)
 double ftolhess; /* Tolerance for computing hessian */  
   static double sqrarg;
 /**************** split *************************/  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
 {  int agegomp= AGEGOMP;
   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)  
      the name of the file (name), its extension only (ext) and its first part of the name (finame)  int imx;
   */   int stepm=1;
   char  *ss;                            /* pointer */  /* Stepm, step in month: minimum step interpolation*/
   int   l1, l2;                         /* length counters */  
   int estepm;
   l1 = strlen(path );                   /* length of path */  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  int m,nb;
   if ( ss == NULL ) {                   /* no directory, so determine current directory */  long *num;
     strcpy( name, path );               /* we got the fullname name because no directory */  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  double **pmmij, ***probs;
     /* get current working directory */  double *ageexmed,*agecens;
     /*    extern  char* getcwd ( char *buf , int len);*/  double dateintmean=0;
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  
       return( GLOCK_ERROR_GETCWD );  double *weight;
     }  int **s; /* Status */
     /* got dirc from getcwd*/  double *agedc, **covar, idx;
     printf(" DIRC = %s \n",dirc);  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
   } else {                              /* strip direcotry from path */  double *lsurv, *lpop, *tpop;
     ss++;                               /* after this, the filename */  
     l2 = strlen( ss );                  /* length of filename */  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  double ftolhess; /* Tolerance for computing hessian */
     strcpy( name, ss );         /* save file name */  
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  /**************** split *************************/
     dirc[l1-l2] = 0;                    /* add zero */  static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
     printf(" DIRC2 = %s \n",dirc);  {
   }    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
   /* We add a separator at the end of dirc if not exists */       the name of the file (name), its extension only (ext) and its first part of the name (finame)
   l1 = strlen( dirc );                  /* length of directory */    */
   if( dirc[l1-1] != DIRSEPARATOR ){    char  *ss;                            /* pointer */
     dirc[l1] =  DIRSEPARATOR;    int   l1, l2;                         /* length counters */
     dirc[l1+1] = 0;   
     printf(" DIRC3 = %s \n",dirc);    l1 = strlen(path );                   /* length of path */
   }    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
   ss = strrchr( name, '.' );            /* find last / */    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
   if (ss >0){    if ( ss == NULL ) {                   /* no directory, so determine current directory */
     ss++;      strcpy( name, path );               /* we got the fullname name because no directory */
     strcpy(ext,ss);                     /* save extension */      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
     l1= strlen( name);        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
     l2= strlen(ss)+1;      /* get current working directory */
     strncpy( finame, name, l1-l2);      /*    extern  char* getcwd ( char *buf , int len);*/
     finame[l1-l2]= 0;      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
   }        return( GLOCK_ERROR_GETCWD );
       }
   return( 0 );                          /* we're done */      /* got dirc from getcwd*/
 }      printf(" DIRC = %s \n",dirc);
     } else {                              /* strip direcotry from path */
       ss++;                               /* after this, the filename */
 /******************************************/      l2 = strlen( ss );                  /* length of filename */
       if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 void replace_back_to_slash(char *s, char*t)      strcpy( name, ss );         /* save file name */
 {      strncpy( dirc, path, l1 - l2 );     /* now the directory */
   int i;      dirc[l1-l2] = 0;                    /* add zero */
   int lg=0;      printf(" DIRC2 = %s \n",dirc);
   i=0;    }
   lg=strlen(t);    /* We add a separator at the end of dirc if not exists */
   for(i=0; i<= lg; i++) {    l1 = strlen( dirc );                  /* length of directory */
     (s[i] = t[i]);    if( dirc[l1-1] != DIRSEPARATOR ){
     if (t[i]== '\\') s[i]='/';      dirc[l1] =  DIRSEPARATOR;
   }      dirc[l1+1] = 0;
 }      printf(" DIRC3 = %s \n",dirc);
     }
 int nbocc(char *s, char occ)    ss = strrchr( name, '.' );            /* find last / */
 {    if (ss >0){
   int i,j=0;      ss++;
   int lg=20;      strcpy(ext,ss);                     /* save extension */
   i=0;      l1= strlen( name);
   lg=strlen(s);      l2= strlen(ss)+1;
   for(i=0; i<= lg; i++) {      strncpy( finame, name, l1-l2);
   if  (s[i] == occ ) j++;      finame[l1-l2]= 0;
   }    }
   return j;  
 }    return( 0 );                          /* we're done */
   }
 void cutv(char *u,char *v, char*t, char occ)  
 {  
   /* 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')  
      gives u="abcedf" and v="ghi2j" */  void replace_back_to_slash(char *s, char*t)
   int i,lg,j,p=0;  {
   i=0;    int i;
   for(j=0; j<=strlen(t)-1; j++) {    int lg=0;
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;    i=0;
   }    lg=strlen(t);
     for(i=0; i<= lg; i++) {
   lg=strlen(t);      (s[i] = t[i]);
   for(j=0; j<p; j++) {      if (t[i]== '\\') s[i]='/';
     (u[j] = t[j]);    }
   }  }
      u[p]='\0';  
   int nbocc(char *s, char occ)
    for(j=0; j<= lg; j++) {  {
     if (j>=(p+1))(v[j-p-1] = t[j]);    int i,j=0;
   }    int lg=20;
 }    i=0;
     lg=strlen(s);
 /********************** nrerror ********************/    for(i=0; i<= lg; i++) {
     if  (s[i] == occ ) j++;
 void nrerror(char error_text[])    }
 {    return j;
   fprintf(stderr,"ERREUR ...\n");  }
   fprintf(stderr,"%s\n",error_text);  
   exit(EXIT_FAILURE);  void cutv(char *u,char *v, char*t, char occ)
 }  {
 /*********************** vector *******************/    /* cuts string t into u and v where u ends before first occurence of char 'occ'
 double *vector(int nl, int nh)       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
 {       gives u="abcedf" and v="ghi2j" */
   double *v;    int i,lg,j,p=0;
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));    i=0;
   if (!v) nrerror("allocation failure in vector");    for(j=0; j<=strlen(t)-1; j++) {
   return v-nl+NR_END;      if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
 }    }
   
 /************************ free vector ******************/    lg=strlen(t);
 void free_vector(double*v, int nl, int nh)    for(j=0; j<p; j++) {
 {      (u[j] = t[j]);
   free((FREE_ARG)(v+nl-NR_END));    }
 }       u[p]='\0';
   
 /************************ivector *******************************/     for(j=0; j<= lg; j++) {
 int *ivector(long nl,long nh)      if (j>=(p+1))(v[j-p-1] = t[j]);
 {    }
   int *v;  }
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));  
   if (!v) nrerror("allocation failure in ivector");  /********************** nrerror ********************/
   return v-nl+NR_END;  
 }  void nrerror(char error_text[])
   {
 /******************free ivector **************************/    fprintf(stderr,"ERREUR ...\n");
 void free_ivector(int *v, long nl, long nh)    fprintf(stderr,"%s\n",error_text);
 {    exit(EXIT_FAILURE);
   free((FREE_ARG)(v+nl-NR_END));  }
 }  /*********************** vector *******************/
   double *vector(int nl, int nh)
 /************************lvector *******************************/  {
 long *lvector(long nl,long nh)    double *v;
 {    v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
   long *v;    if (!v) nrerror("allocation failure in vector");
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));    return v-nl+NR_END;
   if (!v) nrerror("allocation failure in ivector");  }
   return v-nl+NR_END;  
 }  /************************ free vector ******************/
   void free_vector(double*v, int nl, int nh)
 /******************free lvector **************************/  {
 void free_lvector(long *v, long nl, long nh)    free((FREE_ARG)(v+nl-NR_END));
 {  }
   free((FREE_ARG)(v+nl-NR_END));  
 }  /************************ivector *******************************/
   int *ivector(long nl,long nh)
 /******************* imatrix *******************************/  {
 int **imatrix(long nrl, long nrh, long ncl, long nch)     int *v;
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */     v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 {     if (!v) nrerror("allocation failure in ivector");
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;     return v-nl+NR_END;
   int **m;   }
     
   /* allocate pointers to rows */   /******************free ivector **************************/
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));   void free_ivector(int *v, long nl, long nh)
   if (!m) nrerror("allocation failure 1 in matrix()");   {
   m += NR_END;     free((FREE_ARG)(v+nl-NR_END));
   m -= nrl;   }
     
     /************************lvector *******************************/
   /* allocate rows and set pointers to them */   long *lvector(long nl,long nh)
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));   {
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");     long *v;
   m[nrl] += NR_END;     v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
   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 pointer to array of pointers to rows */   /******************free lvector **************************/
   return m;   void free_lvector(long *v, long nl, long nh)
 }   {
     free((FREE_ARG)(v+nl-NR_END));
 /****************** free_imatrix *************************/  }
 void free_imatrix(m,nrl,nrh,ncl,nch)  
       int **m;  /******************* imatrix *******************************/
       long nch,ncl,nrh,nrl;   int **imatrix(long nrl, long nrh, long ncl, long nch)
      /* free an int matrix allocated by imatrix() */        /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
 {   {
   free((FREE_ARG) (m[nrl]+ncl-NR_END));     long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
   free((FREE_ARG) (m+nrl-NR_END));     int **m;
 }    
     /* allocate pointers to rows */
 /******************* matrix *******************************/    m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
 double **matrix(long nrl, long nrh, long ncl, long nch)    if (!m) nrerror("allocation failure 1 in matrix()");
 {    m += NR_END;
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;    m -= nrl;
   double **m;   
    
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));    /* allocate rows and set pointers to them */
   if (!m) nrerror("allocation failure 1 in matrix()");    m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
   m += NR_END;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   m -= nrl;    m[nrl] += NR_END;
     m[nrl] -= ncl;
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));   
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
   m[nrl] += NR_END;   
   m[nrl] -= ncl;    /* return pointer to array of pointers to rows */
     return m;
   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_imatrix *************************/
    */  void free_imatrix(m,nrl,nrh,ncl,nch)
 }        int **m;
         long nch,ncl,nrh,nrl;
 /*************************free matrix ************************/       /* free an int matrix allocated by imatrix() */
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)  {
 {    free((FREE_ARG) (m[nrl]+ncl-NR_END));
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    free((FREE_ARG) (m+nrl-NR_END));
   free((FREE_ARG)(m+nrl-NR_END));  }
 }  
   /******************* matrix *******************************/
 /******************* ma3x *******************************/  double **matrix(long nrl, long nrh, long ncl, long nch)
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)  {
 {    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;    double **m;
   double ***m;  
     m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));    if (!m) nrerror("allocation failure 1 in matrix()");
   if (!m) nrerror("allocation failure 1 in matrix()");    m += NR_END;
   m += NR_END;    m -= nrl;
   m -= nrl;  
     m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    m[nrl] += NR_END;
   m[nrl] += NR_END;    m[nrl] -= ncl;
   m[nrl] -= ncl;  
     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   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])
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));     */
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");  }
   m[nrl][ncl] += NR_END;  
   m[nrl][ncl] -= nll;  /*************************free matrix ************************/
   for (j=ncl+1; j<=nch; j++)   void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
     m[nrl][j]=m[nrl][j-1]+nlay;  {
       free((FREE_ARG)(m[nrl]+ncl-NR_END));
   for (i=nrl+1; i<=nrh; i++) {    free((FREE_ARG)(m+nrl-NR_END));
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;  }
     for (j=ncl+1; j<=nch; j++)   
       m[i][j]=m[i][j-1]+nlay;  /******************* ma3x *******************************/
   }  double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
   return m;   {
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])    long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)    double ***m;
   */  
 }    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
     if (!m) nrerror("allocation failure 1 in matrix()");
 /*************************free ma3x ************************/    m += NR_END;
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)    m -= nrl;
 {  
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   free((FREE_ARG)(m+nrl-NR_END));    m[nrl] += NR_END;
 }    m[nrl] -= ncl;
   
 /*************** function subdirf ***********/    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 char *subdirf(char fileres[])  
 {    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
   /* Caution optionfilefiname is hidden */    if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
   strcpy(tmpout,optionfilefiname);    m[nrl][ncl] += NR_END;
   strcat(tmpout,"/"); /* Add to the right */    m[nrl][ncl] -= nll;
   strcat(tmpout,fileres);    for (j=ncl+1; j<=nch; j++)
   return tmpout;      m[nrl][j]=m[nrl][j-1]+nlay;
 }   
     for (i=nrl+1; i<=nrh; i++) {
 /*************** function subdirf2 ***********/      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 char *subdirf2(char fileres[], char *preop)      for (j=ncl+1; j<=nch; j++)
 {        m[i][j]=m[i][j-1]+nlay;
       }
   /* Caution optionfilefiname is hidden */    return m;
   strcpy(tmpout,optionfilefiname);    /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
   strcat(tmpout,"/");             &(m[i][j][k]) <=> *((*(m+i) + j)+k)
   strcat(tmpout,preop);    */
   strcat(tmpout,fileres);  }
   return tmpout;  
 }  /*************************free ma3x ************************/
   void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 /*************** function subdirf3 ***********/  {
 char *subdirf3(char fileres[], char *preop, char *preop2)    free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 {    free((FREE_ARG)(m[nrl]+ncl-NR_END));
       free((FREE_ARG)(m+nrl-NR_END));
   /* Caution optionfilefiname is hidden */  }
   strcpy(tmpout,optionfilefiname);  
   strcat(tmpout,"/");  /*************** function subdirf ***********/
   strcat(tmpout,preop);  char *subdirf(char fileres[])
   strcat(tmpout,preop2);  {
   strcat(tmpout,fileres);    /* Caution optionfilefiname is hidden */
   return tmpout;    strcpy(tmpout,optionfilefiname);
 }    strcat(tmpout,"/"); /* Add to the right */
     strcat(tmpout,fileres);
 /***************** f1dim *************************/    return tmpout;
 extern int ncom;   }
 extern double *pcom,*xicom;  
 extern double (*nrfunc)(double []);   /*************** function subdirf2 ***********/
    char *subdirf2(char fileres[], char *preop)
 double f1dim(double x)   {
 {    
   int j;     /* Caution optionfilefiname is hidden */
   double f;    strcpy(tmpout,optionfilefiname);
   double *xt;     strcat(tmpout,"/");
      strcat(tmpout,preop);
   xt=vector(1,ncom);     strcat(tmpout,fileres);
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];     return tmpout;
   f=(*nrfunc)(xt);   }
   free_vector(xt,1,ncom);   
   return f;   /*************** function subdirf3 ***********/
 }   char *subdirf3(char fileres[], char *preop, char *preop2)
   {
 /*****************brent *************************/   
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)     /* Caution optionfilefiname is hidden */
 {     strcpy(tmpout,optionfilefiname);
   int iter;     strcat(tmpout,"/");
   double a,b,d,etemp;    strcat(tmpout,preop);
   double fu,fv,fw,fx;    strcat(tmpout,preop2);
   double ftemp;    strcat(tmpout,fileres);
   double p,q,r,tol1,tol2,u,v,w,x,xm;     return tmpout;
   double e=0.0;   }
    
   a=(ax < cx ? ax : cx);   /***************** f1dim *************************/
   b=(ax > cx ? ax : cx);   extern int ncom;
   x=w=v=bx;   extern double *pcom,*xicom;
   fw=fv=fx=(*f)(x);   extern double (*nrfunc)(double []);
   for (iter=1;iter<=ITMAX;iter++) {    
     xm=0.5*(a+b);   double f1dim(double x)
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);   {
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/    int j;
     printf(".");fflush(stdout);    double f;
     fprintf(ficlog,".");fflush(ficlog);    double *xt;
 #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);    xt=vector(1,ncom);
     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);    for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */    f=(*nrfunc)(xt);
 #endif    free_vector(xt,1,ncom);
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){     return f;
       *xmin=x;   }
       return fx;   
     }   /*****************brent *************************/
     ftemp=fu;  double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
     if (fabs(e) > tol1) {   {
       r=(x-w)*(fx-fv);     int iter;
       q=(x-v)*(fx-fw);     double a,b,d,etemp;
       p=(x-v)*q-(x-w)*r;     double fu,fv,fw,fx;
       q=2.0*(q-r);     double ftemp;
       if (q > 0.0) p = -p;     double p,q,r,tol1,tol2,u,v,w,x,xm;
       q=fabs(q);     double e=0.0;
       etemp=e;    
       e=d;     a=(ax < cx ? ax : cx);
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))     b=(ax > cx ? ax : cx);
         d=CGOLD*(e=(x >= xm ? a-x : b-x));     x=w=v=bx;
       else {     fw=fv=fx=(*f)(x);
         d=p/q;     for (iter=1;iter<=ITMAX;iter++) {
         u=x+d;       xm=0.5*(a+b);
         if (u-a < tol2 || b-u < tol2)       tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
           d=SIGN(tol1,xm-x);       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
       }       printf(".");fflush(stdout);
     } else {       fprintf(ficlog,".");fflush(ficlog);
       d=CGOLD*(e=(x >= xm ? a-x : b-x));   #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);
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));       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);
     fu=(*f)(u);       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
     if (fu <= fx) {   #endif
       if (u >= x) a=x; else b=x;       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
       SHFT(v,w,x,u)         *xmin=x;
         SHFT(fv,fw,fx,fu)         return fx;
         } else {       }
           if (u < x) a=u; else b=u;       ftemp=fu;
           if (fu <= fw || w == x) {       if (fabs(e) > tol1) {
             v=w;         r=(x-w)*(fx-fv);
             w=u;         q=(x-v)*(fx-fw);
             fv=fw;         p=(x-v)*q-(x-w)*r;
             fw=fu;         q=2.0*(q-r);
           } else if (fu <= fv || v == x || v == w) {         if (q > 0.0) p = -p;
             v=u;         q=fabs(q);
             fv=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));
   nrerror("Too many iterations in brent");         else {
   *xmin=x;           d=p/q;
   return fx;           u=x+d;
 }           if (u-a < tol2 || b-u < tol2)
             d=SIGN(tol1,xm-x);
 /****************** mnbrak ***********************/        }
       } else {
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,         d=CGOLD*(e=(x >= xm ? a-x : b-x));
             double (*func)(double))       }
 {       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
   double ulim,u,r,q, dum;      fu=(*f)(u);
   double fu;       if (fu <= fx) {
          if (u >= x) a=x; else b=x;
   *fa=(*func)(*ax);         SHFT(v,w,x,u)
   *fb=(*func)(*bx);           SHFT(fv,fw,fx,fu)
   if (*fb > *fa) {           } else {
     SHFT(dum,*ax,*bx,dum)             if (u < x) a=u; else b=u;
       SHFT(dum,*fb,*fa,dum)             if (fu <= fw || w == x) {
       }               v=w;
   *cx=(*bx)+GOLD*(*bx-*ax);               w=u;
   *fc=(*func)(*cx);               fv=fw;
   while (*fb > *fc) {               fw=fu;
     r=(*bx-*ax)*(*fb-*fc);             } else if (fu <= fv || v == x || v == w) {
     q=(*bx-*cx)*(*fb-*fa);               v=u;
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/               fv=fu;
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));             }
     ulim=(*bx)+GLIMIT*(*cx-*bx);           }
     if ((*bx-u)*(u-*cx) > 0.0) {     }
       fu=(*func)(u);     nrerror("Too many iterations in brent");
     } else if ((*cx-u)*(u-ulim) > 0.0) {     *xmin=x;
       fu=(*func)(u);     return fx;
       if (fu < *fc) {   }
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))   
           SHFT(*fb,*fc,fu,(*func)(u))   /****************** mnbrak ***********************/
           }   
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
       u=ulim;               double (*func)(double))
       fu=(*func)(u);   {
     } else {     double ulim,u,r,q, dum;
       u=(*cx)+GOLD*(*cx-*bx);     double fu;
       fu=(*func)(u);    
     }     *fa=(*func)(*ax);
     SHFT(*ax,*bx,*cx,u)     *fb=(*func)(*bx);
       SHFT(*fa,*fb,*fc,fu)     if (*fb > *fa) {
       }       SHFT(dum,*ax,*bx,dum)
 }         SHFT(dum,*fb,*fa,dum)
         }
 /*************** linmin ************************/    *cx=(*bx)+GOLD*(*bx-*ax);
     *fc=(*func)(*cx);
 int ncom;     while (*fb > *fc) {
 double *pcom,*xicom;      r=(*bx-*ax)*(*fb-*fc);
 double (*nrfunc)(double []);       q=(*bx-*cx)*(*fb-*fa);
        u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
 {       ulim=(*bx)+GLIMIT*(*cx-*bx);
   double brent(double ax, double bx, double cx,       if ((*bx-u)*(u-*cx) > 0.0) {
                double (*f)(double), double tol, double *xmin);         fu=(*func)(u);
   double f1dim(double x);       } else if ((*cx-u)*(u-ulim) > 0.0) {
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,         fu=(*func)(u);
               double *fc, double (*func)(double));         if (fu < *fc) {
   int j;           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
   double xx,xmin,bx,ax;             SHFT(*fb,*fc,fu,(*func)(u))
   double fx,fb,fa;            }
        } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
   ncom=n;         u=ulim;
   pcom=vector(1,n);         fu=(*func)(u);
   xicom=vector(1,n);       } else {
   nrfunc=func;         u=(*cx)+GOLD*(*cx-*bx);
   for (j=1;j<=n;j++) {         fu=(*func)(u);
     pcom[j]=p[j];       }
     xicom[j]=xi[j];       SHFT(*ax,*bx,*cx,u)
   }         SHFT(*fa,*fb,*fc,fu)
   ax=0.0;         }
   xx=1.0;   }
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);   
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);   /*************** linmin ************************/
 #ifdef DEBUG  
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  int ncom;
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);  double *pcom,*xicom;
 #endif  double (*nrfunc)(double []);
   for (j=1;j<=n;j++) {    
     xi[j] *= xmin;   void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
     p[j] += xi[j];   {
   }     double brent(double ax, double bx, double cx,
   free_vector(xicom,1,n);                  double (*f)(double), double tol, double *xmin);
   free_vector(pcom,1,n);     double f1dim(double x);
 }     void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
                 double *fc, double (*func)(double));
 char *asc_diff_time(long time_sec, char ascdiff[])    int j;
 {    double xx,xmin,bx,ax;
   long sec_left, days, hours, minutes;    double fx,fb,fa;
   days = (time_sec) / (60*60*24);   
   sec_left = (time_sec) % (60*60*24);    ncom=n;
   hours = (sec_left) / (60*60) ;    pcom=vector(1,n);
   sec_left = (sec_left) %(60*60);    xicom=vector(1,n);
   minutes = (sec_left) /60;    nrfunc=func;
   sec_left = (sec_left) % (60);    for (j=1;j<=n;j++) {
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);        pcom[j]=p[j];
   return ascdiff;      xicom[j]=xi[j];
 }    }
     ax=0.0;
 /*************** powell ************************/    xx=1.0;
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
             double (*func)(double []))     *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
 {   #ifdef DEBUG
   void linmin(double p[], double xi[], int n, double *fret,     printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
               double (*func)(double []));     fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   int i,ibig,j;   #endif
   double del,t,*pt,*ptt,*xit;    for (j=1;j<=n;j++) {
   double fp,fptt;      xi[j] *= xmin;
   double *xits;      p[j] += xi[j];
   int niterf, itmp;    }
     free_vector(xicom,1,n);
   pt=vector(1,n);     free_vector(pcom,1,n);
   ptt=vector(1,n);   }
   xit=vector(1,n);   
   xits=vector(1,n);   char *asc_diff_time(long time_sec, char ascdiff[])
   *fret=(*func)(p);   {
   for (j=1;j<=n;j++) pt[j]=p[j];     long sec_left, days, hours, minutes;
   for (*iter=1;;++(*iter)) {     days = (time_sec) / (60*60*24);
     fp=(*fret);     sec_left = (time_sec) % (60*60*24);
     ibig=0;     hours = (sec_left) / (60*60) ;
     del=0.0;     sec_left = (sec_left) %(60*60);
     last_time=curr_time;    minutes = (sec_left) /60;
     (void) gettimeofday(&curr_time,&tzp);    sec_left = (sec_left) % (60);
     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);    sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
     /*    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);    return ascdiff;
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);  }
     */  
    for (i=1;i<=n;i++) {  /*************** powell ************************/
       printf(" %d %.12f",i, p[i]);  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
       fprintf(ficlog," %d %.12lf",i, p[i]);              double (*func)(double []))
       fprintf(ficrespow," %.12lf", p[i]);  {
     }    void linmin(double p[], double xi[], int n, double *fret,
     printf("\n");                double (*func)(double []));
     fprintf(ficlog,"\n");    int i,ibig,j;
     fprintf(ficrespow,"\n");fflush(ficrespow);    double del,t,*pt,*ptt,*xit;
     if(*iter <=3){    double fp,fptt;
       tm = *localtime(&curr_time.tv_sec);    double *xits;
       strcpy(strcurr,asctime(&tm));    int niterf, itmp;
 /*       asctime_r(&tm,strcurr); */  
       forecast_time=curr_time;     pt=vector(1,n);
       itmp = strlen(strcurr);    ptt=vector(1,n);
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */    xit=vector(1,n);
         strcurr[itmp-1]='\0';    xits=vector(1,n);
       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);    *fret=(*func)(p);
       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++) pt[j]=p[j];
       for(niterf=10;niterf<=30;niterf+=10){    for (*iter=1;;++(*iter)) {
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);      fp=(*fret);
         tmf = *localtime(&forecast_time.tv_sec);      ibig=0;
 /*      asctime_r(&tmf,strfor); */      del=0.0;
         strcpy(strfor,asctime(&tmf));      last_time=curr_time;
         itmp = strlen(strfor);      (void) gettimeofday(&curr_time,&tzp);
         if(strfor[itmp-1]=='\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);
         strfor[itmp-1]='\0';      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);
         printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
         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 (i=1;i<=n;i++) {
       }        printf(" %d %.12f",i, p[i]);
     }        fprintf(ficlog," %d %.12lf",i, p[i]);
     for (i=1;i<=n;i++) {         fprintf(ficrespow," %.12lf", p[i]);
       for (j=1;j<=n;j++) xit[j]=xi[j][i];       }
       fptt=(*fret);       printf("\n");
 #ifdef DEBUG      fprintf(ficlog,"\n");
       printf("fret=%lf \n",*fret);      fprintf(ficrespow,"\n");fflush(ficrespow);
       fprintf(ficlog,"fret=%lf \n",*fret);      if(*iter <=3){
 #endif        tm = *localtime(&curr_time.tv_sec);
       printf("%d",i);fflush(stdout);        strcpy(strcurr,asctime(&tm));
       fprintf(ficlog,"%d",i);fflush(ficlog);  /*       asctime_r(&tm,strcurr); */
       linmin(p,xit,n,fret,func);         forecast_time=curr_time;
       if (fabs(fptt-(*fret)) > del) {         itmp = strlen(strcurr);
         del=fabs(fptt-(*fret));         if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
         ibig=i;           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);
 #ifdef DEBUG        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       printf("%d %.12e",i,(*fret));        for(niterf=10;niterf<=30;niterf+=10){
       fprintf(ficlog,"%d %.12e",i,(*fret));          forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
       for (j=1;j<=n;j++) {          tmf = *localtime(&forecast_time.tv_sec);
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);  /*      asctime_r(&tmf,strfor); */
         printf(" x(%d)=%.12e",j,xit[j]);          strcpy(strfor,asctime(&tmf));
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);          itmp = strlen(strfor);
       }          if(strfor[itmp-1]=='\n')
       for(j=1;j<=n;j++) {          strfor[itmp-1]='\0';
         printf(" p=%.12e",p[j]);          printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
         fprintf(ficlog," p=%.12e",p[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);
       }        }
       printf("\n");      }
       fprintf(ficlog,"\n");      for (i=1;i<=n;i++) {
 #endif        for (j=1;j<=n;j++) xit[j]=xi[j][i];
     }         fptt=(*fret);
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {  #ifdef DEBUG
 #ifdef DEBUG        printf("fret=%lf \n",*fret);
       int k[2],l;        fprintf(ficlog,"fret=%lf \n",*fret);
       k[0]=1;  #endif
       k[1]=-1;        printf("%d",i);fflush(stdout);
       printf("Max: %.12e",(*func)(p));        fprintf(ficlog,"%d",i);fflush(ficlog);
       fprintf(ficlog,"Max: %.12e",(*func)(p));        linmin(p,xit,n,fret,func);
       for (j=1;j<=n;j++) {        if (fabs(fptt-(*fret)) > del) {
         printf(" %.12e",p[j]);          del=fabs(fptt-(*fret));
         fprintf(ficlog," %.12e",p[j]);          ibig=i;
       }        }
       printf("\n");  #ifdef DEBUG
       fprintf(ficlog,"\n");        printf("%d %.12e",i,(*fret));
       for(l=0;l<=1;l++) {        fprintf(ficlog,"%d %.12e",i,(*fret));
         for (j=1;j<=n;j++) {        for (j=1;j<=n;j++) {
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);          printf(" x(%d)=%.12e",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]);          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
         }        }
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        for(j=1;j<=n;j++) {
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));          printf(" p=%.12e",p[j]);
       }          fprintf(ficlog," p=%.12e",p[j]);
 #endif        }
         printf("\n");
         fprintf(ficlog,"\n");
       free_vector(xit,1,n);   #endif
       free_vector(xits,1,n);       }
       free_vector(ptt,1,n);       if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
       free_vector(pt,1,n);   #ifdef DEBUG
       return;         int k[2],l;
     }         k[0]=1;
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");         k[1]=-1;
     for (j=1;j<=n;j++) {         printf("Max: %.12e",(*func)(p));
       ptt[j]=2.0*p[j]-pt[j];         fprintf(ficlog,"Max: %.12e",(*func)(p));
       xit[j]=p[j]-pt[j];         for (j=1;j<=n;j++) {
       pt[j]=p[j];           printf(" %.12e",p[j]);
     }           fprintf(ficlog," %.12e",p[j]);
     fptt=(*func)(ptt);         }
     if (fptt < fp) {         printf("\n");
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);         fprintf(ficlog,"\n");
       if (t < 0.0) {         for(l=0;l<=1;l++) {
         linmin(p,xit,n,fret,func);           for (j=1;j<=n;j++) {
         for (j=1;j<=n;j++) {             ptt[j]=p[j]+(p[j]-pt[j])*k[l];
           xi[j][ibig]=xi[j][n];             printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
           xi[j][n]=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]);
         }          }
 #ifdef DEBUG          printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        }
         for(j=1;j<=n;j++){  #endif
           printf(" %.12e",xit[j]);  
           fprintf(ficlog," %.12e",xit[j]);  
         }        free_vector(xit,1,n);
         printf("\n");        free_vector(xits,1,n);
         fprintf(ficlog,"\n");        free_vector(ptt,1,n);
 #endif        free_vector(pt,1,n);
       }        return;
     }       }
   }       if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
 }       for (j=1;j<=n;j++) {
         ptt[j]=2.0*p[j]-pt[j];
 /**** Prevalence limit (stable or period prevalence)  ****************/        xit[j]=p[j]-pt[j];
         pt[j]=p[j];
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)      }
 {      fptt=(*func)(ptt);
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit      if (fptt < fp) {
      matrix by transitions matrix until convergence is reached */        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
         if (t < 0.0) {
   int i, ii,j,k;          linmin(p,xit,n,fret,func);
   double min, max, maxmin, maxmax,sumnew=0.;          for (j=1;j<=n;j++) {
   double **matprod2();            xi[j][ibig]=xi[j][n];
   double **out, cov[NCOVMAX], **pmij();            xi[j][n]=xit[j];
   double **newm;          }
   double agefin, delaymax=50 ; /* Max number of years to converge */  #ifdef DEBUG
           printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
   for (ii=1;ii<=nlstate+ndeath;ii++)          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
     for (j=1;j<=nlstate+ndeath;j++){          for(j=1;j<=n;j++){
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);            printf(" %.12e",xit[j]);
     }            fprintf(ficlog," %.12e",xit[j]);
           }
    cov[1]=1.;          printf("\n");
            fprintf(ficlog,"\n");
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */  #endif
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){        }
     newm=savm;      }
     /* Covariates have to be included here again */    }
      cov[2]=agefin;  }
     
       for (k=1; k<=cptcovn;k++) {  /**** Prevalence limit (stable or period prevalence)  ****************/
         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]]);*/  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
       }  {
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
       for (k=1; k<=cptcovprod;k++)       matrix by transitions matrix until convergence is reached */
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];  
     int i, ii,j,k;
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/    double min, max, maxmin, maxmax,sumnew=0.;
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/    double **matprod2();
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/    double **out, cov[NCOVMAX], **pmij();
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);    double **newm;
     double agefin, delaymax=50 ; /* Max number of years to converge */
     savm=oldm;  
     oldm=newm;    for (ii=1;ii<=nlstate+ndeath;ii++)
     maxmax=0.;      for (j=1;j<=nlstate+ndeath;j++){
     for(j=1;j<=nlstate;j++){        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       min=1.;      }
       max=0.;  
       for(i=1; i<=nlstate; i++) {     cov[1]=1.;
         sumnew=0;   
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
         prlim[i][j]= newm[i][j]/(1-sumnew);    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
         max=FMAX(max,prlim[i][j]);      newm=savm;
         min=FMIN(min,prlim[i][j]);      /* Covariates have to be included here again */
       }       cov[2]=agefin;
       maxmin=max-min;   
       maxmax=FMAX(maxmax,maxmin);        for (k=1; k<=cptcovn;k++) {
     }          cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
     if(maxmax < ftolpl){          /*      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]]);*/
       return prlim;        }
     }        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
   }        for (k=1; k<=cptcovprod;k++)
 }          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
   
 /*************** transition probabilities ***************/         /*printf("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]);*/
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )        /*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);
   double s1, s2;  
   /*double t34;*/      savm=oldm;
   int i,j,j1, nc, ii, jj;      oldm=newm;
       maxmax=0.;
     for(i=1; i<= nlstate; i++){      for(j=1;j<=nlstate;j++){
       for(j=1; j<i;j++){        min=1.;
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){        max=0.;
           /*s2 += param[i][j][nc]*cov[nc];*/        for(i=1; i<=nlstate; i++) {
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];          sumnew=0;
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
         }          prlim[i][j]= newm[i][j]/(1-sumnew);
         ps[i][j]=s2;          max=FMAX(max,prlim[i][j]);
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */          min=FMIN(min,prlim[i][j]);
       }        }
       for(j=i+1; j<=nlstate+ndeath;j++){        maxmin=max-min;
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){        maxmax=FMAX(maxmax,maxmin);
           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); */      if(maxmax < ftolpl){
         }        return prlim;
         ps[i][j]=s2;      }
       }    }
     }  }
     /*ps[3][2]=1;*/  
       /*************** transition probabilities ***************/
     for(i=1; i<= nlstate; i++){  
       s1=0;  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
       for(j=1; j<i; j++)  {
         s1+=exp(ps[i][j]);    double s1, s2;
       for(j=i+1; j<=nlstate+ndeath; j++)    /*double t34;*/
         s1+=exp(ps[i][j]);    int i,j,j1, nc, ii, jj;
       ps[i][i]=1./(s1+1.);  
       for(j=1; j<i; j++)      for(i=1; i<= nlstate; i++){
         ps[i][j]= exp(ps[i][j])*ps[i][i];        for(j=1; j<i;j++){
       for(j=i+1; j<=nlstate+ndeath; j++)          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
         ps[i][j]= exp(ps[i][j])*ps[i][i];            /*s2 += param[i][j][nc]*cov[nc];*/
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
     } /* end i */  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
               }
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){          ps[i][j]=s2;
       for(jj=1; jj<= nlstate+ndeath; jj++){  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
         ps[ii][jj]=0;        }
         ps[ii][ii]=1;        for(j=i+1; j<=nlstate+ndeath;j++){
       }          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
     }            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); */
           }
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */          ps[i][j]=s2;
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */        }
 /*         printf("ddd %lf ",ps[ii][jj]); */      }
 /*       } */      /*ps[3][2]=1;*/
 /*       printf("\n "); */     
 /*        } */      for(i=1; i<= nlstate; i++){
 /*        printf("\n ");printf("%lf ",cov[2]); */        s1=0;
        /*        for(j=1; j<i; j++)
       for(i=1; i<= npar; i++) printf("%f ",x[i]);          s1+=exp(ps[i][j]);
       goto end;*/        for(j=i+1; j<=nlstate+ndeath; j++)
     return ps;          s1+=exp(ps[i][j]);
 }        ps[i][i]=1./(s1+1.);
         for(j=1; j<i; j++)
 /**************** Product of 2 matrices ******************/          ps[i][j]= exp(ps[i][j])*ps[i][i];
         for(j=i+1; j<=nlstate+ndeath; j++)
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)          ps[i][j]= exp(ps[i][j])*ps[i][i];
 {        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times      } /* end i */
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */     
   /* in, b, out are matrice of pointers which should have been initialized       for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
      before: only the contents of out is modified. The function returns        for(jj=1; jj<= nlstate+ndeath; jj++){
      a pointer to pointers identical to out */          ps[ii][jj]=0;
   long i, j, k;          ps[ii][ii]=1;
   for(i=nrl; i<= nrh; i++)        }
     for(k=ncolol; k<=ncoloh; k++)      }
       for(j=ncl,out[i][k]=0.; j<=nch; j++)     
         out[i][k] +=in[i][j]*b[j][k];  
   /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
   return out;  /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
 }  /*         printf("ddd %lf ",ps[ii][jj]); */
   /*       } */
   /*       printf("\n "); */
 /************* Higher Matrix Product ***************/  /*        } */
   /*        printf("\n ");printf("%lf ",cov[2]); */
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )         /*
 {        for(i=1; i<= npar; i++) printf("%f ",x[i]);
   /* Computes the transition matrix starting at age 'age' over         goto end;*/
      'nhstepm*hstepm*stepm' months (i.e. until      return ps;
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying   }
      nhstepm*hstepm matrices.   
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step   /**************** Product of 2 matrices ******************/
      (typically every 2 years instead of every month which is too big   
      for the memory).  double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
      Model is determined by parameters x and covariates have to be   {
      included manually here.     /* 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(...) */
      */    /* in, b, out are matrice of pointers which should have been initialized
        before: only the contents of out is modified. The function returns
   int i, j, d, h, k;       a pointer to pointers identical to out */
   double **out, cov[NCOVMAX];    long i, j, k;
   double **newm;    for(i=nrl; i<= nrh; i++)
       for(k=ncolol; k<=ncoloh; k++)
   /* Hstepm could be zero and should return the unit matrix */        for(j=ncl,out[i][k]=0.; j<=nch; j++)
   for (i=1;i<=nlstate+ndeath;i++)          out[i][k] +=in[i][j]*b[j][k];
     for (j=1;j<=nlstate+ndeath;j++){  
       oldm[i][j]=(i==j ? 1.0 : 0.0);    return out;
       po[i][j][0]=(i==j ? 1.0 : 0.0);  }
     }  
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */  
   for(h=1; h <=nhstepm; h++){  /************* Higher Matrix Product ***************/
     for(d=1; d <=hstepm; d++){  
       newm=savm;  double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
       /* Covariates have to be included here again */  {
       cov[1]=1.;    /* Computes the transition matrix starting at age 'age' over
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;       'nhstepm*hstepm*stepm' months (i.e. until
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
       for (k=1; k<=cptcovage;k++)       nhstepm*hstepm matrices.
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
       for (k=1; k<=cptcovprod;k++)       (typically every 2 years instead of every month which is too big
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];       for the memory).
        Model is determined by parameters x and covariates have to be
        included manually here.
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/  
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/       */
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,   
                    pmij(pmmij,cov,ncovmodel,x,nlstate));    int i, j, d, h, k;
       savm=oldm;    double **out, cov[NCOVMAX];
       oldm=newm;    double **newm;
     }  
     for(i=1; i<=nlstate+ndeath; i++)    /* Hstepm could be zero and should return the unit matrix */
       for(j=1;j<=nlstate+ndeath;j++) {    for (i=1;i<=nlstate+ndeath;i++)
         po[i][j][h]=newm[i][j];      for (j=1;j<=nlstate+ndeath;j++){
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);        oldm[i][j]=(i==j ? 1.0 : 0.0);
          */        po[i][j][0]=(i==j ? 1.0 : 0.0);
       }      }
   } /* end h */    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
   return po;    for(h=1; h <=nhstepm; h++){
 }      for(d=1; d <=hstepm; d++){
         newm=savm;
         /* Covariates have to be included here again */
 /*************** log-likelihood *************/        cov[1]=1.;
 double func( double *x)        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 {        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
   int i, ii, j, k, mi, d, kk;        for (k=1; k<=cptcovage;k++)
   double l, ll[NLSTATEMAX], cov[NCOVMAX];          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
   double **out;        for (k=1; k<=cptcovprod;k++)
   double sw; /* Sum of weights */          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
   double lli; /* Individual log likelihood */  
   int s1, s2;  
   double bbh, survp;        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
   long ipmx;        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
   /*extern weight */        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
   /* We are differentiating ll according to initial status */                     pmij(pmmij,cov,ncovmodel,x,nlstate));
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/        savm=oldm;
   /*for(i=1;i<imx;i++)         oldm=newm;
     printf(" %d\n",s[4][i]);      }
   */      for(i=1; i<=nlstate+ndeath; i++)
   cov[1]=1.;        for(j=1;j<=nlstate+ndeath;j++) {
           po[i][j][h]=newm[i][j];
   for(k=1; k<=nlstate; k++) ll[k]=0.;          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
            */
   if(mle==1){        }
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){    } /* end h */
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];    return po;
       for(mi=1; mi<= wav[i]-1; mi++){  }
         for (ii=1;ii<=nlstate+ndeath;ii++)  
           for (j=1;j<=nlstate+ndeath;j++){  
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);  /*************** log-likelihood *************/
             savm[ii][j]=(ii==j ? 1.0 : 0.0);  double func( double *x)
           }  {
         for(d=0; d<dh[mi][i]; d++){    int i, ii, j, k, mi, d, kk;
           newm=savm;    double l, ll[NLSTATEMAX], cov[NCOVMAX];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    double **out;
           for (kk=1; kk<=cptcovage;kk++) {    double sw; /* Sum of weights */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    double lli; /* Individual log likelihood */
           }    int s1, s2;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    double bbh, survp;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    long ipmx;
           savm=oldm;    /*extern weight */
           oldm=newm;    /* We are differentiating ll according to initial status */
         } /* end mult */    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
           /*for(i=1;i<imx;i++)
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */      printf(" %d\n",s[4][i]);
         /* But now since version 0.9 we anticipate for bias at large stepm.    */
          * If stepm is larger than one month (smallest stepm) and if the exact delay     cov[1]=1.;
          * (in months) between two waves is not a multiple of stepm, we rounded to   
          * the nearest (and in case of equal distance, to the lowest) interval but now    for(k=1; k<=nlstate; k++) ll[k]=0.;
          * we keep into memory the bias bh[mi][i] and also the previous matrix product  
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the    if(mle==1){
          * probability in order to take into account the bias as a fraction of the way      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
          * -stepm/2 to stepm/2 .        for(mi=1; mi<= wav[i]-1; mi++){
          * For stepm=1 the results are the same as for previous versions of Imach.          for (ii=1;ii<=nlstate+ndeath;ii++)
          * For stepm > 1 the results are less biased than in previous versions.             for (j=1;j<=nlstate+ndeath;j++){
          */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         s1=s[mw[mi][i]][i];              savm[ii][j]=(ii==j ? 1.0 : 0.0);
         s2=s[mw[mi+1][i]][i];            }
         bbh=(double)bh[mi][i]/(double)stepm;           for(d=0; d<dh[mi][i]; d++){
         /* bias bh is positive if real duration            newm=savm;
          * is higher than the multiple of stepm and negative otherwise.            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
          */            for (kk=1; kk<=cptcovage;kk++) {
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         if( s2 > nlstate){             }
           /* i.e. if s2 is a death state and if the date of death is known             out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
              then the contribution to the likelihood is the probability to                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
              die between last step unit time and current  step unit time,             savm=oldm;
              which is also equal to probability to die before dh             oldm=newm;
              minus probability to die before dh-stepm .           } /* end mult */
              In version up to 0.92 likelihood was computed       
         as if date of death was unknown. Death was treated as any other          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
         health state: the date of the interview describes the actual state          /* But now since version 0.9 we anticipate for bias at large stepm.
         and not the date of a change in health state. The former idea was           * If stepm is larger than one month (smallest stepm) and if the exact delay
         to consider that at each interview the state was recorded           * (in months) between two waves is not a multiple of stepm, we rounded to
         (healthy, disable or death) and IMaCh was corrected; but when we           * the nearest (and in case of equal distance, to the lowest) interval but now
         introduced the exact date of death then we should have modified           * we keep into memory the bias bh[mi][i] and also the previous matrix product
         the contribution of an exact death to the likelihood. This new           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
         contribution is smaller and very dependent of the step unit           * probability in order to take into account the bias as a fraction of the way
         stepm. It is no more the probability to die between last interview           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
         and month of death but the probability to survive from last           * -stepm/2 to stepm/2 .
         interview up to one month before death multiplied by the           * For stepm=1 the results are the same as for previous versions of Imach.
         probability to die within a month. Thanks to Chris           * For stepm > 1 the results are less biased than in previous versions.
         Jackson for correcting this bug.  Former versions increased           */
         mortality artificially. The bad side is that we add another loop          s1=s[mw[mi][i]][i];
         which slows down the processing. The difference can be up to 10%          s2=s[mw[mi+1][i]][i];
         lower mortality.          bbh=(double)bh[mi][i]/(double)stepm;
           */          /* bias bh is positive if real duration
           lli=log(out[s1][s2] - savm[s1][s2]);           * is higher than the multiple of stepm and negative otherwise.
            */
           /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
         } else if  (s2==-2) {          if( s2 > nlstate){
           for (j=1,survp=0. ; j<=nlstate; j++)             /* i.e. if s2 is a death state and if the date of death is known
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];               then the contribution to the likelihood is the probability to
           /*survp += out[s1][j]; */               die between last step unit time and current  step unit time,
           lli= log(survp);               which is also equal to probability to die before dh
         }               minus probability to die before dh-stepm .
                        In version up to 0.92 likelihood was computed
         else if  (s2==-4) {           as if date of death was unknown. Death was treated as any other
           for (j=3,survp=0. ; j<=nlstate; j++)            health state: the date of the interview describes the actual state
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          and not the date of a change in health state. The former idea was
           lli= log(survp);           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
         else if  (s2==-5) {           the contribution of an exact death to the likelihood. This new
           for (j=1,survp=0. ; j<=2; j++)            contribution is smaller and very dependent of the step unit
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          stepm. It is no more the probability to die between last interview
           lli= log(survp);           and month of death but the probability to survive from last
         }           interview up to one month before death multiplied by the
                   probability to die within a month. Thanks to Chris
         else{          Jackson for correcting this bug.  Former versions increased
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */          mortality artificially. The bad side is that we add another loop
           /*  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 */          which slows down the processing. The difference can be up to 10%
         }           lower mortality.
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/            */
         /*if(lli ==000.0)*/            lli=log(out[s1][s2] - savm[s1][s2]);
         /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */  
         ipmx +=1;  
         sw += weight[i];          } else if  (s2==-2) {
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            for (j=1,survp=0. ; j<=nlstate; j++)
       } /* end of wave */              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
     } /* end of individual */            /*survp += out[s1][j]; */
   }  else if(mle==2){            lli= log(survp);
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          }
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];         
       for(mi=1; mi<= wav[i]-1; mi++){          else if  (s2==-4) {
         for (ii=1;ii<=nlstate+ndeath;ii++)            for (j=3,survp=0. ; j<=nlstate; j++)  
           for (j=1;j<=nlstate+ndeath;j++){              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);            lli= log(survp);
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          }
           }  
         for(d=0; d<=dh[mi][i]; d++){          else if  (s2==-5) {
           newm=savm;            for (j=1,survp=0. ; j<=2; j++)  
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           for (kk=1; kk<=cptcovage;kk++) {            lli= log(survp);
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          }
           }         
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          else{
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
           savm=oldm;            /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
           oldm=newm;          }
         } /* end mult */          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                 /*if(lli ==000.0)*/
         s1=s[mw[mi][i]][i];          /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
         s2=s[mw[mi+1][i]][i];          ipmx +=1;
         bbh=(double)bh[mi][i]/(double)stepm;           sw += weight[i];
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         ipmx +=1;        } /* end of wave */
         sw += weight[i];      } /* end of individual */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;    }  else if(mle==2){
       } /* end of wave */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
     } /* end of individual */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   }  else if(mle==3){  /* exponential inter-extrapolation */        for(mi=1; mi<= wav[i]-1; mi++){
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          for (ii=1;ii<=nlstate+ndeath;ii++)
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            for (j=1;j<=nlstate+ndeath;j++){
       for(mi=1; mi<= wav[i]-1; mi++){              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         for (ii=1;ii<=nlstate+ndeath;ii++)              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           for (j=1;j<=nlstate+ndeath;j++){            }
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          for(d=0; d<=dh[mi][i]; d++){
             savm[ii][j]=(ii==j ? 1.0 : 0.0);            newm=savm;
           }            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         for(d=0; d<dh[mi][i]; d++){            for (kk=1; kk<=cptcovage;kk++) {
           newm=savm;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            }
           for (kk=1; kk<=cptcovage;kk++) {            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           }            savm=oldm;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,            oldm=newm;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          } /* end mult */
           savm=oldm;       
           oldm=newm;          s1=s[mw[mi][i]][i];
         } /* end mult */          s2=s[mw[mi+1][i]][i];
                 bbh=(double)bh[mi][i]/(double)stepm;
         s1=s[mw[mi][i]][i];          lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
         s2=s[mw[mi+1][i]][i];          ipmx +=1;
         bbh=(double)bh[mi][i]/(double)stepm;           sw += weight[i];
         lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         ipmx +=1;        } /* end of wave */
         sw += weight[i];      } /* end of individual */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;    }  else if(mle==3){  /* exponential inter-extrapolation */
       } /* end of wave */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
     } /* end of individual */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   }else if (mle==4){  /* ml=4 no inter-extrapolation */        for(mi=1; mi<= wav[i]-1; mi++){
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          for (ii=1;ii<=nlstate+ndeath;ii++)
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            for (j=1;j<=nlstate+ndeath;j++){
       for(mi=1; mi<= wav[i]-1; mi++){              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         for (ii=1;ii<=nlstate+ndeath;ii++)              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           for (j=1;j<=nlstate+ndeath;j++){            }
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          for(d=0; d<dh[mi][i]; d++){
             savm[ii][j]=(ii==j ? 1.0 : 0.0);            newm=savm;
           }            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         for(d=0; d<dh[mi][i]; d++){            for (kk=1; kk<=cptcovage;kk++) {
           newm=savm;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            }
           for (kk=1; kk<=cptcovage;kk++) {            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           }            savm=oldm;
                     oldm=newm;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          } /* end mult */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));       
           savm=oldm;          s1=s[mw[mi][i]][i];
           oldm=newm;          s2=s[mw[mi+1][i]][i];
         } /* end mult */          bbh=(double)bh[mi][i]/(double)stepm;
                 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 */
         s1=s[mw[mi][i]][i];          ipmx +=1;
         s2=s[mw[mi+1][i]][i];          sw += weight[i];
         if( s2 > nlstate){           ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           lli=log(out[s1][s2] - savm[s1][s2]);        } /* end of wave */
         }else{      } /* end of individual */
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */    }else if (mle==4){  /* ml=4 no inter-extrapolation */
         }      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         ipmx +=1;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         sw += weight[i];        for(mi=1; mi<= wav[i]-1; mi++){
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          for (ii=1;ii<=nlstate+ndeath;ii++)
 /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */            for (j=1;j<=nlstate+ndeath;j++){
       } /* end of wave */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     } /* end of individual */              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */            }
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          for(d=0; d<dh[mi][i]; d++){
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            newm=savm;
       for(mi=1; mi<= wav[i]-1; mi++){            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         for (ii=1;ii<=nlstate+ndeath;ii++)            for (kk=1; kk<=cptcovage;kk++) {
           for (j=1;j<=nlstate+ndeath;j++){              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);            }
             savm[ii][j]=(ii==j ? 1.0 : 0.0);         
           }            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         for(d=0; d<dh[mi][i]; d++){                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           newm=savm;            savm=oldm;
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            oldm=newm;
           for (kk=1; kk<=cptcovage;kk++) {          } /* end mult */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];       
           }          s1=s[mw[mi][i]][i];
                   s2=s[mw[mi+1][i]][i];
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          if( s2 > nlstate){
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            lli=log(out[s1][s2] - savm[s1][s2]);
           savm=oldm;          }else{
           oldm=newm;            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
         } /* end mult */          }
                 ipmx +=1;
         s1=s[mw[mi][i]][i];          sw += weight[i];
         s2=s[mw[mi+1][i]][i];          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */  /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
         ipmx +=1;        } /* end of wave */
         sw += weight[i];      } /* end of individual */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
         /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       } /* end of wave */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
     } /* end of individual */        for(mi=1; mi<= wav[i]-1; mi++){
   } /* End of if */          for (ii=1;ii<=nlstate+ndeath;ii++)
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];            for (j=1;j<=nlstate+ndeath;j++){
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   return -l;            }
 }          for(d=0; d<dh[mi][i]; d++){
             newm=savm;
 /*************** log-likelihood *************/            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 double funcone( double *x)            for (kk=1; kk<=cptcovage;kk++) {
 {              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   /* Same as likeli but slower because of a lot of printf and if */            }
   int i, ii, j, k, mi, d, kk;         
   double l, ll[NLSTATEMAX], cov[NCOVMAX];            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   double **out;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   double lli; /* Individual log likelihood */            savm=oldm;
   double llt;            oldm=newm;
   int s1, s2;          } /* end mult */
   double bbh, survp;       
   /*extern weight */          s1=s[mw[mi][i]][i];
   /* We are differentiating ll according to initial status */          s2=s[mw[mi+1][i]][i];
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   /*for(i=1;i<imx;i++)           ipmx +=1;
     printf(" %d\n",s[4][i]);          sw += weight[i];
   */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   cov[1]=1.;          /*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 */
   for(k=1; k<=nlstate; k++) ll[k]=0.;      } /* end of individual */
     } /* End of if */
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     for(mi=1; mi<= wav[i]-1; mi++){    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
       for (ii=1;ii<=nlstate+ndeath;ii++)    return -l;
         for (j=1;j<=nlstate+ndeath;j++){  }
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);  
           savm[ii][j]=(ii==j ? 1.0 : 0.0);  /*************** log-likelihood *************/
         }  double funcone( double *x)
       for(d=0; d<dh[mi][i]; d++){  {
         newm=savm;    /* Same as likeli but slower because of a lot of printf and if */
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    int i, ii, j, k, mi, d, kk;
         for (kk=1; kk<=cptcovage;kk++) {    double l, ll[NLSTATEMAX], cov[NCOVMAX];
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    double **out;
         }    double lli; /* Individual log likelihood */
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    double llt;
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    int s1, s2;
         savm=oldm;    double bbh, survp;
         oldm=newm;    /*extern weight */
       } /* end mult */    /* We are differentiating ll according to initial status */
           /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
       s1=s[mw[mi][i]][i];    /*for(i=1;i<imx;i++)
       s2=s[mw[mi+1][i]][i];      printf(" %d\n",s[4][i]);
       bbh=(double)bh[mi][i]/(double)stepm;     */
       /* bias is positive if real duration    cov[1]=1.;
        * is higher than the multiple of stepm and negative otherwise.  
        */    for(k=1; k<=nlstate; k++) ll[k]=0.;
       if( s2 > nlstate && (mle <5) ){  /* Jackson */  
         lli=log(out[s1][s2] - savm[s1][s2]);    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       } else if  (s2==-2) {      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         for (j=1,survp=0. ; j<=nlstate; j++)       for(mi=1; mi<= wav[i]-1; mi++){
           survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];        for (ii=1;ii<=nlstate+ndeath;ii++)
         lli= log(survp);          for (j=1;j<=nlstate+ndeath;j++){
       }else if (mle==1){            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */            savm[ii][j]=(ii==j ? 1.0 : 0.0);
       } 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 */        for(d=0; d<dh[mi][i]; d++){
       } else if(mle==3){  /* exponential inter-extrapolation */          newm=savm;
         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 */          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       } else if (mle==4){  /* mle=4 no inter-extrapolation */          for (kk=1; kk<=cptcovage;kk++) {
         lli=log(out[s1][s2]); /* Original formula */            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */          }
         lli=log(out[s1][s2]); /* Original formula */          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
       } /* End of if */                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
       ipmx +=1;          savm=oldm;
       sw += weight[i];          oldm=newm;
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;        } /* end mult */
 /*       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){        s1=s[mw[mi][i]][i];
         fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\        s2=s[mw[mi+1][i]][i];
  %11.6f %11.6f %11.6f ", \        bbh=(double)bh[mi][i]/(double)stepm;
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],        /* bias is positive if real duration
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);         * is higher than the multiple of stepm and negative otherwise.
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){         */
           llt +=ll[k]*gipmx/gsw;        if( s2 > nlstate && (mle <5) ){  /* Jackson */
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);          lli=log(out[s1][s2] - savm[s1][s2]);
         }        } else if  (s2==-2) {
         fprintf(ficresilk," %10.6f\n", -llt);          for (j=1,survp=0. ; j<=nlstate; j++)
       }            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
     } /* end of wave */          lli= log(survp);
   } /* end of individual */        }else if (mle==1){
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */        } else if(mle==2){
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          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 */
   if(globpr==0){ /* First time we count the contributions and weights */        } else if(mle==3){  /* exponential inter-extrapolation */
     gipmx=ipmx;          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 */
     gsw=sw;        } else if (mle==4){  /* mle=4 no inter-extrapolation */
   }          lli=log(out[s1][s2]); /* Original formula */
   return -l;        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
 }          lli=log(out[s1][s2]); /* Original formula */
         } /* End of if */
         ipmx +=1;
 /*************** function likelione ***********/        sw += weight[i];
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 {  /*       printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
   /* This routine should help understanding what is done with         if(globpr){
      the selection of individuals/waves and          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
      to check the exact contribution to the likelihood.   %11.6f %11.6f %11.6f ", \
      Plotting could be done.                  num[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]);
   int k;          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
             llt +=ll[k]*gipmx/gsw;
   if(*globpri !=0){ /* Just counts and sums, no printings */            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
     strcpy(fileresilk,"ilk");           }
     strcat(fileresilk,fileres);          fprintf(ficresilk," %10.6f\n", -llt);
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {        }
       printf("Problem with resultfile: %s\n", fileresilk);      } /* end of wave */
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);    } /* end of individual */
     }    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
     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");    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */    if(globpr==0){ /* First time we count the contributions and weights */
     for(k=1; k<=nlstate; k++)       gipmx=ipmx;
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);      gsw=sw;
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");    }
   }    return -l;
   }
   *fretone=(*funcone)(p);  
   if(*globpri !=0){  
     fclose(ficresilk);  /*************** function likelione ***********/
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
     fflush(fichtm);   {
   }     /* This routine should help understanding what is done with
   return;       the selection of individuals/waves and
 }       to check the exact contribution to the likelihood.
        Plotting could be done.
      */
 /*********** Maximum Likelihood Estimation ***************/    int k;
   
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))    if(*globpri !=0){ /* Just counts and sums, no printings */
 {      strcpy(fileresilk,"ilk");
   int i,j, iter;      strcat(fileresilk,fileres);
   double **xi;      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
   double fret;        printf("Problem with resultfile: %s\n", fileresilk);
   double fretone; /* Only one call to likelihood */        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
   /*  char filerespow[FILENAMELENGTH];*/      }
   xi=matrix(1,npar,1,npar);      fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
   for (i=1;i<=npar;i++)      fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
     for (j=1;j<=npar;j++)      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
       xi[i][j]=(i==j ? 1.0 : 0.0);      for(k=1; k<=nlstate; k++)
   printf("Powell\n");  fprintf(ficlog,"Powell\n");        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
   strcpy(filerespow,"pow");       fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
   strcat(filerespow,fileres);    }
   if((ficrespow=fopen(filerespow,"w"))==NULL) {  
     printf("Problem with resultfile: %s\n", filerespow);    *fretone=(*funcone)(p);
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);    if(*globpri !=0){
   }      fclose(ficresilk);
   fprintf(ficrespow,"# Powell\n# iter -2*LL");      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
   for (i=1;i<=nlstate;i++)      fflush(fichtm);
     for(j=1;j<=nlstate+ndeath;j++)    }
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);    return;
   fprintf(ficrespow,"\n");  }
   
   powell(p,xi,npar,ftol,&iter,&fret,func);  
   /*********** Maximum Likelihood Estimation ***************/
   free_matrix(xi,1,npar,1,npar);  
   fclose(ficrespow);  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   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));    int i,j, iter;
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));    double **xi;
     double fret;
 }    double fretone; /* Only one call to likelihood */
     /*  char filerespow[FILENAMELENGTH];*/
 /**** Computes Hessian and covariance matrix ***/    xi=matrix(1,npar,1,npar);
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))    for (i=1;i<=npar;i++)
 {      for (j=1;j<=npar;j++)
   double  **a,**y,*x,pd;        xi[i][j]=(i==j ? 1.0 : 0.0);
   double **hess;    printf("Powell\n");  fprintf(ficlog,"Powell\n");
   int i, j,jk;    strcpy(filerespow,"pow");
   int *indx;    strcat(filerespow,fileres);
     if((ficrespow=fopen(filerespow,"w"))==NULL) {
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);      printf("Problem with resultfile: %s\n", filerespow);
   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
   void lubksb(double **a, int npar, int *indx, double b[]) ;    }
   void ludcmp(double **a, int npar, int *indx, double *d) ;    fprintf(ficrespow,"# Powell\n# iter -2*LL");
   double gompertz(double p[]);    for (i=1;i<=nlstate;i++)
   hess=matrix(1,npar,1,npar);      for(j=1;j<=nlstate+ndeath;j++)
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   printf("\nCalculation of the hessian matrix. Wait...\n");    fprintf(ficrespow,"\n");
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");  
   for (i=1;i<=npar;i++){    powell(p,xi,npar,ftol,&iter,&fret,func);
     printf("%d",i);fflush(stdout);  
     fprintf(ficlog,"%d",i);fflush(ficlog);    free_matrix(xi,1,npar,1,npar);
        fclose(ficrespow);
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);    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));
     /*  printf(" %f ",p[i]);    fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/  
   }  }
     
   for (i=1;i<=npar;i++) {  /**** 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 []))
       if (j>i) {   {
         printf(".%d%d",i,j);fflush(stdout);    double  **a,**y,*x,pd;
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);    double **hess;
         hess[i][j]=hessij(p,delti,i,j,func,npar);    int i, j,jk;
             int *indx;
         hess[j][i]=hess[i][j];      
         /*printf(" %lf ",hess[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);
     }    void lubksb(double **a, int npar, int *indx, double b[]) ;
   }    void ludcmp(double **a, int npar, int *indx, double *d) ;
   printf("\n");    double gompertz(double p[]);
   fprintf(ficlog,"\n");    hess=matrix(1,npar,1,npar);
   
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");    printf("\nCalculation of the hessian matrix. Wait...\n");
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");    fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
       for (i=1;i<=npar;i++){
   a=matrix(1,npar,1,npar);      printf("%d",i);fflush(stdout);
   y=matrix(1,npar,1,npar);      fprintf(ficlog,"%d",i);fflush(ficlog);
   x=vector(1,npar);     
   indx=ivector(1,npar);       hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
   for (i=1;i<=npar;i++)     
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];      /*  printf(" %f ",p[i]);
   ludcmp(a,npar,indx,&pd);          printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
     }
   for (j=1;j<=npar;j++) {   
     for (i=1;i<=npar;i++) x[i]=0;    for (i=1;i<=npar;i++) {
     x[j]=1;      for (j=1;j<=npar;j++)  {
     lubksb(a,npar,indx,x);        if (j>i) {
     for (i=1;i<=npar;i++){           printf(".%d%d",i,j);fflush(stdout);
       matcov[i][j]=x[i];          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
     }          hess[i][j]=hessij(p,delti,i,j,func,npar);
   }         
           hess[j][i]=hess[i][j];    
   printf("\n#Hessian matrix#\n");          /*printf(" %lf ",hess[i][j]);*/
   fprintf(ficlog,"\n#Hessian matrix#\n");        }
   for (i=1;i<=npar;i++) {       }
     for (j=1;j<=npar;j++) {     }
       printf("%.3e ",hess[i][j]);    printf("\n");
       fprintf(ficlog,"%.3e ",hess[i][j]);    fprintf(ficlog,"\n");
     }  
     printf("\n");    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
     fprintf(ficlog,"\n");    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
   }   
     a=matrix(1,npar,1,npar);
   /* Recompute Inverse */    y=matrix(1,npar,1,npar);
   for (i=1;i<=npar;i++)    x=vector(1,npar);
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];    indx=ivector(1,npar);
   ludcmp(a,npar,indx,&pd);    for (i=1;i<=npar;i++)
       for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
   /*  printf("\n#Hessian matrix recomputed#\n");    ludcmp(a,npar,indx,&pd);
   
   for (j=1;j<=npar;j++) {    for (j=1;j<=npar;j++) {
     for (i=1;i<=npar;i++) x[i]=0;      for (i=1;i<=npar;i++) x[i]=0;
     x[j]=1;      x[j]=1;
     lubksb(a,npar,indx,x);      lubksb(a,npar,indx,x);
     for (i=1;i<=npar;i++){       for (i=1;i<=npar;i++){
       y[i][j]=x[i];        matcov[i][j]=x[i];
       printf("%.3e ",y[i][j]);      }
       fprintf(ficlog,"%.3e ",y[i][j]);    }
     }  
     printf("\n");    printf("\n#Hessian matrix#\n");
     fprintf(ficlog,"\n");    fprintf(ficlog,"\n#Hessian matrix#\n");
   }    for (i=1;i<=npar;i++) {
   */      for (j=1;j<=npar;j++) {
         printf("%.3e ",hess[i][j]);
   free_matrix(a,1,npar,1,npar);        fprintf(ficlog,"%.3e ",hess[i][j]);
   free_matrix(y,1,npar,1,npar);      }
   free_vector(x,1,npar);      printf("\n");
   free_ivector(indx,1,npar);      fprintf(ficlog,"\n");
   free_matrix(hess,1,npar,1,npar);    }
   
     /* Recompute Inverse */
 }    for (i=1;i<=npar;i++)
       for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 /*************** hessian matrix ****************/    ludcmp(a,npar,indx,&pd);
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)  
 {    /*  printf("\n#Hessian matrix recomputed#\n");
   int i;  
   int l=1, lmax=20;    for (j=1;j<=npar;j++) {
   double k1,k2;      for (i=1;i<=npar;i++) x[i]=0;
   double p2[NPARMAX+1];      x[j]=1;
   double res;      lubksb(a,npar,indx,x);
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;      for (i=1;i<=npar;i++){
   double fx;        y[i][j]=x[i];
   int k=0,kmax=10;        printf("%.3e ",y[i][j]);
   double l1;        fprintf(ficlog,"%.3e ",y[i][j]);
       }
   fx=func(x);      printf("\n");
   for (i=1;i<=npar;i++) p2[i]=x[i];      fprintf(ficlog,"\n");
   for(l=0 ; l <=lmax; l++){    }
     l1=pow(10,l);    */
     delts=delt;  
     for(k=1 ; k <kmax; k=k+1){    free_matrix(a,1,npar,1,npar);
       delt = delta*(l1*k);    free_matrix(y,1,npar,1,npar);
       p2[theta]=x[theta] +delt;    free_vector(x,1,npar);
       k1=func(p2)-fx;    free_ivector(indx,1,npar);
       p2[theta]=x[theta]-delt;    free_matrix(hess,1,npar,1,npar);
       k2=func(p2)-fx;  
       /*res= (k1-2.0*fx+k2)/delt/delt; */  
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */  }
         
 #ifdef DEBUG  /*************** hessian matrix ****************/
       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);  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
       fprintf(ficlog,"%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);  {
 #endif    int i;
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */    int l=1, lmax=20;
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){    double k1,k2;
         k=kmax;    double p2[NPARMAX+1];
       }    double res;
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */    double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
         k=kmax; l=lmax*10.;    double fx;
       }    int k=0,kmax=10;
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){     double l1;
         delts=delt;  
       }    fx=func(x);
     }    for (i=1;i<=npar;i++) p2[i]=x[i];
   }    for(l=0 ; l <=lmax; l++){
   delti[theta]=delts;      l1=pow(10,l);
   return res;       delts=delt;
         for(k=1 ; k <kmax; k=k+1){
 }        delt = delta*(l1*k);
         p2[theta]=x[theta] +delt;
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)        k1=func(p2)-fx;
 {        p2[theta]=x[theta]-delt;
   int i;        k2=func(p2)-fx;
   int l=1, l1, lmax=20;        /*res= (k1-2.0*fx+k2)/delt/delt; */
   double k1,k2,k3,k4,res,fx;        res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
   double p2[NPARMAX+1];       
   int k;  #ifdef DEBUG
         printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
   fx=func(x);        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 (k=1; k<=2; k++) {  #endif
     for (i=1;i<=npar;i++) p2[i]=x[i];        /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
     p2[thetai]=x[thetai]+delti[thetai]/k;        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;          k=kmax;
     k1=func(p2)-fx;        }
           else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
     p2[thetai]=x[thetai]+delti[thetai]/k;          k=kmax; l=lmax*10.;
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;        }
     k2=func(p2)-fx;        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
             delts=delt;
     p2[thetai]=x[thetai]-delti[thetai]/k;        }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;      }
     k3=func(p2)-fx;    }
       delti[theta]=delts;
     p2[thetai]=x[thetai]-delti[thetai]/k;    return res;
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;   
     k4=func(p2)-fx;  }
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */  
 #ifdef DEBUG  double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
     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);    int i;
 #endif    int l=1, l1, lmax=20;
   }    double k1,k2,k3,k4,res,fx;
   return res;    double p2[NPARMAX+1];
 }    int k;
   
 /************** Inverse of matrix **************/    fx=func(x);
 void ludcmp(double **a, int n, int *indx, double *d)     for (k=1; k<=2; k++) {
 {       for (i=1;i<=npar;i++) p2[i]=x[i];
   int i,imax,j,k;       p2[thetai]=x[thetai]+delti[thetai]/k;
   double big,dum,sum,temp;       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   double *vv;       k1=func(p2)-fx;
     
   vv=vector(1,n);       p2[thetai]=x[thetai]+delti[thetai]/k;
   *d=1.0;       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
   for (i=1;i<=n;i++) {       k2=func(p2)-fx;
     big=0.0;    
     for (j=1;j<=n;j++)       p2[thetai]=x[thetai]-delti[thetai]/k;
       if ((temp=fabs(a[i][j])) > big) big=temp;       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");       k3=func(p2)-fx;
     vv[i]=1.0/big;    
   }       p2[thetai]=x[thetai]-delti[thetai]/k;
   for (j=1;j<=n;j++) {       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
     for (i=1;i<j;i++) {       k4=func(p2)-fx;
       sum=a[i][j];       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];   #ifdef DEBUG
       a[i][j]=sum;       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);
     big=0.0;   #endif
     for (i=j;i<=n;i++) {     }
       sum=a[i][j];     return res;
       for (k=1;k<j;k++)   }
         sum -= a[i][k]*a[k][j];   
       a[i][j]=sum;   /************** Inverse of matrix **************/
       if ( (dum=vv[i]*fabs(sum)) >= big) {   void ludcmp(double **a, int n, int *indx, double *d)
         big=dum;   {
         imax=i;     int i,imax,j,k;
       }     double big,dum,sum,temp;
     }     double *vv;
     if (j != imax) {    
       for (k=1;k<=n;k++) {     vv=vector(1,n);
         dum=a[imax][k];     *d=1.0;
         a[imax][k]=a[j][k];     for (i=1;i<=n;i++) {
         a[j][k]=dum;       big=0.0;
       }       for (j=1;j<=n;j++)
       *d = -(*d);         if ((temp=fabs(a[i][j])) > big) big=temp;
       vv[imax]=vv[j];       if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
     }       vv[i]=1.0/big;
     indx[j]=imax;     }
     if (a[j][j] == 0.0) a[j][j]=TINY;     for (j=1;j<=n;j++) {
     if (j != n) {       for (i=1;i<j;i++) {
       dum=1.0/(a[j][j]);         sum=a[i][j];
       for (i=j+1;i<=n;i++) a[i][j] *= dum;         for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
     }         a[i][j]=sum;
   }       }
   free_vector(vv,1,n);  /* Doesn't work */      big=0.0;
 ;      for (i=j;i<=n;i++) {
 }         sum=a[i][j];
         for (k=1;k<j;k++)
 void lubksb(double **a, int n, int *indx, double b[])           sum -= a[i][k]*a[k][j];
 {         a[i][j]=sum;
   int i,ii=0,ip,j;         if ( (dum=vv[i]*fabs(sum)) >= big) {
   double sum;           big=dum;
            imax=i;
   for (i=1;i<=n;i++) {         }
     ip=indx[i];       }
     sum=b[ip];       if (j != imax) {
     b[ip]=b[i];         for (k=1;k<=n;k++) {
     if (ii)           dum=a[imax][k];
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];           a[imax][k]=a[j][k];
     else if (sum) ii=i;           a[j][k]=dum;
     b[i]=sum;         }
   }         *d = -(*d);
   for (i=n;i>=1;i--) {         vv[imax]=vv[j];
     sum=b[i];       }
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];       indx[j]=imax;
     b[i]=sum/a[i][i];       if (a[j][j] == 0.0) a[j][j]=TINY;
   }       if (j != n) {
 }         dum=1.0/(a[j][j]);
         for (i=j+1;i<=n;i++) a[i][j] *= dum;
 void pstamp(FILE *fichier)      }
 {    }
   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);    free_vector(vv,1,n);  /* Doesn't work */
 }  ;
   }
 /************ Frequencies ********************/  
 void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])  void lubksb(double **a, int n, int *indx, double b[])
 {  /* Some frequencies */  {
       int i,ii=0,ip,j;
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;    double sum;
   int first;   
   double ***freq; /* Frequencies */    for (i=1;i<=n;i++) {
   double *pp, **prop;      ip=indx[i];
   double pos,posprop, k2, dateintsum=0,k2cpt=0;      sum=b[ip];
   char fileresp[FILENAMELENGTH];      b[ip]=b[i];
         if (ii)
   pp=vector(1,nlstate);        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
   prop=matrix(1,nlstate,iagemin,iagemax+3);      else if (sum) ii=i;
   strcpy(fileresp,"p");      b[i]=sum;
   strcat(fileresp,fileres);    }
   if((ficresp=fopen(fileresp,"w"))==NULL) {    for (i=n;i>=1;i--) {
     printf("Problem with prevalence resultfile: %s\n", fileresp);      sum=b[i];
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
     exit(0);      b[i]=sum/a[i][i];
   }    }
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);  }
   j1=0;  
     void pstamp(FILE *fichier)
   j=cptcoveff;  {
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
   }
   first=1;  
   /************ Frequencies ********************/
   for(k1=1; k1<=j;k1++){  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[])
     for(i1=1; i1<=ncodemax[k1];i1++){  {  /* Some frequencies */
       j1++;   
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    int i, m, jk, k1,i1, j1, bool, z1,z2,j;
         scanf("%d", i);*/    int first;
       for (i=-5; i<=nlstate+ndeath; i++)      double ***freq; /* Frequencies */
         for (jk=-5; jk<=nlstate+ndeath; jk++)      double *pp, **prop;
           for(m=iagemin; m <= iagemax+3; m++)    double pos,posprop, k2, dateintsum=0,k2cpt=0;
             freq[i][jk][m]=0;    char fileresp[FILENAMELENGTH];
    
     for (i=1; i<=nlstate; i++)      pp=vector(1,nlstate);
       for(m=iagemin; m <= iagemax+3; m++)    prop=matrix(1,nlstate,iagemin,iagemax+3);
         prop[i][m]=0;    strcpy(fileresp,"p");
           strcat(fileresp,fileres);
       dateintsum=0;    if((ficresp=fopen(fileresp,"w"))==NULL) {
       k2cpt=0;      printf("Problem with prevalence resultfile: %s\n", fileresp);
       for (i=1; i<=imx; i++) {      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
         bool=1;      exit(0);
         if  (cptcovn>0) {    }
           for (z1=1; z1<=cptcoveff; z1++)     freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     j1=0;
               bool=0;   
         }    j=cptcoveff;
         if (bool==1){    if (cptcovn<1) {j=1;ncodemax[1]=1;}
           for(m=firstpass; m<=lastpass; m++){  
             k2=anint[m][i]+(mint[m][i]/12.);    first=1;
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/  
               if(agev[m][i]==0) agev[m][i]=iagemax+1;    for(k1=1; k1<=j;k1++){
               if(agev[m][i]==1) agev[m][i]=iagemax+2;      for(i1=1; i1<=ncodemax[k1];i1++){
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];        j1++;
               if (m<lastpass) {        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];          scanf("%d", i);*/
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];        for (i=-5; i<=nlstate+ndeath; i++)  
               }          for (jk=-5; jk<=nlstate+ndeath; jk++)  
                           for(m=iagemin; m <= iagemax+3; m++)
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {              freq[i][jk][m]=0;
                 dateintsum=dateintsum+k2;  
                 k2cpt++;      for (i=1; i<=nlstate; i++)  
               }        for(m=iagemin; m <= iagemax+3; m++)
               /*}*/          prop[i][m]=0;
           }       
         }        dateintsum=0;
       }        k2cpt=0;
                for (i=1; i<=imx; i++) {
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/          bool=1;
       pstamp(ficresp);          if  (cptcovn>0) {
       if  (cptcovn>0) {            for (z1=1; z1<=cptcoveff; z1++)
         fprintf(ficresp, "\n#********** Variable ");               if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);                bool=0;
         fprintf(ficresp, "**********\n#");          }
       }          if (bool==1){
       for(i=1; i<=nlstate;i++)             for(m=firstpass; m<=lastpass; m++){
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);              k2=anint[m][i]+(mint[m][i]/12.);
       fprintf(ficresp, "\n");              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                       if(agev[m][i]==0) agev[m][i]=iagemax+1;
       for(i=iagemin; i <= iagemax+3; i++){                if(agev[m][i]==1) agev[m][i]=iagemax+2;
         if(i==iagemax+3){                if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
           fprintf(ficlog,"Total");                if (m<lastpass) {
         }else{                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
           if(first==1){                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
             first=0;                }
             printf("See log file for details...\n");               
           }                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
           fprintf(ficlog,"Age %d", i);                  dateintsum=dateintsum+k2;
         }                  k2cpt++;
         for(jk=1; jk <=nlstate ; jk++){                }
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)                /*}*/
             pp[jk] += freq[jk][m][i];             }
         }          }
         for(jk=1; jk <=nlstate ; jk++){        }
           for(m=-1, pos=0; m <=0 ; m++)         
             pos += freq[jk][m][i];        /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
           if(pp[jk]>=1.e-10){        pstamp(ficresp);
             if(first==1){        if  (cptcovn>0) {
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);          fprintf(ficresp, "\n#********** Variable ");
             }          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);          fprintf(ficresp, "**********\n#");
           }else{        }
             if(first==1)        for(i=1; i<=nlstate;i++)
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);        fprintf(ficresp, "\n");
           }       
         }        for(i=iagemin; i <= iagemax+3; i++){
           if(i==iagemax+3){
         for(jk=1; jk <=nlstate ; jk++){            fprintf(ficlog,"Total");
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)          }else{
             pp[jk] += freq[jk][m][i];            if(first==1){
         }                     first=0;
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){              printf("See log file for details...\n");
           pos += pp[jk];            }
           posprop += prop[jk][i];            fprintf(ficlog,"Age %d", i);
         }          }
         for(jk=1; jk <=nlstate ; jk++){          for(jk=1; jk <=nlstate ; jk++){
           if(pos>=1.e-5){            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
             if(first==1)              pp[jk] += freq[jk][m][i];
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);          }
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);          for(jk=1; jk <=nlstate ; jk++){
           }else{            for(m=-1, pos=0; m <=0 ; m++)
             if(first==1)              pos += freq[jk][m][i];
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);            if(pp[jk]>=1.e-10){
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);              if(first==1){
           }              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
           if( i <= iagemax){              }
             if(pos>=1.e-5){              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);            }else{
               /*probs[i][jk][j1]= pp[jk]/pos;*/              if(first==1)
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             }              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             else            }
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);          }
           }  
         }          for(jk=1; jk <=nlstate ; jk++){
                     for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
         for(jk=-1; jk <=nlstate+ndeath; jk++)              pp[jk] += freq[jk][m][i];
           for(m=-1; m <=nlstate+ndeath; m++)          }      
             if(freq[jk][m][i] !=0 ) {          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
             if(first==1)            pos += pp[jk];
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);            posprop += prop[jk][i];
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);          }
             }          for(jk=1; jk <=nlstate ; jk++){
         if(i <= iagemax)            if(pos>=1.e-5){
           fprintf(ficresp,"\n");              if(first==1)
         if(first==1)                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
           printf("Others in log...\n");              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
         fprintf(ficlog,"\n");            }else{
       }              if(first==1)
     }                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
   }              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
   dateintmean=dateintsum/k2cpt;             }
              if( i <= iagemax){
   fclose(ficresp);              if(pos>=1.e-5){
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
   free_vector(pp,1,nlstate);                /*probs[i][jk][j1]= pp[jk]/pos;*/
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);                /*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 of Freq */              }
 }              else
                 fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 /************ 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)          }
 {           
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people          for(jk=-1; jk <=nlstate+ndeath; jk++)
      in each health status at the date of interview (if between dateprev1 and dateprev2).            for(m=-1; m <=nlstate+ndeath; m++)
      We still use firstpass and lastpass as another selection.              if(freq[jk][m][i] !=0 ) {
   */              if(first==1)
                  printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
   double ***freq; /* Frequencies */              }
   double *pp, **prop;          if(i <= iagemax)
   double pos,posprop;             fprintf(ficresp,"\n");
   double  y2; /* in fractional years */          if(first==1)
   int iagemin, iagemax;            printf("Others in log...\n");
           fprintf(ficlog,"\n");
   iagemin= (int) agemin;        }
   iagemax= (int) agemax;      }
   /*pp=vector(1,nlstate);*/    }
   prop=matrix(1,nlstate,iagemin,iagemax+3);     dateintmean=dateintsum/k2cpt;
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/   
   j1=0;    fclose(ficresp);
       free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
   j=cptcoveff;    free_vector(pp,1,nlstate);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
       /* End of Freq */
   for(k1=1; k1<=j;k1++){  }
     for(i1=1; i1<=ncodemax[k1];i1++){  
       j1++;  /************ 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=1; i<=nlstate; i++)    {  
         for(m=iagemin; m <= iagemax+3; m++)    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
           prop[i][m]=0.0;       in each health status at the date of interview (if between dateprev1 and dateprev2).
             We still use firstpass and lastpass as another selection.
       for (i=1; i<=imx; i++) { /* Each individual */    */
         bool=1;   
         if  (cptcovn>0) {    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
           for (z1=1; z1<=cptcoveff; z1++)     double ***freq; /* Frequencies */
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     double *pp, **prop;
               bool=0;    double pos,posprop;
         }     double  y2; /* in fractional years */
         if (bool==1) {     int iagemin, iagemax;
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/  
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */    iagemin= (int) agemin;
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */    iagemax= (int) agemax;
               if(agev[m][i]==0) agev[m][i]=iagemax+1;    /*pp=vector(1,nlstate);*/
               if(agev[m][i]==1) agev[m][i]=iagemax+2;    prop=matrix(1,nlstate,iagemin,iagemax+3);
               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);     /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
               if (s[m][i]>0 && s[m][i]<=nlstate) {     j1=0;
                 /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/   
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];    j=cptcoveff;
                 prop[s[m][i]][iagemax+3] += weight[i];     if (cptcovn<1) {j=1;ncodemax[1]=1;}
               }    
             }    for(k1=1; k1<=j;k1++){
           } /* end selection of waves */      for(i1=1; i1<=ncodemax[k1];i1++){
         }        j1++;
       }       
       for(i=iagemin; i <= iagemax+3; i++){          for (i=1; i<=nlstate; i++)  
                   for(m=iagemin; m <= iagemax+3; m++)
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {             prop[i][m]=0.0;
           posprop += prop[jk][i];        
         }         for (i=1; i<=imx; i++) { /* Each individual */
           bool=1;
         for(jk=1; jk <=nlstate ; jk++){               if  (cptcovn>0) {
           if( i <=  iagemax){             for (z1=1; z1<=cptcoveff; z1++)
             if(posprop>=1.e-5){               if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
               probs[i][jk][j1]= prop[jk][i]/posprop;                bool=0;
             }           }
           }           if (bool==1) {
         }/* end jk */             for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
       }/* end i */               y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
     } /* end i1 */              if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
   } /* end k1 */                if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   if(agev[m][i]==1) agev[m][i]=iagemax+2;
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/                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);
   /*free_vector(pp,1,nlstate);*/                if (s[m][i]>0 && s[m][i]<=nlstate) {
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);                  /*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]]);*/
 }  /* End of prevalence */                  prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   prop[s[m][i]][iagemax+3] += weight[i];
 /************* Waves Concatenation ***************/                }
               }
 void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)            } /* end selection of waves */
 {          }
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.        }
      Death is a valid wave (if date is known).        for(i=iagemin; i <= iagemax+3; i++){  
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i         
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
      and mw[mi+1][i]. dh depends on stepm.            posprop += prop[jk][i];
      */          }
   
   int i, mi, m;          for(jk=1; jk <=nlstate ; jk++){    
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;            if( i <=  iagemax){
      double sum=0., jmean=0.;*/              if(posprop>=1.e-5){
   int first;                probs[i][jk][j1]= prop[jk][i]/posprop;
   int j, k=0,jk, ju, jl;              }
   double sum=0.;            }
   first=0;          }/* end jk */
   jmin=1e+5;        }/* end i */
   jmax=-1;      } /* end i1 */
   jmean=0.;    } /* end k1 */
   for(i=1; i<=imx; i++){   
     mi=0;    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
     m=firstpass;    /*free_vector(pp,1,nlstate);*/
     while(s[m][i] <= nlstate){    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)  }  /* End of prevalence */
         mw[++mi][i]=m;  
       if(m >=lastpass)  /************* Waves Concatenation ***************/
         break;  
       else  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)
         m++;  {
     }/* end while */    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
     if (s[m][i] > nlstate){       Death is a valid wave (if date is known).
       mi++;     /* Death is another wave */       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
       /* if(mi==0)  never been interviewed correctly before death */       dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
          /* Only death is a correct wave */       and mw[mi+1][i]. dh depends on stepm.
       mw[mi][i]=m;       */
     }  
     int i, mi, m;
     wav[i]=mi;    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
     if(mi==0){       double sum=0., jmean=0.;*/
       nbwarn++;    int first;
       if(first==0){    int j, k=0,jk, ju, jl;
         printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);    double sum=0.;
         first=1;    first=0;
       }    jmin=1e+5;
       if(first==1){    jmax=-1;
         fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);    jmean=0.;
       }    for(i=1; i<=imx; i++){
     } /* end mi==0 */      mi=0;
   } /* End individuals */      m=firstpass;
       while(s[m][i] <= nlstate){
   for(i=1; i<=imx; i++){        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
     for(mi=1; mi<wav[i];mi++){          mw[++mi][i]=m;
       if (stepm <=0)        if(m >=lastpass)
         dh[mi][i]=1;          break;
       else{        else
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */          m++;
           if (agedc[i] < 2*AGESUP) {      }/* end while */
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);       if (s[m][i] > nlstate){
             if(j==0) j=1;  /* Survives at least one month after exam */        mi++;     /* Death is another wave */
             else if(j<0){        /* if(mi==0)  never been interviewed correctly before death */
               nberr++;           /* Only death is a correct wave */
               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]);        mw[mi][i]=m;
               j=1; /* Temporary Dangerous patch */      }
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);  
               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]);      wav[i]=mi;
               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);      if(mi==0){
             }        nbwarn++;
             k=k+1;        if(first==0){
             if (j >= jmax){          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
               jmax=j;          first=1;
               ijmax=i;        }
             }        if(first==1){
             if (j <= jmin){          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
               jmin=j;        }
               ijmin=i;      } /* end mi==0 */
             }    } /* End individuals */
             sum=sum+j;  
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/    for(i=1; i<=imx; i++){
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/      for(mi=1; mi<wav[i];mi++){
           }        if (stepm <=0)
         }          dh[mi][i]=1;
         else{        else{
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 /*        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]); */            if (agedc[i] < 2*AGESUP) {
               j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
           k=k+1;              if(j==0) j=1;  /* Survives at least one month after exam */
           if (j >= jmax) {              else if(j<0){
             jmax=j;                nberr++;
             ijmax=i;                printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
           }                j=1; /* Temporary Dangerous patch */
           else if (j <= jmin){                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);
             jmin=j;                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]);
             ijmin=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);
           }              }
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */              k=k+1;
           /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/              if (j >= jmax){
           if(j<0){                jmax=j;
             nberr++;                ijmax=i;
             printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);              }
             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]);              if (j <= jmin){
           }                jmin=j;
           sum=sum+j;                ijmin=i;
         }              }
         jk= j/stepm;              sum=sum+j;
         jl= j -jk*stepm;              /*if (j<0) printf("j=%d num=%d \n",j,i);*/
         ju= j -(jk+1)*stepm;              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */            }
           if(jl==0){          }
             dh[mi][i]=jk;          else{
             bh[mi][i]=0;            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
           }else{ /* We want a negative bias in order to only have interpolation ie  /*        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]); */
                   * at the price of an extra matrix product in likelihood */  
             dh[mi][i]=jk+1;            k=k+1;
             bh[mi][i]=ju;            if (j >= jmax) {
           }              jmax=j;
         }else{              ijmax=i;
           if(jl <= -ju){            }
             dh[mi][i]=jk;            else if (j <= jmin){
             bh[mi][i]=jl;       /* bias is positive if real duration              jmin=j;
                                  * is higher than the multiple of stepm and negative otherwise.              ijmin=i;
                                  */            }
           }            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
           else{            /*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]);*/
             dh[mi][i]=jk+1;            if(j<0){
             bh[mi][i]=ju;              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]);
           if(dh[mi][i]==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]);
             dh[mi][i]=1; /* At least one step */            }
             bh[mi][i]=ju; /* At least one step */            sum=sum+j;
             /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/          }
           }          jk= j/stepm;
         } /* end if mle */          jl= j -jk*stepm;
       }          ju= j -(jk+1)*stepm;
     } /* end wave */          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
   }            if(jl==0){
   jmean=sum/k;              dh[mi][i]=jk;
   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);              bh[mi][i]=0;
   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{ /* 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;
 /*********** Tricode ****************************/              bh[mi][i]=ju;
 void tricode(int *Tvar, int **nbcode, int imx)            }
 {          }else{
               if(jl <= -ju){
   int Ndum[20],ij=1, k, j, i, maxncov=19;              dh[mi][i]=jk;
   int cptcode=0;              bh[mi][i]=jl;       /* bias is positive if real duration
   cptcoveff=0;                                    * is higher than the multiple of stepm and negative otherwise.
                                     */
   for (k=0; k<maxncov; k++) Ndum[k]=0;            }
   for (k=1; k<=7; k++) ncodemax[k]=0;            else{
               dh[mi][i]=jk+1;
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {              bh[mi][i]=ju;
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum             }
                                modality*/             if(dh[mi][i]==0){
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/              dh[mi][i]=1; /* At least one step */
       Ndum[ij]++; /*store the modality */              bh[mi][i]=ju; /* At least one step */
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/              /*  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);*/
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable             }
                                        Tvar[j]. If V=sex and male is 0 and           } /* end if mle */
                                        female is 1, then  cptcode=1.*/        }
     }      } /* end wave */
     }
     for (i=0; i<=cptcode; i++) {    jmean=sum/k;
       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 */    printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);
     }    fprintf(ficlog,"Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, ijmin, jmax, ijmax, jmean);
    }
     ij=1;   
     for (i=1; i<=ncodemax[j]; i++) {  /*********** Tricode ****************************/
       for (k=0; k<= maxncov; k++) {  void tricode(int *Tvar, int **nbcode, int imx)
         if (Ndum[k] != 0) {  {
           nbcode[Tvar[j]][ij]=k;    
           /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */    int Ndum[20],ij=1, k, j, i, maxncov=19;
               int cptcode=0;
           ij++;    cptcoveff=0;
         }   
         if (ij > ncodemax[j]) break;     for (k=0; k<maxncov; k++) Ndum[k]=0;
       }      for (k=1; k<=7; k++) ncodemax[k]=0;
     }   
   }      for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
       for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
  for (k=0; k< maxncov; k++) Ndum[k]=0;                                 modality*/
         ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
  for (i=1; i<=ncovmodel-2; i++) {         Ndum[ij]++; /*store the modality */
    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
    ij=Tvar[i];        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
    Ndum[ij]++;                                         Tvar[j]. If V=sex and male is 0 and
  }                                         female is 1, then  cptcode=1.*/
       }
  ij=1;  
  for (i=1; i<= maxncov; i++) {      for (i=0; i<=cptcode; i++) {
    if((Ndum[i]!=0) && (i<=ncovcol)){        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 */
      Tvaraff[ij]=i; /*For printing */      }
      ij++;  
    }      ij=1;
  }      for (i=1; i<=ncodemax[j]; i++) {
          for (k=0; k<= maxncov; k++) {
  cptcoveff=ij-1; /*Number of simple covariates*/          if (Ndum[k] != 0) {
 }            nbcode[Tvar[j]][ij]=k;
             /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 /*********** Health Expectancies ****************/           
             ij++;
 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[] )          }
           if (ij > ncodemax[j]) break;
 {        }  
   /* Health expectancies, no variances */      }
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;    }  
   double age, agelim, hf;  
   double ***p3mat;   for (k=0; k< maxncov; k++) Ndum[k]=0;
   double eip;  
    for (i=1; i<=ncovmodel-2; i++) {
   pstamp(ficreseij);     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");     ij=Tvar[i];
   fprintf(ficreseij,"# Age");     Ndum[ij]++;
   for(i=1; i<=nlstate;i++){   }
     for(j=1; j<=nlstate;j++){  
       fprintf(ficreseij," e%1d%1d ",i,j);   ij=1;
     }   for (i=1; i<= maxncov; i++) {
     fprintf(ficreseij," e%1d. ",i);     if((Ndum[i]!=0) && (i<=ncovcol)){
   }       Tvaraff[ij]=i; /*For printing */
   fprintf(ficreseij,"\n");       ij++;
      }
      }
   if(estepm < stepm){   
     printf ("Problem %d lower than %d\n",estepm, stepm);   cptcoveff=ij-1; /*Number of simple covariates*/
   }  }
   else  hstepm=estepm;     
   /* We compute the life expectancy from trapezoids spaced every estepm months  /*********** Health Expectancies ****************/
    * 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  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[] )
    * we are calculating an estimate of the Life Expectancy assuming a linear   
    * progression in between and thus overestimating or underestimating according  {
    * to the curvature of the survival function. If, for the same date, we     /* Health expectancies, no variances */
    * estimate the model with stepm=1 month, we can keep estepm to 24 months    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
    * to compare the new estimate of Life expectancy with the same linear     double age, agelim, hf;
    * hypothesis. A more precise result, taking into account a more precise    double ***p3mat;
    * curvature will be obtained if estepm is as small as stepm. */    double eip;
   
   /* For example we decided to compute the life expectancy with the smallest unit */    pstamp(ficreseij);
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.     fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
      nhstepm is the number of hstepm from age to agelim     fprintf(ficreseij,"# Age");
      nstepm is the number of stepm from age to agelin.     for(i=1; i<=nlstate;i++){
      Look at hpijx to understand the reason of that which relies in memory size      for(j=1; j<=nlstate;j++){
      and note for a fixed period like estepm months */        fprintf(ficreseij," e%1d%1d ",i,j);
   /* 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      fprintf(ficreseij," e%1d. ",i);
      means that if the survival funtion is printed only each two years of age and if    }
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     fprintf(ficreseij,"\n");
      results. So we changed our mind and took the option of the best precision.  
   */   
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     if(estepm < stepm){
       printf ("Problem %d lower than %d\n",estepm, stepm);
   agelim=AGESUP;    }
   /* nhstepm age range expressed in number of stepm */    else  hstepm=estepm;  
   nstepm=(int) rint((agelim-age)*YEARM/stepm);     /* We compute the life expectancy from trapezoids spaced every estepm months
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */      * This is mainly to measure the difference between two models: for example
   /* if (stepm >= YEARM) hstepm=1;*/     * if stepm=24 months pijx are given only every 2 years and by summing them
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */     * we are calculating an estimate of the Life Expectancy assuming a linear
   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);     * progression in between and thus overestimating or underestimating according
      * to the curvature of the survival function. If, for the same date, we
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */     * estimate the model with stepm=1 month, we can keep estepm to 24 months
     /* Computed by stepm unit matrices, product of hstepm matrices, stored     * to compare the new estimate of Life expectancy with the same linear
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */     * hypothesis. A more precise result, taking into account a more precise
          * curvature will be obtained if estepm is as small as stepm. */
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);    
         /* For example we decided to compute the life expectancy with the smallest unit */
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
            nhstepm is the number of hstepm from age to agelim
     printf("%d|",(int)age);fflush(stdout);       nstepm is the number of stepm from age to agelin.
     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);       Look at hpijx to understand the reason of that which relies in memory size
            and note for a fixed period like estepm months */
     /* Computing expectancies */    /* 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
       for(j=1; j<=nlstate;j++)       means that if the survival funtion is printed only each two years of age and if
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){       you sum them up and add 1 year (area under the trapezoids) you won't get the same
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;       results. So we changed our mind and took the option of the best precision.
               */
           /* 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]);*/    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   
         }    agelim=AGESUP;
     /* If stepm=6 months */
     fprintf(ficreseij,"%3.0f",age );      /* Computed by stepm unit matrices, product of hstepm matrices, stored
     for(i=1; i<=nlstate;i++){         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
       eip=0;     
       for(j=1; j<=nlstate;j++){  /* nhstepm age range expressed in number of stepm */
         eip +=eij[i][j][(int)age];    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
         fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
       }    /* if (stepm >= YEARM) hstepm=1;*/
       fprintf(ficreseij,"%9.4f", eip );    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
     }    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     fprintf(ficreseij,"\n");  
         for (age=bage; age<=fage; age ++){
   }  
   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  
   printf("\n");      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
   fprintf(ficlog,"\n");     
         hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 }     
       printf("%d|",(int)age);fflush(stdout);
 void cvevsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
      
 {  
   /* Covariances of health expectancies eij and of total life expectancies according      /* Computing expectancies */
    to initial status i, ei. .      for(i=1; i<=nlstate;i++)
   */        for(j=1; j<=nlstate;j++)
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   double age, agelim, hf;            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
   double ***p3matp, ***p3matm, ***varhe;           
   double **dnewm,**doldm;            /*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]);*/
   double *xp, *xm;  
   double **gp, **gm;          }
   double ***gradg, ***trgradg;     
   int theta;      fprintf(ficreseij,"%3.0f",age );
       for(i=1; i<=nlstate;i++){
   double eip, vip;        eip=0;
         for(j=1; j<=nlstate;j++){
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);          eip +=eij[i][j][(int)age];
   xp=vector(1,npar);          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
   xm=vector(1,npar);        }
   dnewm=matrix(1,nlstate*nlstate,1,npar);        fprintf(ficreseij,"%9.4f", eip );
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);      }
         fprintf(ficreseij,"\n");
   pstamp(ficresstdeij);     
   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");    }
   fprintf(ficresstdeij,"# Age");    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   for(i=1; i<=nlstate;i++){    printf("\n");
     for(j=1; j<=nlstate;j++)    fprintf(ficlog,"\n");
       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);   
     fprintf(ficresstdeij," e%1d. ",i);  }
   }  
   fprintf(ficresstdeij,"\n");  void cvevsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
   
   pstamp(ficrescveij);  {
   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");    /* Covariances of health expectancies eij and of total life expectancies according
   fprintf(ficrescveij,"# Age");     to initial status i, ei. .
   for(i=1; i<=nlstate;i++)    */
     for(j=1; j<=nlstate;j++){    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
       cptj= (j-1)*nlstate+i;    double age, agelim, hf;
       for(i2=1; i2<=nlstate;i2++)    double ***p3matp, ***p3matm, ***varhe;
         for(j2=1; j2<=nlstate;j2++){    double **dnewm,**doldm;
           cptj2= (j2-1)*nlstate+i2;    double *xp, *xm;
           if(cptj2 <= cptj)    double **gp, **gm;
             fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);    double ***gradg, ***trgradg;
         }    int theta;
     }  
   fprintf(ficrescveij,"\n");    double eip, vip;
     
   if(estepm < stepm){    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
     printf ("Problem %d lower than %d\n",estepm, stepm);    xp=vector(1,npar);
   }    xm=vector(1,npar);
   else  hstepm=estepm;       dnewm=matrix(1,nlstate*nlstate,1,npar);
   /* We compute the life expectancy from trapezoids spaced every estepm months    doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
    * 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    pstamp(ficresstdeij);
    * we are calculating an estimate of the Life Expectancy assuming a linear     fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
    * progression in between and thus overestimating or underestimating according    fprintf(ficresstdeij,"# Age");
    * to the curvature of the survival function. If, for the same date, we     for(i=1; i<=nlstate;i++){
    * estimate the model with stepm=1 month, we can keep estepm to 24 months      for(j=1; j<=nlstate;j++)
    * to compare the new estimate of Life expectancy with the same linear         fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
    * hypothesis. A more precise result, taking into account a more precise      fprintf(ficresstdeij," e%1d. ",i);
    * curvature will be obtained if estepm is as small as stepm. */    }
     fprintf(ficresstdeij,"\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.     pstamp(ficrescveij);
      nhstepm is the number of hstepm from age to agelim     fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
      nstepm is the number of stepm from age to agelin.     fprintf(ficrescveij,"# Age");
      Look at hpijx to understand the reason of that which relies in memory size    for(i=1; i<=nlstate;i++)
      and note for a fixed period like estepm months */      for(j=1; j<=nlstate;j++){
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the        cptj= (j-1)*nlstate+i;
      survival function given by stepm (the optimization length). Unfortunately it        for(i2=1; i2<=nlstate;i2++)
      means that if the survival funtion is printed only each two years of age and if          for(j2=1; j2<=nlstate;j2++){
      you sum them up and add 1 year (area under the trapezoids) you won't get the same             cptj2= (j2-1)*nlstate+i2;
      results. So we changed our mind and took the option of the best precision.            if(cptj2 <= cptj)
   */              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */           }
       }
   /* If stepm=6 months */    fprintf(ficrescveij,"\n");
   /* nhstepm age range expressed in number of stepm */   
   agelim=AGESUP;    if(estepm < stepm){
   nstepm=(int) rint((agelim-age)*YEARM/stepm);       printf ("Problem %d lower than %d\n",estepm, stepm);
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */     }
   /* if (stepm >= YEARM) hstepm=1;*/    else  hstepm=estepm;  
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */    /* We compute the life expectancy from trapezoids spaced every estepm months
        * This is mainly to measure the difference between two models: for example
   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);     * if stepm=24 months pijx are given only every 2 years and by summing them
   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);     * we are calculating an estimate of the Life Expectancy assuming a linear
   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);     * progression in between and thus overestimating or underestimating according
   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);     * to the curvature of the survival function. If, for the same date, we
   gp=matrix(0,nhstepm,1,nlstate*nlstate);     * estimate the model with stepm=1 month, we can keep estepm to 24 months
   gm=matrix(0,nhstepm,1,nlstate*nlstate);     * to compare the new estimate of Life expectancy with the same linear
      * hypothesis. A more precise result, taking into account a more precise
   for (age=bage; age<=fage; age ++){      * curvature will be obtained if estepm is as small as stepm. */
   
     /* Computed by stepm unit matrices, product of hstepm matrices, stored    /* For example we decided to compute the life expectancy with the smallest unit */
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */    /* 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
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */       nstepm is the number of stepm from age to agelin.
        Look at hpijx to understand the reason of that which relies in memory size
     /* Computing  Variances of health expectancies */       and note for a fixed period like estepm months */
     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
        decrease memory allocation */       survival function given by stepm (the optimization length). Unfortunately it
     for(theta=1; theta <=npar; theta++){       means that if the survival funtion is printed only each two years of age and if
       for(i=1; i<=npar; i++){        you sum them up and add 1 year (area under the trapezoids) you won't get the same
         xp[i] = x[i] + (i==theta ?delti[theta]:0);       results. So we changed our mind and took the option of the best precision.
         xm[i] = x[i] - (i==theta ?delti[theta]:0);    */
       }    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);    
       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);      /* If stepm=6 months */
       /* nhstepm age range expressed in number of stepm */
       for(j=1; j<= nlstate; j++){    agelim=AGESUP;
         for(i=1; i<=nlstate; i++){    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
           for(h=0; h<=nhstepm-1; h++){    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
             gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;    /* if (stepm >= YEARM) hstepm=1;*/
             gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
           }   
         }    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       }    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
          gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
       for(ij=1; ij<= nlstate*nlstate; ij++)    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
         for(h=0; h<=nhstepm-1; h++){    gp=matrix(0,nhstepm,1,nlstate*nlstate);
           gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];    gm=matrix(0,nhstepm,1,nlstate*nlstate);
         }  
     }/* End theta */    for (age=bage; age<=fage; age ++){
       
           /* Computed by stepm unit matrices, product of hstepm matrices, stored
     for(h=0; h<=nhstepm-1; h++)         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
       for(j=1; j<=nlstate*nlstate;j++)   
         for(theta=1; theta <=npar; theta++)      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
           trgradg[h][j][theta]=gradg[h][theta][j];  
           /* Computing  Variances of health expectancies */
       /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
      for(ij=1;ij<=nlstate*nlstate;ij++)         decrease memory allocation */
       for(ji=1;ji<=nlstate*nlstate;ji++)      for(theta=1; theta <=npar; theta++){
         varhe[ij][ji][(int)age] =0.;        for(i=1; i<=npar; i++){
           xp[i] = x[i] + (i==theta ?delti[theta]:0);
      printf("%d|",(int)age);fflush(stdout);          xm[i] = x[i] - (i==theta ?delti[theta]:0);
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);        }
      for(h=0;h<=nhstepm-1;h++){        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
       for(k=0;k<=nhstepm-1;k++){        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);   
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);        for(j=1; j<= nlstate; j++){
         for(ij=1;ij<=nlstate*nlstate;ij++)          for(i=1; i<=nlstate; i++){
           for(ji=1;ji<=nlstate*nlstate;ji++)            for(h=0; h<=nhstepm-1; h++){
             varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;              gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
       }              gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
     }            }
     /* 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(ij=1; ij<= nlstate*nlstate; ij++)
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){          for(h=0; h<=nhstepm-1; h++){
           eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                     }
           /* 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]);*/      }/* End theta */
      
         }     
       for(h=0; h<=nhstepm-1; h++)
     fprintf(ficresstdeij,"%3.0f",age );        for(j=1; j<=nlstate*nlstate;j++)
     for(i=1; i<=nlstate;i++){          for(theta=1; theta <=npar; theta++)
       eip=0.;            trgradg[h][j][theta]=gradg[h][theta][j];
       vip=0.;     
       for(j=1; j<=nlstate;j++){  
         eip += eij[i][j][(int)age];       for(ij=1;ij<=nlstate*nlstate;ij++)
         for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */        for(ji=1;ji<=nlstate*nlstate;ji++)
           vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];          varhe[ij][ji][(int)age] =0.;
         fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );  
       }       printf("%d|",(int)age);fflush(stdout);
       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
     }       for(h=0;h<=nhstepm-1;h++){
     fprintf(ficresstdeij,"\n");        for(k=0;k<=nhstepm-1;k++){
           matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
     fprintf(ficrescveij,"%3.0f",age );          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
     for(i=1; i<=nlstate;i++)          for(ij=1;ij<=nlstate*nlstate;ij++)
       for(j=1; j<=nlstate;j++){            for(ji=1;ji<=nlstate*nlstate;ji++)
         cptj= (j-1)*nlstate+i;              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
         for(i2=1; i2<=nlstate;i2++)        }
           for(j2=1; j2<=nlstate;j2++){      }
             cptj2= (j2-1)*nlstate+i2;  
             if(cptj2 <= cptj)      /* Computing expectancies */
               fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
           }      for(i=1; i<=nlstate;i++)
       }        for(j=1; j<=nlstate;j++)
     fprintf(ficrescveij,"\n");          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
   }           
   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);            /* 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]);*/
   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);  
   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);          }
   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);  
   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      fprintf(ficresstdeij,"%3.0f",age );
   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      for(i=1; i<=nlstate;i++){
   printf("\n");        eip=0.;
   fprintf(ficlog,"\n");        vip=0.;
         for(j=1; j<=nlstate;j++){
   free_vector(xm,1,npar);          eip += eij[i][j][(int)age];
   free_vector(xp,1,npar);          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);        }
 }        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
       }
 /************ Variance ******************/      fprintf(ficresstdeij,"\n");
 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(ficrescveij,"%3.0f",age );
   /* Variance of health expectancies */      for(i=1; i<=nlstate;i++)
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/        for(j=1; j<=nlstate;j++){
   /* double **newm;*/          cptj= (j-1)*nlstate+i;
   double **dnewm,**doldm;          for(i2=1; i2<=nlstate;i2++)
   double **dnewmp,**doldmp;            for(j2=1; j2<=nlstate;j2++){
   int i, j, nhstepm, hstepm, h, nstepm ;              cptj2= (j2-1)*nlstate+i2;
   int k, cptcode;              if(cptj2 <= cptj)
   double *xp;                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
   double **gp, **gm;  /* for var eij */            }
   double ***gradg, ***trgradg; /*for var eij */        }
   double **gradgp, **trgradgp; /* for var p point j */      fprintf(ficrescveij,"\n");
   double *gpp, *gmp; /* for var p point j */     
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */    }
   double ***p3mat;    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
   double age,agelim, hf;    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
   double ***mobaverage;    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
   int theta;    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
   char digit[4];    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   char digitp[25];    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     printf("\n");
   char fileresprobmorprev[FILENAMELENGTH];    fprintf(ficlog,"\n");
   
   if(popbased==1){    free_vector(xm,1,npar);
     if(mobilav!=0)    free_vector(xp,1,npar);
       strcpy(digitp,"-populbased-mobilav-");    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
     else strcpy(digitp,"-populbased-nomobil-");    free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
   }    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
   else   }
     strcpy(digitp,"-stablbased-");  
   /************ Variance ******************/
   if (mobilav!=0) {  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[])
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  {
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){    /* Variance of health expectancies */
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    /* double **newm;*/
     }    double **dnewm,**doldm;
   }    double **dnewmp,**doldmp;
     int i, j, nhstepm, hstepm, h, nstepm ;
   strcpy(fileresprobmorprev,"prmorprev");     int k, cptcode;
   sprintf(digit,"%-d",ij);    double *xp;
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/    double **gp, **gm;  /* for var eij */
   strcat(fileresprobmorprev,digit); /* Tvar to be done */    double ***gradg, ***trgradg; /*for var eij */
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */    double **gradgp, **trgradgp; /* for var p point j */
   strcat(fileresprobmorprev,fileres);    double *gpp, *gmp; /* for var p point j */
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
     printf("Problem with resultfile: %s\n", fileresprobmorprev);    double ***p3mat;
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);    double age,agelim, hf;
   }    double ***mobaverage;
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    int theta;
      char digit[4];
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    char digitp[25];
   pstamp(ficresprobmorprev);  
   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);    char fileresprobmorprev[FILENAMELENGTH];
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);  
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){    if(popbased==1){
     fprintf(ficresprobmorprev," p.%-d SE",j);      if(mobilav!=0)
     for(i=1; i<=nlstate;i++)        strcpy(digitp,"-populbased-mobilav-");
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);      else strcpy(digitp,"-populbased-nomobil-");
   }      }
   fprintf(ficresprobmorprev,"\n");    else
   fprintf(ficgp,"\n# Routine varevsij");      strcpy(digitp,"-stablbased-");
   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/  
   fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");    if (mobilav!=0) {
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 /*   } */      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   pstamp(ficresvij);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");      }
   if(popbased==1)    }
     fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");  
   else    strcpy(fileresprobmorprev,"prmorprev");
     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");    sprintf(digit,"%-d",ij);
   fprintf(ficresvij,"# Age");    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
   for(i=1; i<=nlstate;i++)    strcat(fileresprobmorprev,digit); /* Tvar to be done */
     for(j=1; j<=nlstate;j++)    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);    strcat(fileresprobmorprev,fileres);
   fprintf(ficresvij,"\n");    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
       printf("Problem with resultfile: %s\n", fileresprobmorprev);
   xp=vector(1,npar);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
   dnewm=matrix(1,nlstate,1,npar);    }
   doldm=matrix(1,nlstate,1,nlstate);    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);   
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
     pstamp(ficresprobmorprev);
   gradgp=matrix(1,npar,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);
   gpp=vector(nlstate+1,nlstate+ndeath);    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
   gmp=vector(nlstate+1,nlstate+ndeath);    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/      fprintf(ficresprobmorprev," p.%-d SE",j);
         for(i=1; i<=nlstate;i++)
   if(estepm < stepm){        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
     printf ("Problem %d lower than %d\n",estepm, stepm);    }  
   }    fprintf(ficresprobmorprev,"\n");
   else  hstepm=estepm;       fprintf(ficgp,"\n# Routine varevsij");
   /* For example we decided to compute the life expectancy with the smallest unit */    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.     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");
      nhstepm is the number of hstepm from age to agelim     fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
      nstepm is the number of stepm from age to agelin.   /*   } */
      Look at hpijx to understand the reason of that which relies in memory size    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
      and note for a fixed period like k years */    pstamp(ficresvij);
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
      survival function given by stepm (the optimization length). Unfortunately it    if(popbased==1)
      means that if the survival funtion is printed every two years of age and if      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     else
      results. So we changed our mind and took the option of the best precision.      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
   */    fprintf(ficresvij,"# Age");
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     for(i=1; i<=nlstate;i++)
   agelim = AGESUP;      for(j=1; j<=nlstate;j++)
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     fprintf(ficresvij,"\n");
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */  
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    xp=vector(1,npar);
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);    dnewm=matrix(1,nlstate,1,npar);
     gp=matrix(0,nhstepm,1,nlstate);    doldm=matrix(1,nlstate,1,nlstate);
     gm=matrix(0,nhstepm,1,nlstate);    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
     doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   
     for(theta=1; theta <=npar; theta++){    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/    gpp=vector(nlstate+1,nlstate+ndeath);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    gmp=vector(nlstate+1,nlstate+ndeath);
       }    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);     
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    if(estepm < stepm){
       printf ("Problem %d lower than %d\n",estepm, stepm);
       if (popbased==1) {    }
         if(mobilav ==0){    else  hstepm=estepm;  
           for(i=1; i<=nlstate;i++)    /* For example we decided to compute the life expectancy with the smallest unit */
             prlim[i][i]=probs[(int)age][i][ij];    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
         }else{ /* mobilav */        nhstepm is the number of hstepm from age to agelim
           for(i=1; i<=nlstate;i++)       nstepm is the number of stepm from age to agelin.
             prlim[i][i]=mobaverage[(int)age][i][ij];       Look at hpijx to understand the reason of that which relies in memory size
         }       and note for a fixed period like k years */
       }    /* 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
       for(j=1; j<= nlstate; j++){       means that if the survival funtion is printed every two years of age and if
         for(h=0; h<=nhstepm; h++){       you sum them up and add 1 year (area under the trapezoids) you won't get the same
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)       results. So we changed our mind and took the option of the best precision.
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];    */
         }    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
       }    agelim = AGESUP;
       /* This for computing probability of death (h=1 means    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
          computed over hstepm matrices product = hstepm*stepm months)       nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
          as a weighted average of prlim.      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       */      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       for(j=nlstate+1;j<=nlstate+ndeath;j++){      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
         for(i=1,gpp[j]=0.; i<= nlstate; i++)      gp=matrix(0,nhstepm,1,nlstate);
           gpp[j] += prlim[i][i]*p3mat[i][j][1];      gm=matrix(0,nhstepm,1,nlstate);
       }      
       /* end probability of death */  
       for(theta=1; theta <=npar; theta++){
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */        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);
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);          }
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
          prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
       if (popbased==1) {  
         if(mobilav ==0){        if (popbased==1) {
           for(i=1; i<=nlstate;i++)          if(mobilav ==0){
             prlim[i][i]=probs[(int)age][i][ij];            for(i=1; i<=nlstate;i++)
         }else{ /* mobilav */               prlim[i][i]=probs[(int)age][i][ij];
           for(i=1; i<=nlstate;i++)          }else{ /* mobilav */
             prlim[i][i]=mobaverage[(int)age][i][ij];            for(i=1; i<=nlstate;i++)
         }              prlim[i][i]=mobaverage[(int)age][i][ij];
       }          }
         }
       for(j=1; j<= nlstate; j++){   
         for(h=0; h<=nhstepm; h++){        for(j=1; j<= nlstate; j++){
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)          for(h=0; h<=nhstepm; h++){
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
         }              gp[h][j] += prlim[i][i]*p3mat[i][j][h];
       }          }
       /* This for computing probability of death (h=1 means        }
          computed over hstepm matrices product = hstepm*stepm months)         /* This for computing probability of death (h=1 means
          as a weighted average of prlim.           computed over hstepm matrices product = hstepm*stepm months)
       */           as a weighted average of prlim.
       for(j=nlstate+1;j<=nlstate+ndeath;j++){        */
         for(i=1,gmp[j]=0.; i<= nlstate; i++)        for(j=nlstate+1;j<=nlstate+ndeath;j++){
          gmp[j] += prlim[i][i]*p3mat[i][j][1];          for(i=1,gpp[j]=0.; i<= nlstate; i++)
       }                gpp[j] += prlim[i][i]*p3mat[i][j][1];
       /* end probability of death */        }    
         /* end probability of death */
       for(j=1; j<= nlstate; j++) /* vareij */  
         for(h=0; h<=nhstepm; h++){        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         }        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
         prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */   
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];        if (popbased==1) {
       }          if(mobilav ==0){
             for(i=1; i<=nlstate;i++)
     } /* End theta */              prlim[i][i]=probs[(int)age][i][ij];
           }else{ /* mobilav */
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */            for(i=1; i<=nlstate;i++)
               prlim[i][i]=mobaverage[(int)age][i][ij];
     for(h=0; h<=nhstepm; h++) /* veij */          }
       for(j=1; j<=nlstate;j++)        }
         for(theta=1; theta <=npar; theta++)  
           trgradg[h][j][theta]=gradg[h][theta][j];        for(j=1; j<= nlstate; j++){
           for(h=0; h<=nhstepm; h++){
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
       for(theta=1; theta <=npar; theta++)              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
         trgradgp[j][theta]=gradgp[theta][j];          }
           }
         /* This for computing probability of death (h=1 means
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */           computed over hstepm matrices product = hstepm*stepm months)
     for(i=1;i<=nlstate;i++)           as a weighted average of prlim.
       for(j=1;j<=nlstate;j++)        */
         vareij[i][j][(int)age] =0.;        for(j=nlstate+1;j<=nlstate+ndeath;j++){
           for(i=1,gmp[j]=0.; i<= nlstate; i++)
     for(h=0;h<=nhstepm;h++){           gmp[j] += prlim[i][i]*p3mat[i][j][1];
       for(k=0;k<=nhstepm;k++){        }    
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);        /* end probability of death */
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);  
         for(i=1;i<=nlstate;i++)        for(j=1; j<= nlstate; j++) /* vareij */
           for(j=1;j<=nlstate;j++)          for(h=0; h<=nhstepm; h++){
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
       }          }
     }  
           for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
     /* pptj */          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);        }
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);  
     for(j=nlstate+1;j<=nlstate+ndeath;j++)      } /* End theta */
       for(i=nlstate+1;i<=nlstate+ndeath;i++)  
         varppt[j][i]=doldmp[j][i];      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
     /* end ppptj */  
     /*  x centered again */      for(h=0; h<=nhstepm; h++) /* veij */
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);          for(j=1; j<=nlstate;j++)
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);          for(theta=1; theta <=npar; theta++)
              trgradg[h][j][theta]=gradg[h][theta][j];
     if (popbased==1) {  
       if(mobilav ==0){      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
         for(i=1; i<=nlstate;i++)        for(theta=1; theta <=npar; theta++)
           prlim[i][i]=probs[(int)age][i][ij];          trgradgp[j][theta]=gradgp[theta][j];
       }else{ /* mobilav */    
         for(i=1; i<=nlstate;i++)  
           prlim[i][i]=mobaverage[(int)age][i][ij];      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       }      for(i=1;i<=nlstate;i++)
     }        for(j=1;j<=nlstate;j++)
                        vareij[i][j][(int)age] =0.;
     /* This for computing probability of death (h=1 means  
        computed over hstepm (estepm) matrices product = hstepm*stepm months)       for(h=0;h<=nhstepm;h++){
        as a weighted average of prlim.        for(k=0;k<=nhstepm;k++){
     */          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
     for(j=nlstate+1;j<=nlstate+ndeath;j++){          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
       for(i=1,gmp[j]=0.;i<= nlstate; i++)           for(i=1;i<=nlstate;i++)
         gmp[j] += prlim[i][i]*p3mat[i][j][1];             for(j=1;j<=nlstate;j++)
     }                  vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
     /* end probability of death */        }
       }
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);   
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){      /* pptj */
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
       for(i=1; i<=nlstate;i++){      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);      for(j=nlstate+1;j<=nlstate+ndeath;j++)
       }        for(i=nlstate+1;i<=nlstate+ndeath;i++)
     }           varppt[j][i]=doldmp[j][i];
     fprintf(ficresprobmorprev,"\n");      /* end ppptj */
       /*  x centered again */
     fprintf(ficresvij,"%.0f ",age );      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
     for(i=1; i<=nlstate;i++)      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
       for(j=1; j<=nlstate;j++){   
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);      if (popbased==1) {
       }        if(mobilav ==0){
     fprintf(ficresvij,"\n");          for(i=1; i<=nlstate;i++)
     free_matrix(gp,0,nhstepm,1,nlstate);            prlim[i][i]=probs[(int)age][i][ij];
     free_matrix(gm,0,nhstepm,1,nlstate);        }else{ /* mobilav */
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);          for(i=1; i<=nlstate;i++)
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);            prlim[i][i]=mobaverage[(int)age][i][ij];
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        }
   } /* End age */      }
   free_vector(gpp,nlstate+1,nlstate+ndeath);               
   free_vector(gmp,nlstate+1,nlstate+ndeath);      /* This for computing probability of death (h=1 means
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);         computed over hstepm (estepm) matrices product = hstepm*stepm months)
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/         as a weighted average of prlim.
   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 */      for(j=nlstate+1;j<=nlstate+ndeath;j++){
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");        for(i=1,gmp[j]=0.;i<= nlstate; i++)
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */      }    
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */      /* end probability of death */
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));  
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);        for(i=1; i<=nlstate;i++){
   /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 */        }
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */      }
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);      fprintf(ficresprobmorprev,"\n");
   
   free_vector(xp,1,npar);      fprintf(ficresvij,"%.0f ",age );
   free_matrix(doldm,1,nlstate,1,nlstate);      for(i=1; i<=nlstate;i++)
   free_matrix(dnewm,1,nlstate,1,npar);        for(j=1; j<=nlstate;j++){
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);        }
   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);      free_matrix(gp,0,nhstepm,1,nlstate);
   fclose(ficresprobmorprev);      free_matrix(gm,0,nhstepm,1,nlstate);
   fflush(ficgp);      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
   fflush(fichtm);       free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 }  /* end varevsij */      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     } /* End age */
 /************ Variance of prevlim ******************/    free_vector(gpp,nlstate+1,nlstate+ndeath);
 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[])    free_vector(gmp,nlstate+1,nlstate+ndeath);
 {    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
   /* Variance of prevalence limit */    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
   double **newm;    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
   double **dnewm,**doldm;    fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
   int i, j, nhstepm, hstepm;  /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
   int k, cptcode;  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
   double *xp;  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
   double *gp, *gm;    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
   double **gradg, **trgradg;    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
   double age,agelim;    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
   int theta;    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);
   pstamp(ficresvpl);    /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);
   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");  */
   fprintf(ficresvpl,"# Age");  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
   for(i=1; i<=nlstate;i++)    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
       fprintf(ficresvpl," %1d-%1d",i,i);  
   fprintf(ficresvpl,"\n");    free_vector(xp,1,npar);
     free_matrix(doldm,1,nlstate,1,nlstate);
   xp=vector(1,npar);    free_matrix(dnewm,1,nlstate,1,npar);
   dnewm=matrix(1,nlstate,1,npar);    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   doldm=matrix(1,nlstate,1,nlstate);    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
       free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   hstepm=1*YEARM; /* Every year of age */    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */     fclose(ficresprobmorprev);
   agelim = AGESUP;    fflush(ficgp);
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    fflush(fichtm);
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */   }  /* end varevsij */
     if (stepm >= YEARM) hstepm=1;  
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */  /************ Variance of prevlim ******************/
     gradg=matrix(1,npar,1,nlstate);  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[])
     gp=vector(1,nlstate);  {
     gm=vector(1,nlstate);    /* Variance of prevalence limit */
     /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
     for(theta=1; theta <=npar; theta++){    double **newm;
       for(i=1; i<=npar; i++){ /* Computes gradient */    double **dnewm,**doldm;
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    int i, j, nhstepm, hstepm;
       }    int k, cptcode;
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    double *xp;
       for(i=1;i<=nlstate;i++)    double *gp, *gm;
         gp[i] = prlim[i][i];    double **gradg, **trgradg;
         double age,agelim;
       for(i=1; i<=npar; i++) /* Computes gradient */    int theta;
         xp[i] = x[i] - (i==theta ?delti[theta]:0);   
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    pstamp(ficresvpl);
       for(i=1;i<=nlstate;i++)    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
         gm[i] = prlim[i][i];    fprintf(ficresvpl,"# Age");
     for(i=1; i<=nlstate;i++)
       for(i=1;i<=nlstate;i++)        fprintf(ficresvpl," %1d-%1d",i,i);
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];    fprintf(ficresvpl,"\n");
     } /* End theta */  
     xp=vector(1,npar);
     trgradg =matrix(1,nlstate,1,npar);    dnewm=matrix(1,nlstate,1,npar);
     doldm=matrix(1,nlstate,1,nlstate);
     for(j=1; j<=nlstate;j++)   
       for(theta=1; theta <=npar; theta++)    hstepm=1*YEARM; /* Every year of age */
         trgradg[j][theta]=gradg[theta][j];    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
     agelim = AGESUP;
     for(i=1;i<=nlstate;i++)    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
       varpl[i][(int)age] =0.;      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);      if (stepm >= YEARM) hstepm=1;
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
     for(i=1;i<=nlstate;i++)      gradg=matrix(1,npar,1,nlstate);
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */      gp=vector(1,nlstate);
       gm=vector(1,nlstate);
     fprintf(ficresvpl,"%.0f ",age );  
     for(i=1; i<=nlstate;i++)      for(theta=1; theta <=npar; theta++){
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));        for(i=1; i<=npar; i++){ /* Computes gradient */
     fprintf(ficresvpl,"\n");          xp[i] = x[i] + (i==theta ?delti[theta]:0);
     free_vector(gp,1,nlstate);        }
     free_vector(gm,1,nlstate);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
     free_matrix(gradg,1,npar,1,nlstate);        for(i=1;i<=nlstate;i++)
     free_matrix(trgradg,1,nlstate,1,npar);          gp[i] = prlim[i][i];
   } /* End age */     
         for(i=1; i<=npar; i++) /* Computes gradient */
   free_vector(xp,1,npar);          xp[i] = x[i] - (i==theta ?delti[theta]:0);
   free_matrix(doldm,1,nlstate,1,npar);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   free_matrix(dnewm,1,nlstate,1,nlstate);        for(i=1;i<=nlstate;i++)
           gm[i] = prlim[i][i];
 }  
         for(i=1;i<=nlstate;i++)
 /************ Variance of one-step probabilities  ******************/          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 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[])      } /* End theta */
 {  
   int i, j=0,  i1, k1, l1, t, tj;      trgradg =matrix(1,nlstate,1,npar);
   int k2, l2, j1,  z1;  
   int k=0,l, cptcode;      for(j=1; j<=nlstate;j++)
   int first=1, first1;        for(theta=1; theta <=npar; theta++)
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;          trgradg[j][theta]=gradg[theta][j];
   double **dnewm,**doldm;  
   double *xp;      for(i=1;i<=nlstate;i++)
   double *gp, *gm;        varpl[i][(int)age] =0.;
   double **gradg, **trgradg;      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
   double **mu;      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
   double age,agelim, cov[NCOVMAX];      for(i=1;i<=nlstate;i++)
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
   int theta;  
   char fileresprob[FILENAMELENGTH];      fprintf(ficresvpl,"%.0f ",age );
   char fileresprobcov[FILENAMELENGTH];      for(i=1; i<=nlstate;i++)
   char fileresprobcor[FILENAMELENGTH];        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
       fprintf(ficresvpl,"\n");
   double ***varpij;      free_vector(gp,1,nlstate);
       free_vector(gm,1,nlstate);
   strcpy(fileresprob,"prob");       free_matrix(gradg,1,npar,1,nlstate);
   strcat(fileresprob,fileres);      free_matrix(trgradg,1,nlstate,1,npar);
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {    } /* End age */
     printf("Problem with resultfile: %s\n", fileresprob);  
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);    free_vector(xp,1,npar);
   }    free_matrix(doldm,1,nlstate,1,npar);
   strcpy(fileresprobcov,"probcov");     free_matrix(dnewm,1,nlstate,1,nlstate);
   strcat(fileresprobcov,fileres);  
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {  }
     printf("Problem with resultfile: %s\n", fileresprobcov);  
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);  /************ Variance of one-step probabilities  ******************/
   }  void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])
   strcpy(fileresprobcor,"probcor");   {
   strcat(fileresprobcor,fileres);    int i, j=0,  i1, k1, l1, t, tj;
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {    int k2, l2, j1,  z1;
     printf("Problem with resultfile: %s\n", fileresprobcor);    int k=0,l, cptcode;
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);    int first=1, first1;
   }    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    double **dnewm,**doldm;
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    double *xp;
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    double *gp, *gm;
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    double **gradg, **trgradg;
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    double **mu;
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    double age,agelim, cov[NCOVMAX];
   pstamp(ficresprob);    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");    int theta;
   fprintf(ficresprob,"# Age");    char fileresprob[FILENAMELENGTH];
   pstamp(ficresprobcov);    char fileresprobcov[FILENAMELENGTH];
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");    char fileresprobcor[FILENAMELENGTH];
   fprintf(ficresprobcov,"# Age");  
   pstamp(ficresprobcor);    double ***varpij;
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");  
   fprintf(ficresprobcor,"# Age");    strcpy(fileresprob,"prob");
     strcat(fileresprob,fileres);
     if((ficresprob=fopen(fileresprob,"w"))==NULL) {
   for(i=1; i<=nlstate;i++)      printf("Problem with resultfile: %s\n", fileresprob);
     for(j=1; j<=(nlstate+ndeath);j++){      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);    }
       fprintf(ficresprobcov," p%1d-%1d ",i,j);    strcpy(fileresprobcov,"probcov");
       fprintf(ficresprobcor," p%1d-%1d ",i,j);    strcat(fileresprobcov,fileres);
     }      if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
  /* fprintf(ficresprob,"\n");      printf("Problem with resultfile: %s\n", fileresprobcov);
   fprintf(ficresprobcov,"\n");      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
   fprintf(ficresprobcor,"\n");    }
  */    strcpy(fileresprobcor,"probcor");
  xp=vector(1,npar);    strcat(fileresprobcor,fileres);
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));      printf("Problem with resultfile: %s\n", fileresprobcor);
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);    }
   first=1;    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(ficgp,"\n# Routine varprob");    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
   fprintf(fichtm,"\n");    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
     printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\    pstamp(ficresprob);
   file %s<br>\n",optionfilehtmcov);    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\    fprintf(ficresprob,"# Age");
 and drawn. It helps understanding how is the covariance between two incidences.\    pstamp(ficresprobcov);
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\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(ficresprobcov,"# Age");
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \    pstamp(ficresprobcor);
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 standard deviations wide on each axis. <br>\    fprintf(ficresprobcor,"# Age");
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\  
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\  
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");    for(i=1; i<=nlstate;i++)
       for(j=1; j<=(nlstate+ndeath);j++){
   cov[1]=1;        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
   tj=cptcoveff;        fprintf(ficresprobcov," p%1d-%1d ",i,j);
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}        fprintf(ficresprobcor," p%1d-%1d ",i,j);
   j1=0;      }  
   for(t=1; t<=tj;t++){   /* fprintf(ficresprob,"\n");
     for(i1=1; i1<=ncodemax[t];i1++){     fprintf(ficresprobcov,"\n");
       j1++;    fprintf(ficresprobcor,"\n");
       if  (cptcovn>0) {   */
         fprintf(ficresprob, "\n#********** Variable ");    xp=vector(1,npar);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
         fprintf(ficresprob, "**********\n#\n");    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
         fprintf(ficresprobcov, "\n#********** Variable ");     mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
         fprintf(ficresprobcov, "**********\n#\n");    first=1;
             fprintf(ficgp,"\n# Routine varprob");
         fprintf(ficgp, "\n#********** Variable ");     fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    fprintf(fichtm,"\n");
         fprintf(ficgp, "**********\n#\n");  
             fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
             fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");     file %s<br>\n",optionfilehtmcov);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");  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");
         fprintf(ficresprobcor, "\n#********** Variable ");        fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
         fprintf(ficresprobcor, "**********\n#");      would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
       }  standard deviations wide on each axis. <br>\
          Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
       for (age=bage; age<=fage; age ++){    and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
         cov[2]=age;  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
         for (k=1; k<=cptcovn;k++) {  
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];    cov[1]=1;
         }    tj=cptcoveff;
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
         for (k=1; k<=cptcovprod;k++)    j1=0;
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];    for(t=1; t<=tj;t++){
               for(i1=1; i1<=ncodemax[t];i1++){
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));        j1++;
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);        if  (cptcovn>0) {
         gp=vector(1,(nlstate)*(nlstate+ndeath));          fprintf(ficresprob, "\n#********** Variable ");
         gm=vector(1,(nlstate)*(nlstate+ndeath));          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
               fprintf(ficresprob, "**********\n#\n");
         for(theta=1; theta <=npar; theta++){          fprintf(ficresprobcov, "\n#********** Variable ");
           for(i=1; i<=npar; i++)          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);          fprintf(ficresprobcov, "**********\n#\n");
                    
           pmij(pmmij,cov,ncovmodel,xp,nlstate);          fprintf(ficgp, "\n#********** Variable ");
                     for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           k=0;          fprintf(ficgp, "**********\n#\n");
           for(i=1; i<= (nlstate); i++){         
             for(j=1; j<=(nlstate+ndeath);j++){         
               k=k+1;          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
               gp[k]=pmmij[i][j];          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             }          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
           }         
                     fprintf(ficresprobcor, "\n#********** Variable ");    
           for(i=1; i<=npar; i++)          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);          fprintf(ficresprobcor, "**********\n#");    
             }
           pmij(pmmij,cov,ncovmodel,xp,nlstate);       
           k=0;        for (age=bage; age<=fage; age ++){
           for(i=1; i<=(nlstate); i++){          cov[2]=age;
             for(j=1; j<=(nlstate+ndeath);j++){          for (k=1; k<=cptcovn;k++) {
               k=k+1;            cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
               gm[k]=pmmij[i][j];          }
             }          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           }          for (k=1; k<=cptcovprod;k++)
                  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)          
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];            gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
         }          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
           gp=vector(1,(nlstate)*(nlstate+ndeath));
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)          gm=vector(1,(nlstate)*(nlstate+ndeath));
           for(theta=1; theta <=npar; theta++)     
             trgradg[j][theta]=gradg[theta][j];          for(theta=1; theta <=npar; theta++){
                     for(i=1; i<=npar; i++)
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);               xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);           
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));            pmij(pmmij,cov,ncovmodel,xp,nlstate);
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));           
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);            k=0;
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);            for(i=1; i<= (nlstate); i++){
               for(j=1; j<=(nlstate+ndeath);j++){
         pmij(pmmij,cov,ncovmodel,x,nlstate);                k=k+1;
                         gp[k]=pmmij[i][j];
         k=0;              }
         for(i=1; i<=(nlstate); i++){            }
           for(j=1; j<=(nlstate+ndeath);j++){           
             k=k+1;            for(i=1; i<=npar; i++)
             mu[k][(int) age]=pmmij[i][j];              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
           }     
         }            pmij(pmmij,cov,ncovmodel,xp,nlstate);
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)            k=0;
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)            for(i=1; i<=(nlstate); i++){
             varpij[i][j][(int)age] = doldm[i][j];              for(j=1; j<=(nlstate+ndeath);j++){
                 k=k+1;
         /*printf("\n%d ",(int)age);                gm[k]=pmmij[i][j];
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){              }
           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));            }
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));       
           }*/            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
               gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
         fprintf(ficresprob,"\n%d ",(int)age);          }
         fprintf(ficresprobcov,"\n%d ",(int)age);  
         fprintf(ficresprobcor,"\n%d ",(int)age);          for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
             for(theta=1; theta <=npar; theta++)
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)              trgradg[j][theta]=gradg[theta][j];
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));         
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
         }          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
         i=0;          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
         for (k=1; k<=(nlstate);k++){          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
           for (l=1; l<=(nlstate+ndeath);l++){   
             i=i++;          pmij(pmmij,cov,ncovmodel,x,nlstate);
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);         
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);          k=0;
             for (j=1; j<=i;j++){          for(i=1; i<=(nlstate); i++){
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);            for(j=1; j<=(nlstate+ndeath);j++){
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));              k=k+1;
             }              mu[k][(int) age]=pmmij[i][j];
           }            }
         }/* end of loop for state */          }
       } /* end of loop for age */          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
             for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
       /* Confidence intervalle of pij  */              varpij[i][j][(int)age] = doldm[i][j];
       /*  
         fprintf(ficgp,"\nset noparametric;unset label");          /*printf("\n%d ",(int)age);
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");            for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
         fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);            }*/
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);  
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);          fprintf(ficresprob,"\n%d ",(int)age);
       */          fprintf(ficresprobcov,"\n%d ",(int)age);
           fprintf(ficresprobcor,"\n%d ",(int)age);
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/  
       first1=1;          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
       for (k2=1; k2<=(nlstate);k2++){            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
         for (l2=1; l2<=(nlstate+ndeath);l2++){           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
           if(l2==k2) continue;            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
           j=(k2-1)*(nlstate+ndeath)+l2;            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
           for (k1=1; k1<=(nlstate);k1++){          }
             for (l1=1; l1<=(nlstate+ndeath);l1++){           i=0;
               if(l1==k1) continue;          for (k=1; k<=(nlstate);k++){
               i=(k1-1)*(nlstate+ndeath)+l1;            for (l=1; l<=(nlstate+ndeath);l++){
               if(i<=j) continue;              i=i++;
               for (age=bage; age<=fage; age ++){               fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                 if ((int)age %5==0){              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;              for (j=1; j<=i;j++){
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   mu1=mu[i][(int) age]/stepm*YEARM ;              }
                   mu2=mu[j][(int) age]/stepm*YEARM;            }
                   c12=cv12/sqrt(v1*v2);          }/* end of loop for state */
                   /* Computing eigen value of matrix of covariance */        } /* end of loop for age */
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;  
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;        /* Confidence intervalle of pij  */
                   /* Eigen vectors */        /*
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));          fprintf(ficgp,"\nset noparametric;unset label");
                   /*v21=sqrt(1.-v11*v11); *//* error */          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   v21=(lc1-v1)/cv12*v11;          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   v12=-v21;          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);
                   v22=v11;          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   tnalp=v21/v11;          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   if(first1==1){          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                     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);  
                   }        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   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);        first1=1;
                   /*printf(fignu*/        for (k2=1; k2<=(nlstate);k2++){
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */          for (l2=1; l2<=(nlstate+ndeath);l2++){
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */            if(l2==k2) continue;
                   if(first==1){            j=(k2-1)*(nlstate+ndeath)+l2;
                     first=0;            for (k1=1; k1<=(nlstate);k1++){
                     fprintf(ficgp,"\nset parametric;unset label");              for (l1=1; l1<=(nlstate+ndeath);l1++){
                     fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);                if(l1==k1) continue;
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");                i=(k1-1)*(nlstate+ndeath)+l1;
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\                if(i<=j) continue;
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\                for (age=bage; age<=fage; age ++){
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\                  if ((int)age %5==0){
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);                    mu1=mu[i][(int) age]/stepm*YEARM ;
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    mu2=mu[j][(int) age]/stepm*YEARM;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                    c12=cv12/sqrt(v1*v2);
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                    /* Computing eigen value of matrix of covariance */
                     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",\                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                    /* Eigen vectors */
                   }else{                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                     first=0;                    /*v21=sqrt(1.-v11*v11); *//* error */
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);                    v21=(lc1-v1)/cv12*v11;
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                    v12=-v21;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                    v22=v11;
                     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",\                    tnalp=v21/v11;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                    if(first1==1){
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                      first1=0;
                   }/* if first */                      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);
                 } /* age mod 5 */                    }
               } /* end loop age */                    fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    /*printf(fignu*/
               first=1;                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
             } /*l12 */                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
           } /* k12 */                    if(first==1){
         } /*l1 */                      first=0;
       }/* k1 */                      fprintf(ficgp,"\nset parametric;unset label");
     } /* loop covariates */                      fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);
   }                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
   free_vector(xp,1,npar);                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   fclose(ficresprob);                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   fclose(ficresprobcov);                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
   fclose(ficresprobcor);                      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   fflush(ficgp);                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
   fflush(fichtmcov);                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 }                      fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
                               mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                               mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 /******************* Printing html file ***********/                    }else{
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \                      first=0;
                   int lastpass, int stepm, int weightopt, char model[],\                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   int popforecast, int estepm ,\                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   double jprev1, double mprev1,double anprev1, \                      fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
                   double jprev2, double mprev2,double anprev2){                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
   int jj1, k1, i1, cpt;                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                     }/* if first */
    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \                  } /* age mod 5 */
    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \                } /* end loop age */
 </ul>");                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \                first=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 ",              } /*l12 */
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));            } /* k12 */
    fprintf(fichtm,"\          } /*l1 */
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",        }/* k1 */
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));      } /* loop covariates */
    fprintf(fichtm,"\    }
  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
    fprintf(fichtm,"\    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
  - (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): \    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
    <a href=\"%s\">%s</a> <br>\n</li>",    free_vector(xp,1,npar);
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));    fclose(ficresprob);
     fclose(ficresprobcov);
     fclose(ficresprobcor);
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");    fflush(ficgp);
     fflush(fichtmcov);
  m=cptcoveff;  }
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}  
   
  jj1=0;  /******************* Printing html file ***********/
  for(k1=1; k1<=m;k1++){  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
    for(i1=1; i1<=ncodemax[k1];i1++){                    int lastpass, int stepm, int weightopt, char model[],\
      jj1++;                    int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
      if (cptcovn > 0) {                    int popforecast, int estepm ,\
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");                    double jprev1, double mprev1,double anprev1, \
        for (cpt=1; cpt<=cptcoveff;cpt++)                     double jprev2, double mprev2,double anprev2){
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    int jj1, k1, i1, cpt;
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");  
      }     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
      /* Pij */     <li><a href='#secondorder'>Result files (second order (variance)</a>\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> \  </ul>");
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);          fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
      /* Quasi-incidences */   - 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(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \     fprintf(fichtm,"\
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
        /* Period (stable) prevalence in each health state */             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
        for(cpt=1; cpt<nlstate;cpt++){     fprintf(fichtm,"\
          fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
        }     fprintf(fichtm,"\
      for(cpt=1; cpt<=nlstate;cpt++) {   - (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): \
         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> \     <a href=\"%s\">%s</a> <br>\n",
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
      }     fprintf(fichtm,"\
    } /* end i1 */   - Population projections by age and states: \
  }/* End k1 */     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
  fprintf(fichtm,"</ul>");  
   fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
   
  fprintf(fichtm,"\   m=cptcoveff;
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);  
    jj1=0;
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",   for(k1=1; k1<=m;k1++){
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));     for(i1=1; i1<=ncodemax[k1];i1++){
  fprintf(fichtm,"\       jj1++;
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",       if (cptcovn > 0) {
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
          for (cpt=1; cpt<=cptcoveff;cpt++)
  fprintf(fichtm,"\           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));       }
  fprintf(fichtm,"\       /* Pij */
  - 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(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> \
    <a href=\"%s\">%s</a> <br>\n</li>",  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
            estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));       /* Quasi-incidences */
  fprintf(fichtm,"\       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
  - (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): \   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> \
    <a href=\"%s\">%s</a> <br>\n</li>",  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
            estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));         /* Period (stable) prevalence in each health state */
  fprintf(fichtm,"\         for(cpt=1; cpt<nlstate;cpt++){
  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), eij are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences (i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
  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",       for(cpt=1; cpt<=nlstate;cpt++) {
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));          fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
  fprintf(fichtm,"\  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\       }
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));     } /* end i1 */
    }/* End k1 */
 /*  if(popforecast==1) fprintf(fichtm,"\n */   fprintf(fichtm,"</ul>");
 /*  - 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); */   fprintf(fichtm,"\
 /*  else  */  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 /*    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); */   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
  fflush(fichtm);  
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
            subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
  m=cptcoveff;   fprintf(fichtm,"\
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
            subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
  jj1=0;  
  for(k1=1; k1<=m;k1++){   fprintf(fichtm,"\
    for(i1=1; i1<=ncodemax[k1];i1++){   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
      jj1++;           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
      if (cptcovn > 0) {   fprintf(fichtm,"\
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");   - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
        for (cpt=1; cpt<=cptcoveff;cpt++)      <a href=\"%s\">%s</a> <br>\n</li>",
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");   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): \
      for(cpt=1; cpt<=nlstate;cpt++) {     <a href=\"%s\">%s</a> <br>\n</li>",
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\   fprintf(fichtm,"\
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);     - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), eij are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences (i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
      }           estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \   fprintf(fichtm,"\
 health expectancies in states (1) and (2): %s%d.png<br>\   - 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",
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);           subdirf2(fileres,"t"),subdirf2(fileres,"t"));
    } /* end i1 */   fprintf(fichtm,"\
  }/* End k1 */   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
  fprintf(fichtm,"</ul>");           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
  fflush(fichtm);  
 }  /*  if(popforecast==1) fprintf(fichtm,"\n */
   /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 /******************* Gnuplot file **************/  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){  /*      <br>",fileres,fileres,fileres,fileres); */
   /*  else  */
   char dirfileres[132],optfileres[132];  /*    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); */
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;   fflush(fichtm);
   int ng;   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */  
 /*     printf("Problem with file %s",optionfilegnuplot); */   m=cptcoveff;
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 /*   } */  
    jj1=0;
   /*#ifdef windows */   for(k1=1; k1<=m;k1++){
   fprintf(ficgp,"cd \"%s\" \n",pathc);     for(i1=1; i1<=ncodemax[k1];i1++){
     /*#endif */       jj1++;
   m=pow(2,cptcoveff);       if (cptcovn > 0) {
          fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
   strcpy(dirfileres,optionfilefiname);         for (cpt=1; cpt<=cptcoveff;cpt++)
   strcpy(optfileres,"vpl");           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
  /* 1eme*/         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
   for (cpt=1; cpt<= nlstate ; cpt ++) {       }
    for (k1=1; k1<= m ; k1 ++) {       for(cpt=1; cpt<=nlstate;cpt++) {
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
      fprintf(ficgp,"set xlabel \"Age\" \n\  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 set ylabel \"Probability\" \n\       }
 set ter png small\n\       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 set size 0.65,0.65\n\  health expectancies in states (1) and (2): %s%d.png<br>\
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);  <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
      } /* end i1 */
      for (i=1; i<= nlstate ; i ++) {   }/* End k1 */
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");   fprintf(fichtm,"</ul>");
        else fprintf(ficgp," \%%*lf (\%%*lf)");   fflush(fichtm);
      }  }
      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);  
      for (i=1; i<= nlstate ; i ++) {  /******************* Gnuplot file **************/
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");  void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
        else fprintf(ficgp," \%%*lf (\%%*lf)");  
      }     char dirfileres[132],optfileres[132];
      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);     int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
      for (i=1; i<= nlstate ; i ++) {    int ng;
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
        else fprintf(ficgp," \%%*lf (\%%*lf)");  /*     printf("Problem with file %s",optionfilegnuplot); */
      }    /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
      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));  /*   } */
    }  
   }    /*#ifdef windows */
   /*2 eme*/    fprintf(ficgp,"cd \"%s\" \n",pathc);
         /*#endif */
   for (k1=1; k1<= m ; k1 ++) {     m=pow(2,cptcoveff);
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);  
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);    strcpy(dirfileres,optionfilefiname);
         strcpy(optfileres,"vpl");
     for (i=1; i<= nlstate+1 ; i ++) {   /* 1eme*/
       k=2*i;    for (cpt=1; cpt<= nlstate ; cpt ++) {
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);     for (k1=1; k1<= m ; k1 ++) {
       for (j=1; j<= nlstate+1 ; j ++) {       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");       fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
         else fprintf(ficgp," \%%*lf (\%%*lf)");       fprintf(ficgp,"set xlabel \"Age\" \n\
       }     set ylabel \"Probability\" \n\
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");  set ter png small\n\
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);  set size 0.65,0.65\n\
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
       for (j=1; j<= nlstate+1 ; j ++) {  
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");       for (i=1; i<= nlstate ; i ++) {
         else fprintf(ficgp," \%%*lf (\%%*lf)");         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       }            else fprintf(ficgp," \%%*lf (\%%*lf)");
       fprintf(ficgp,"\" t\"\" w l 0,");       }
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);       fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
       for (j=1; j<= nlstate+1 ; j ++) {       for (i=1; i<= nlstate ; i ++) {
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
         else fprintf(ficgp," \%%*lf (\%%*lf)");         else fprintf(ficgp," \%%*lf (\%%*lf)");
       }          }
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");       fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
       else fprintf(ficgp,"\" t\"\" w l 0,");       for (i=1; i<= nlstate ; i ++) {
     }         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
   }         else fprintf(ficgp," \%%*lf (\%%*lf)");
          }  
   /*3eme*/       fprintf(ficgp,"\" t\"\" w l 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
        }
   for (k1=1; k1<= m ; k1 ++) {     }
     for (cpt=1; cpt<= nlstate ; cpt ++) {    /*2 eme*/
       /*       k=2+nlstate*(2*cpt-2); */   
       k=2+(nlstate+1)*(cpt-1);    for (k1=1; k1<= m ; k1 ++) {
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);      fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
       fprintf(ficgp,"set ter png small\n\      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
 set size 0.65,0.65\n\     
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);      for (i=1; i<= nlstate+1 ; i ++) {
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);        k=2*i;
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);        for (j=1; j<= nlstate+1 ; j ++) {
         fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");          else fprintf(ficgp," \%%*lf (\%%*lf)");
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);        }  
                 if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
       */        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
       for (i=1; i< nlstate ; i ++) {        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
         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);        for (j=1; j<= nlstate+1 ; j ++) {
         /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   else fprintf(ficgp," \%%*lf (\%%*lf)");
       }         }  
       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);        fprintf(ficgp,"\" t\"\" w l 0,");
     }        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
   }        for (j=1; j<= nlstate+1 ; j ++) {
             if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
   /* CV preval stable (period) */          else fprintf(ficgp," \%%*lf (\%%*lf)");
   for (k1=1; k1<= m ; k1 ++) {         }  
     for (cpt=1; cpt<=nlstate ; cpt ++) {        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
       k=3;        else fprintf(ficgp,"\" t\"\" w l 0,");
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);      }
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\    }
 set ter png small\nset size 0.65,0.65\n\   
 unset log y\n\    /*3eme*/
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);   
           for (k1=1; k1<= m ; k1 ++) {
       for (i=1; i< nlstate ; i ++)      for (cpt=1; cpt<= nlstate ; cpt ++) {
         fprintf(ficgp,"+$%d",k+i+1);        /*       k=2+nlstate*(2*cpt-2); */
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);        k=2+(nlstate+1)*(cpt-1);
               fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
       l=3+(nlstate+ndeath)*cpt;        fprintf(ficgp,"set ter png small\n\
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);  set size 0.65,0.65\n\
       for (i=1; i< nlstate ; i ++) {  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
         l=3+(nlstate+ndeath)*cpt;        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
         fprintf(ficgp,"+$%d",l+i+1);          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
       }          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);             fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
     }           for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
   }            fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
            
   /* proba elementaires */        */
   for(i=1,jk=1; i <=nlstate; i++){        for (i=1; i< nlstate ; i ++) {
     for(k=1; k <=(nlstate+ndeath); k++){          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);
       if (k != i) {          /*      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 <=ncovmodel; j++){         
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);        }
           jk++;         fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
           fprintf(ficgp,"\n");      }
         }    }
       }   
     }    /* CV preval stable (period) */
    }    for (k1=1; k1<= m ; k1 ++) {
       for (cpt=1; cpt<=nlstate ; cpt ++) {
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/        k=3;
      for(jk=1; jk <=m; jk++) {        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);         fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
        if (ng==2)  set ter png small\nset size 0.65,0.65\n\
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");  unset log y\n\
        else  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
          fprintf(ficgp,"\nset title \"Probability\"\n");       
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);        for (i=1; i< nlstate ; i ++)
        i=1;          fprintf(ficgp,"+$%d",k+i+1);
        for(k2=1; k2<=nlstate; k2++) {        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
          k3=i;       
          for(k=1; k<=(nlstate+ndeath); k++) {        l=3+(nlstate+ndeath)*cpt;
            if (k != k2){        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
              if(ng==2)        for (i=1; i< nlstate ; i ++) {
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);          l=3+(nlstate+ndeath)*cpt;
              else          fprintf(ficgp,"+$%d",l+i+1);
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);        }
              ij=1;        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
              for(j=3; j <=ncovmodel; j++) {      }
                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++;    /* proba elementaires */
                }    for(i=1,jk=1; i <=nlstate; i++){
                else      for(k=1; k <=(nlstate+ndeath); k++){
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);        if (k != i) {
              }          for(j=1; j <=ncovmodel; j++){
              fprintf(ficgp,")/(1");            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                          jk++;
              for(k1=1; k1 <=nlstate; k1++){               fprintf(ficgp,"\n");
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);          }
                ij=1;        }
                for(j=3; j <=ncovmodel; j++){      }
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {     }
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);  
                    ij++;     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                  }       for(jk=1; jk <=m; jk++) {
                  else         fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);         if (ng==2)
                }           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                fprintf(ficgp,")");         else
              }           fprintf(ficgp,"\nset title \"Probability\"\n");
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");         i=1;
              i=i+ncovmodel;         for(k2=1; k2<=nlstate; k2++) {
            }           k3=i;
          } /* end k */           for(k=1; k<=(nlstate+ndeath); k++) {
        } /* end k2 */             if (k != k2){
      } /* end jk */               if(ng==2)
    } /* end ng */                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
    fflush(ficgp);                else
 }  /* end gnuplot */                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                ij=1;
                for(j=3; j <=ncovmodel; j++) {
 /*************** Moving average **************/                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                    ij++;
   int i, cpt, cptcod;                 }
   int modcovmax =1;                 else
   int mobilavrange, mob;                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
   double age;               }
                fprintf(ficgp,")/(1");
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose                
                            a covariate has 2 modalities */               for(k1=1; k1 <=nlstate; k1++){  
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                  ij=1;
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){                 for(j=3; j <=ncovmodel; j++){
     if(mobilav==1) mobilavrange=5; /* default */                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
     else mobilavrange=mobilav;                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
     for (age=bage; age<=fage; age++)                     ij++;
       for (i=1; i<=nlstate;i++)                   }
         for (cptcod=1;cptcod<=modcovmax;cptcod++)                   else
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
     /* 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                 fprintf(ficgp,")");
        we use a 5 terms etc. until the borders are no more concerned.                }
     */                fprintf(ficgp,") t \"p%d%d\" ", k2,k);
     for (mob=3;mob <=mobilavrange;mob=mob+2){               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){               i=i+ncovmodel;
         for (i=1; i<=nlstate;i++){             }
           for (cptcod=1;cptcod<=modcovmax;cptcod++){           } /* end k */
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];         } /* end k2 */
               for (cpt=1;cpt<=(mob-1)/2;cpt++){       } /* end jk */
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];     } /* end ng */
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];     fflush(ficgp);
               }  }  /* end gnuplot */
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;  
           }  
         }  /*************** Moving average **************/
       }/* end age */  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
     }/* end mob */  
   }else return -1;    int i, cpt, cptcod;
   return 0;    int modcovmax =1;
 }/* End movingaverage */    int mobilavrange, mob;
     double age;
   
 /************** Forecasting ******************/    modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
 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){                             a covariate has 2 modalities */
   /* proj1, year, month, day of starting projection     if (cptcovn<1) modcovmax=1; /* At least 1 pass */
      agemin, agemax range of age  
      dateprev1 dateprev2 range of dates during which prevalence is computed    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
      anproj2 year of en of projection (same day and month as proj1).      if(mobilav==1) mobilavrange=5; /* default */
   */      else mobilavrange=mobilav;
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;      for (age=bage; age<=fage; age++)
   int *popage;        for (i=1; i<=nlstate;i++)
   double agec; /* generic age */          for (cptcod=1;cptcod<=modcovmax;cptcod++)
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
   double *popeffectif,*popcount;      /* We keep the original values on the extreme ages bage, fage and for
   double ***p3mat;         fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
   double ***mobaverage;         we use a 5 terms etc. until the borders are no more concerned.
   char fileresf[FILENAMELENGTH];      */
       for (mob=3;mob <=mobilavrange;mob=mob+2){
   agelim=AGESUP;        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);          for (i=1; i<=nlstate;i++){
              for (cptcod=1;cptcod<=modcovmax;cptcod++){
   strcpy(fileresf,"f");               mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
   strcat(fileresf,fileres);                for (cpt=1;cpt<=(mob-1)/2;cpt++){
   if((ficresf=fopen(fileresf,"w"))==NULL) {                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
     printf("Problem with forecast resultfile: %s\n", fileresf);                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);                }
   }              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
   printf("Computing forecasting: result on file '%s' \n", fileresf);            }
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);          }
         }/* end age */
   if (cptcoveff==0) ncodemax[cptcoveff]=1;      }/* end mob */
     }else return -1;
   if (mobilav!=0) {    return 0;
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  }/* End movingaverage */
     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);  /************** Forecasting ******************/
     }  prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
   }    /* proj1, year, month, day of starting projection
        agemin, agemax range of age
   stepsize=(int) (stepm+YEARM-1)/YEARM;       dateprev1 dateprev2 range of dates during which prevalence is computed
   if (stepm<=12) stepsize=1;       anproj2 year of en of projection (same day and month as proj1).
   if(estepm < stepm){    */
     printf ("Problem %d lower than %d\n",estepm, stepm);    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
   }    int *popage;
   else  hstepm=estepm;       double agec; /* generic age */
     double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
   hstepm=hstepm/stepm;     double *popeffectif,*popcount;
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and    double ***p3mat;
                                fractional in yp1 */    double ***mobaverage;
   anprojmean=yp;    char fileresf[FILENAMELENGTH];
   yp2=modf((yp1*12),&yp);  
   mprojmean=yp;    agelim=AGESUP;
   yp1=modf((yp2*30.5),&yp);    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
   jprojmean=yp;   
   if(jprojmean==0) jprojmean=1;    strcpy(fileresf,"f");
   if(mprojmean==0) jprojmean=1;    strcat(fileresf,fileres);
     if((ficresf=fopen(fileresf,"w"))==NULL) {
   i1=cptcoveff;      printf("Problem with forecast resultfile: %s\n", fileresf);
   if (cptcovn < 1){i1=1;}      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
       }
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);     printf("Computing forecasting: result on file '%s' \n", fileresf);
       fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
   fprintf(ficresf,"#****** Routine prevforecast **\n");  
     if (cptcoveff==0) ncodemax[cptcoveff]=1;
 /*            if (h==(int)(YEARM*yearp)){ */  
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){    if (mobilav!=0) {
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       k=k+1;      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
       fprintf(ficresf,"\n#******");        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
       for(j=1;j<=cptcoveff;j++) {        printf(" Error in movingaverage mobilav=%d\n",mobilav);
         fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      }
       }    }
       fprintf(ficresf,"******\n");  
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");    stepsize=(int) (stepm+YEARM-1)/YEARM;
       for(j=1; j<=nlstate+ndeath;j++){     if (stepm<=12) stepsize=1;
         for(i=1; i<=nlstate;i++)                  if(estepm < stepm){
           fprintf(ficresf," p%d%d",i,j);      printf ("Problem %d lower than %d\n",estepm, stepm);
         fprintf(ficresf," p.%d",j);    }
       }    else  hstepm=estepm;  
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {   
         fprintf(ficresf,"\n");    hstepm=hstepm/stepm;
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);       yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                                  fractional in yp1 */
         for (agec=fage; agec>=(ageminpar-1); agec--){     anprojmean=yp;
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);     yp2=modf((yp1*12),&yp);
           nhstepm = nhstepm/hstepm;     mprojmean=yp;
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    yp1=modf((yp2*30.5),&yp);
           oldm=oldms;savm=savms;    jprojmean=yp;
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);      if(jprojmean==0) jprojmean=1;
             if(mprojmean==0) jprojmean=1;
           for (h=0; h<=nhstepm; h++){  
             if (h*hstepm/YEARM*stepm ==yearp) {    i1=cptcoveff;
               fprintf(ficresf,"\n");    if (cptcovn < 1){i1=1;}
               for(j=1;j<=cptcoveff;j++)    
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);    fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);   
             }     fprintf(ficresf,"#****** Routine prevforecast **\n");
             for(j=1; j<=nlstate+ndeath;j++) {  
               ppij=0.;  /*            if (h==(int)(YEARM*yearp)){ */
               for(i=1; i<=nlstate;i++) {    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                 if (mobilav==1)       for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];        k=k+1;
                 else {        fprintf(ficresf,"\n#******");
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];        for(j=1;j<=cptcoveff;j++) {
                 }          fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                 if (h*hstepm/YEARM*stepm== yearp) {        }
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);        fprintf(ficresf,"******\n");
                 }        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
               } /* end i */        for(j=1; j<=nlstate+ndeath;j++){
               if (h*hstepm/YEARM*stepm==yearp) {          for(i=1; i<=nlstate;i++)              
                 fprintf(ficresf," %.3f", ppij);            fprintf(ficresf," p%d%d",i,j);
               }          fprintf(ficresf," p.%d",j);
             }/* end j */        }
           } /* end h */        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          fprintf(ficresf,"\n");
         } /* end agec */          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
       } /* end yearp */  
     } /* end cptcod */          for (agec=fage; agec>=(ageminpar-1); agec--){
   } /* end  cptcov */            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
                    nhstepm = nhstepm/hstepm;
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             oldm=oldms;savm=savms;
   fclose(ficresf);            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 }         
             for (h=0; h<=nhstepm; h++){
 /************** Forecasting *****not tested NB*************/              if (h*hstepm/YEARM*stepm ==yearp) {
 populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){                fprintf(ficresf,"\n");
                   for(j=1;j<=cptcoveff;j++)
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   int *popage;                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
   double calagedatem, agelim, kk1, kk2;              }
   double *popeffectif,*popcount;              for(j=1; j<=nlstate+ndeath;j++) {
   double ***p3mat,***tabpop,***tabpopprev;                ppij=0.;
   double ***mobaverage;                for(i=1; i<=nlstate;i++) {
   char filerespop[FILENAMELENGTH];                  if (mobilav==1)
                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                  else {
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
   agelim=AGESUP;                  }
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;                  if (h*hstepm/YEARM*stepm== yearp) {
                       fprintf(ficresf," %.3f", p3mat[i][j][h]);
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);                  }
                   } /* end i */
                   if (h*hstepm/YEARM*stepm==yearp) {
   strcpy(filerespop,"pop");                   fprintf(ficresf," %.3f", ppij);
   strcat(filerespop,fileres);                }
   if((ficrespop=fopen(filerespop,"w"))==NULL) {              }/* end j */
     printf("Problem with forecast resultfile: %s\n", filerespop);            } /* end h */
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   }          } /* end agec */
   printf("Computing forecasting: result on file '%s' \n", filerespop);        } /* end yearp */
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);      } /* end cptcod */
     } /* end  cptcov */
   if (cptcoveff==0) ncodemax[cptcoveff]=1;         
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if (mobilav!=0) {  
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    fclose(ficresf);
     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);  /************** 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){
   }   
     int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
   stepsize=(int) (stepm+YEARM-1)/YEARM;    int *popage;
   if (stepm<=12) stepsize=1;    double calagedatem, agelim, kk1, kk2;
       double *popeffectif,*popcount;
   agelim=AGESUP;    double ***p3mat,***tabpop,***tabpopprev;
       double ***mobaverage;
   hstepm=1;    char filerespop[FILENAMELENGTH];
   hstepm=hstepm/stepm;   
       tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if (popforecast==1) {    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     if((ficpop=fopen(popfile,"r"))==NULL) {    agelim=AGESUP;
       printf("Problem with population file : %s\n",popfile);exit(0);    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);   
     }     prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
     popage=ivector(0,AGESUP);   
     popeffectif=vector(0,AGESUP);   
     popcount=vector(0,AGESUP);    strcpy(filerespop,"pop");
         strcat(filerespop,fileres);
     i=1;       if((ficrespop=fopen(filerespop,"w"))==NULL) {
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;      printf("Problem with forecast resultfile: %s\n", filerespop);
          fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
     imx=i;    }
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];    printf("Computing forecasting: result on file '%s' \n", filerespop);
   }    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
   
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){    if (cptcoveff==0) ncodemax[cptcoveff]=1;
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){  
       k=k+1;    if (mobilav!=0) {
       fprintf(ficrespop,"\n#******");      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       for(j=1;j<=cptcoveff;j++) {      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
       }        printf(" Error in movingaverage mobilav=%d\n",mobilav);
       fprintf(ficrespop,"******\n");      }
       fprintf(ficrespop,"# Age");    }
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);  
       if (popforecast==1)  fprintf(ficrespop," [Population]");    stepsize=(int) (stepm+YEARM-1)/YEARM;
           if (stepm<=12) stepsize=1;
       for (cpt=0; cpt<=0;cpt++) {    
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);       agelim=AGESUP;
            
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){     hstepm=1;
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);     hstepm=hstepm/stepm;
           nhstepm = nhstepm/hstepm;    
               if (popforecast==1) {
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      if((ficpop=fopen(popfile,"r"))==NULL) {
           oldm=oldms;savm=savms;        printf("Problem with population file : %s\n",popfile);exit(0);
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);          fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
               }
           for (h=0; h<=nhstepm; h++){      popage=ivector(0,AGESUP);
             if (h==(int) (calagedatem+YEARM*cpt)) {      popeffectif=vector(0,AGESUP);
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);      popcount=vector(0,AGESUP);
             }      
             for(j=1; j<=nlstate+ndeath;j++) {      i=1;  
               kk1=0.;kk2=0;      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
               for(i=1; i<=nlstate;i++) {                   
                 if (mobilav==1)       imx=i;
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                 else {    }
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];  
                 }    for(cptcov=1,k=0;cptcov<=i2;cptcov++){
               }     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
               if (h==(int)(calagedatem+12*cpt)){        k=k+1;
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;        fprintf(ficrespop,"\n#******");
                   /*fprintf(ficrespop," %.3f", kk1);        for(j=1;j<=cptcoveff;j++) {
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
               }        }
             }        fprintf(ficrespop,"******\n");
             for(i=1; i<=nlstate;i++){        fprintf(ficrespop,"# Age");
               kk1=0.;        for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                 for(j=1; j<=nlstate;j++){        if (popforecast==1)  fprintf(ficrespop," [Population]");
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];        
                 }        for (cpt=0; cpt<=0;cpt++) {
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];          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--){
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);            nhstepm = nhstepm/hstepm;
           }           
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         }            oldm=oldms;savm=savms;
       }            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
           
   /******/            for (h=0; h<=nhstepm; h++){
               if (h==(int) (calagedatem+YEARM*cpt)) {
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {                 fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
         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--){               for(j=1; j<=nlstate+ndeath;j++) {
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);                 kk1=0.;kk2=0;
           nhstepm = nhstepm/hstepm;                 for(i=1; i<=nlstate;i++) {              
                             if (mobilav==1)
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                    kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
           oldm=oldms;savm=savms;                  else {
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);                      kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
           for (h=0; h<=nhstepm; h++){                  }
             if (h==(int) (calagedatem+YEARM*cpt)) {                }
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);                if (h==(int)(calagedatem+12*cpt)){
             }                   tabpop[(int)(agedeb)][j][cptcod]=kk1;
             for(j=1; j<=nlstate+ndeath;j++) {                    /*fprintf(ficrespop," %.3f", kk1);
               kk1=0.;kk2=0;                      if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
               for(i=1; i<=nlstate;i++) {                              }
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];                  }
               }              for(i=1; i<=nlstate;i++){
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                        kk1=0.;
             }                  for(j=1; j<=nlstate;j++){
           }                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                  }
         }                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
       }              }
    }   
   }              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
                  fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            }
             free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   if (popforecast==1) {          }
     free_ivector(popage,0,AGESUP);        }
     free_vector(popeffectif,0,AGESUP);   
     free_vector(popcount,0,AGESUP);    /******/
   }  
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   fclose(ficrespop);          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
 } /* End of popforecast */            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
             nhstepm = nhstepm/hstepm;
 int fileappend(FILE *fichier, char *optionfich)           
 {            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   if((fichier=fopen(optionfich,"a"))==NULL) {            oldm=oldms;savm=savms;
     printf("Problem with file: %s\n", optionfich);            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
     fprintf(ficlog,"Problem with file: %s\n", optionfich);            for (h=0; h<=nhstepm; h++){
     return (0);              if (h==(int) (calagedatem+YEARM*cpt)) {
   }                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   fflush(fichier);              }
   return (1);              for(j=1; j<=nlstate+ndeath;j++) {
 }                kk1=0.;kk2=0;
                 for(i=1; i<=nlstate;i++) {              
                   kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
 /**************** function prwizard **********************/                }
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
 {              }
             }
   /* Wizard to print covariance matrix template */            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           }
   char ca[32], cb[32], cc[32];        }
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;     }
   int numlinepar;    }
    
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");  
   for(i=1; i <=nlstate; i++){    if (popforecast==1) {
     jj=0;      free_ivector(popage,0,AGESUP);
     for(j=1; j <=nlstate+ndeath; j++){      free_vector(popeffectif,0,AGESUP);
       if(j==i) continue;      free_vector(popcount,0,AGESUP);
       jj++;    }
       /*ca[0]= k+'a'-1;ca[1]='\0';*/    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       printf("%1d%1d",i,j);    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       fprintf(ficparo,"%1d%1d",i,j);    fclose(ficrespop);
       for(k=1; k<=ncovmodel;k++){  } /* End of popforecast */
         /*        printf(" %lf",param[i][j][k]); */  
         /*        fprintf(ficparo," %lf",param[i][j][k]); */  int fileappend(FILE *fichier, char *optionfich)
         printf(" 0.");  {
         fprintf(ficparo," 0.");    if((fichier=fopen(optionfich,"a"))==NULL) {
       }      printf("Problem with file: %s\n", optionfich);
       printf("\n");      fprintf(ficlog,"Problem with file: %s\n", optionfich);
       fprintf(ficparo,"\n");      return (0);
     }    }
   }    fflush(fichier);
   printf("# Scales (for hessian or gradient estimation)\n");    return (1);
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");  }
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/   
   for(i=1; i <=nlstate; i++){  
     jj=0;  /**************** function prwizard **********************/
     for(j=1; j <=nlstate+ndeath; j++){  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
       if(j==i) continue;  {
       jj++;  
       fprintf(ficparo,"%1d%1d",i,j);    /* Wizard to print covariance matrix template */
       printf("%1d%1d",i,j);  
       fflush(stdout);    char ca[32], cb[32], cc[32];
       for(k=1; k<=ncovmodel;k++){    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
         /*      printf(" %le",delti3[i][j][k]); */    int numlinepar;
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */  
         printf(" 0.");    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         fprintf(ficparo," 0.");    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       }    for(i=1; i <=nlstate; i++){
       numlinepar++;      jj=0;
       printf("\n");      for(j=1; j <=nlstate+ndeath; j++){
       fprintf(ficparo,"\n");        if(j==i) continue;
     }        jj++;
   }        /*ca[0]= k+'a'-1;ca[1]='\0';*/
   printf("# Covariance matrix\n");        printf("%1d%1d",i,j);
 /* # 121 Var(a12)\n\ */        fprintf(ficparo,"%1d%1d",i,j);
 /* # 122 Cov(b12,a12) Var(b12)\n\ */        for(k=1; k<=ncovmodel;k++){
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */          /*        printf(" %lf",param[i][j][k]); */
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */          /*        fprintf(ficparo," %lf",param[i][j][k]); */
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */          printf(" 0.");
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */          fprintf(ficparo," 0.");
 /* # 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("\n");
   fflush(stdout);        fprintf(ficparo,"\n");
   fprintf(ficparo,"# Covariance matrix\n");      }
   /* # 121 Var(a12)\n\ */    }
   /* # 122 Cov(b12,a12) Var(b12)\n\ */    printf("# Scales (for hessian or gradient estimation)\n");
   /* #   ...\n\ */    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
       for(i=1; i <=nlstate; i++){
   for(itimes=1;itimes<=2;itimes++){      jj=0;
     jj=0;      for(j=1; j <=nlstate+ndeath; j++){
     for(i=1; i <=nlstate; i++){        if(j==i) continue;
       for(j=1; j <=nlstate+ndeath; j++){        jj++;
         if(j==i) continue;        fprintf(ficparo,"%1d%1d",i,j);
         for(k=1; k<=ncovmodel;k++){        printf("%1d%1d",i,j);
           jj++;        fflush(stdout);
           ca[0]= k+'a'-1;ca[1]='\0';        for(k=1; k<=ncovmodel;k++){
           if(itimes==1){          /*      printf(" %le",delti3[i][j][k]); */
             printf("#%1d%1d%d",i,j,k);          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
             fprintf(ficparo,"#%1d%1d%d",i,j,k);          printf(" 0.");
           }else{          fprintf(ficparo," 0.");
             printf("%1d%1d%d",i,j,k);        }
             fprintf(ficparo,"%1d%1d%d",i,j,k);        numlinepar++;
             /*  printf(" %.5le",matcov[i][j]); */        printf("\n");
           }        fprintf(ficparo,"\n");
           ll=0;      }
           for(li=1;li <=nlstate; li++){    }
             for(lj=1;lj <=nlstate+ndeath; lj++){    printf("# Covariance matrix\n");
               if(lj==li) continue;  /* # 121 Var(a12)\n\ */
               for(lk=1;lk<=ncovmodel;lk++){  /* # 122 Cov(b12,a12) Var(b12)\n\ */
                 ll++;  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                 if(ll<=jj){  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   cb[0]= lk +'a'-1;cb[1]='\0';  /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   if(ll<jj){  /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                     if(itimes==1){  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);    fflush(stdout);
                     }else{    fprintf(ficparo,"# Covariance matrix\n");
                       printf(" 0.");    /* # 121 Var(a12)\n\ */
                       fprintf(ficparo," 0.");    /* # 122 Cov(b12,a12) Var(b12)\n\ */
                     }    /* #   ...\n\ */
                   }else{    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                     if(itimes==1){   
                       printf(" Var(%s%1d%1d)",ca,i,j);    for(itimes=1;itimes<=2;itimes++){
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);      jj=0;
                     }else{      for(i=1; i <=nlstate; i++){
                       printf(" 0.");        for(j=1; j <=nlstate+ndeath; j++){
                       fprintf(ficparo," 0.");          if(j==i) continue;
                     }          for(k=1; k<=ncovmodel;k++){
                   }            jj++;
                 }            ca[0]= k+'a'-1;ca[1]='\0';
               } /* end lk */            if(itimes==1){
             } /* end lj */              printf("#%1d%1d%d",i,j,k);
           } /* end li */              fprintf(ficparo,"#%1d%1d%d",i,j,k);
           printf("\n");            }else{
           fprintf(ficparo,"\n");              printf("%1d%1d%d",i,j,k);
           numlinepar++;              fprintf(ficparo,"%1d%1d%d",i,j,k);
         } /* end k*/              /*  printf(" %.5le",matcov[i][j]); */
       } /*end j */            }
     } /* end i */            ll=0;
   } /* end itimes */            for(li=1;li <=nlstate; li++){
               for(lj=1;lj <=nlstate+ndeath; lj++){
 } /* end of prwizard */                if(lj==li) continue;
 /******************* Gompertz Likelihood ******************************/                for(lk=1;lk<=ncovmodel;lk++){
 double gompertz(double x[])                  ll++;
 {                   if(ll<=jj){
   double A,B,L=0.0,sump=0.,num=0.;                    cb[0]= lk +'a'-1;cb[1]='\0';
   int i,n=0; /* n is the size of the sample */                    if(ll<jj){
                       if(itimes==1){
   for (i=0;i<=imx-1 ; i++) {                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     sump=sump+weight[i];                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     /*    sump=sump+1;*/                      }else{
     num=num+1;                        printf(" 0.");
   }                        fprintf(ficparo," 0.");
                        }
                      }else{
   /* for (i=0; i<=imx; i++)                       if(itimes==1){
      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(" Var(%s%1d%1d)",ca,i,j);
                         fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
   for (i=1;i<=imx ; i++)                      }else{
     {                        printf(" 0.");
       if (cens[i] == 1 && wav[i]>1)                        fprintf(ficparo," 0.");
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));                      }
                           }
       if (cens[i] == 0 && wav[i]>1)                  }
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))                } /* end lk */
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);                } /* end lj */
                   } /* end li */
       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */            printf("\n");
       if (wav[i] > 1 ) { /* ??? */            fprintf(ficparo,"\n");
         L=L+A*weight[i];            numlinepar++;
         /*      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]);*/          } /* end k*/
       }        } /*end j */
     }      } /* end i */
     } /* end itimes */
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/  
    } /* end of prwizard */
   return -2*L*num/sump;  /******************* Gompertz Likelihood ******************************/
 }  double gompertz(double x[])
   {
 /******************* Printing html file ***********/    double A,B,L=0.0,sump=0.,num=0.;
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \    int i,n=0; /* n is the size of the sample */
                   int lastpass, int stepm, int weightopt, char model[],\  
                   int imx,  double p[],double **matcov,double agemortsup){    for (i=0;i<=imx-1 ; i++) {
   int i,k;      sump=sump+weight[i];
       /*    sump=sump+1;*/
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");      num=num+1;
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);    }
   for (i=1;i<=2;i++)    
     fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));   
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");    /* for (i=0; i<=imx; i++)
   fprintf(fichtm,"</ul>");       if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
   
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");    for (i=1;i<=imx ; i++)
       {
  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 (cens[i] == 1 && wav[i]>1)
           A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
  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]);        if (cens[i] == 0 && wav[i]>1)
           A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                 +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
   fflush(fichtm);       
 }        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
         if (wav[i] > 1 ) { /* ??? */
 /******************* Gnuplot file **************/          L=L+A*weight[i];
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){          /*      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]);*/
         }
   char dirfileres[132],optfileres[132];      }
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;  
   int ng;   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
    
     return -2*L*num/sump;
   /*#ifdef windows */  }
   fprintf(ficgp,"cd \"%s\" \n",pathc);  
     /*#endif */  /******************* Printing html file ***********/
   void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                     int lastpass, int stepm, int weightopt, char model[],\
   strcpy(dirfileres,optionfilefiname);                    int imx,  double p[],double **matcov,double agemortsup){
   strcpy(optfileres,"vpl");    int i,k;
   fprintf(ficgp,"set out \"graphmort.png\"\n ");   
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");     fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
   fprintf(ficgp, "set ter png small\n set log y\n");     fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
   fprintf(ficgp, "set size 0.65,0.65\n");    for (i=1;i<=2;i++)
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);      fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
     fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 }     fprintf(fichtm,"</ul>");
   
   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>");
   
 /***********************************************/   for (k=agegomp;k<(agemortsup-2);k++)
 /**************** Main Program *****************/     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]);
 /***********************************************/  
    
 int main(int argc, char *argv[])    fflush(fichtm);
 {  }
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);  
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;  /******************* Gnuplot file **************/
   int linei, month, year,iout;  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   int jj, ll, li, lj, lk, imk;  
   int numlinepar=0; /* Current linenumber of parameter file */    char dirfileres[132],optfileres[132];
   int itimes;    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
   int NDIM=2;    int ng;
   
   char ca[32], cb[32], cc[32];  
   char dummy[]="                         ";    /*#ifdef windows */
   /*  FILE *fichtm; *//* Html File */    fprintf(ficgp,"cd \"%s\" \n",pathc);
   /* FILE *ficgp;*/ /*Gnuplot File */      /*#endif */
   struct stat info;  
   double agedeb, agefin,hf;  
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;    strcpy(dirfileres,optionfilefiname);
     strcpy(optfileres,"vpl");
   double fret;    fprintf(ficgp,"set out \"graphmort.png\"\n ");
   double **xi,tmp,delta;    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");
   double dum; /* Dummy variable */    fprintf(ficgp, "set size 0.65,0.65\n");
   double ***p3mat;    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
   double ***mobaverage;  
   int *indx;  }
   char line[MAXLINE], linepar[MAXLINE];  
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];  
   char pathr[MAXLINE], pathimach[MAXLINE];   
   char **bp, *tok, *val; /* pathtot */  
   int firstobs=1, lastobs=10;  
   int sdeb, sfin; /* Status at beginning and end */  /***********************************************/
   int c,  h , cpt,l;  /**************** Main Program *****************/
   int ju,jl, mi;  /***********************************************/
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;  
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;   int main(int argc, char *argv[])
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */  {
   int mobilav=0,popforecast=0;    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
   int hstepm, nhstepm;    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
   int agemortsup;    int linei, month, year,iout;
   float  sumlpop=0.;    int jj, ll, li, lj, lk, imk;
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;    int numlinepar=0; /* Current linenumber of parameter file */
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;    int itimes;
     int NDIM=2;
   double bage, fage, age, agelim, agebase;  
   double ftolpl=FTOL;    char ca[32], cb[32], cc[32];
   double **prlim;    char dummy[]="                         ";
   double *severity;    /*  FILE *fichtm; *//* Html File */
   double ***param; /* Matrix of parameters */    /* FILE *ficgp;*/ /*Gnuplot File */
   double  *p;    struct stat info;
   double **matcov; /* Matrix of covariance */    double agedeb, agefin,hf;
   double ***delti3; /* Scale */    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
   double *delti; /* Scale */  
   double ***eij, ***vareij;    double fret;
   double **varpl; /* Variances of prevalence limits by age */    double **xi,tmp,delta;
   double *epj, vepp;  
   double kk1, kk2;    double dum; /* Dummy variable */
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;    double ***p3mat;
   double **ximort;    double ***mobaverage;
   char *alph[]={"a","a","b","c","d","e"}, str[4];    int *indx;
   int *dcwave;    char line[MAXLINE], linepar[MAXLINE];
     char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
   char z[1]="c", occ;    char pathr[MAXLINE], pathimach[MAXLINE];
     char **bp, *tok, *val; /* pathtot */
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];    int firstobs=1, lastobs=10;
   char  *strt, strtend[80];    int sdeb, sfin; /* Status at beginning and end */
   char *stratrunc;    int c,  h , cpt,l;
   int lstra;    int ju,jl, mi;
     int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
   long total_usecs;    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
      int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 /*   setlocale (LC_ALL, ""); */    int mobilav=0,popforecast=0;
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */    int hstepm, nhstepm;
 /*   textdomain (PACKAGE); */    int agemortsup;
 /*   setlocale (LC_CTYPE, ""); */    float  sumlpop=0.;
 /*   setlocale (LC_MESSAGES, ""); */    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
     double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */  
   (void) gettimeofday(&start_time,&tzp);    double bage, fage, age, agelim, agebase;
   curr_time=start_time;    double ftolpl=FTOL;
   tm = *localtime(&start_time.tv_sec);    double **prlim;
   tmg = *gmtime(&start_time.tv_sec);    double *severity;
   strcpy(strstart,asctime(&tm));    double ***param; /* Matrix of parameters */
     double  *p;
 /*  printf("Localtime (at start)=%s",strstart); */    double **matcov; /* Matrix of covariance */
 /*  tp.tv_sec = tp.tv_sec +86400; */    double ***delti3; /* Scale */
 /*  tm = *localtime(&start_time.tv_sec); */    double *delti; /* Scale */
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */    double ***eij, ***vareij;
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */    double **varpl; /* Variances of prevalence limits by age */
 /*   tmg.tm_hour=tmg.tm_hour + 1; */    double *epj, vepp;
 /*   tp.tv_sec = mktime(&tmg); */    double kk1, kk2;
 /*   strt=asctime(&tmg); */    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 /*   printf("Time(after) =%s",strstart);  */    double **ximort;
 /*  (void) time (&time_value);    char *alph[]={"a","a","b","c","d","e"}, str[4];
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);    int *dcwave;
 *  tm = *localtime(&time_value);  
 *  strstart=asctime(&tm);    char z[1]="c", occ;
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);   
 */    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
     char  *strt, strtend[80];
   nberr=0; /* Number of errors and warnings */    char *stratrunc;
   nbwarn=0;    int lstra;
   getcwd(pathcd, size);  
     long total_usecs;
   printf("\n%s\n%s",version,fullversion);   
   if(argc <=1){  /*   setlocale (LC_ALL, ""); */
     printf("\nEnter the parameter file name: ");  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
     fgets(pathr,FILENAMELENGTH,stdin);  /*   textdomain (PACKAGE); */
     i=strlen(pathr);  /*   setlocale (LC_CTYPE, ""); */
     if(pathr[i-1]=='\n')  /*   setlocale (LC_MESSAGES, ""); */
       pathr[i-1]='\0';  
    for (tok = pathr; tok != NULL; ){    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
       printf("Pathr |%s|\n",pathr);    (void) gettimeofday(&start_time,&tzp);
       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');    curr_time=start_time;
       printf("val= |%s| pathr=%s\n",val,pathr);    tm = *localtime(&start_time.tv_sec);
       strcpy (pathtot, val);    tmg = *gmtime(&start_time.tv_sec);
       if(pathr[0] == '\0') break; /* Dirty */    strcpy(strstart,asctime(&tm));
     }  
   }  /*  printf("Localtime (at start)=%s",strstart); */
   else{  /*  tp.tv_sec = tp.tv_sec +86400; */
     strcpy(pathtot,argv[1]);  /*  tm = *localtime(&start_time.tv_sec); */
   }  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
   /*cygwin_split_path(pathtot,path,optionfile);  /*   tmg.tm_hour=tmg.tm_hour + 1; */
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/  /*   tp.tv_sec = mktime(&tmg); */
   /* cutv(path,optionfile,pathtot,'\\');*/  /*   strt=asctime(&tmg); */
   /*   printf("Time(after) =%s",strstart);  */
   /* Split argv[0], imach program to get pathimach */  /*  (void) time (&time_value);
   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);  *  tm = *localtime(&time_value);
   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);  *  strstart=asctime(&tm);
  /*   strcpy(pathimach,argv[0]); */  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */  */
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);  
   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);    nberr=0; /* Number of errors and warnings */
   chdir(path); /* Can be a relative path */    nbwarn=0;
   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */    getcwd(pathcd, size);
     printf("Current directory %s!\n",pathcd);  
   strcpy(command,"mkdir ");    printf("\n%s\n%s",version,fullversion);
   strcat(command,optionfilefiname);    if(argc <=1){
   if((outcmd=system(command)) != 0){      printf("\nEnter the parameter file name: ");
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);      fgets(pathr,FILENAMELENGTH,stdin);
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */      i=strlen(pathr);
     /* fclose(ficlog); */      if(pathr[i-1]=='\n')
 /*     exit(1); */        pathr[i-1]='\0';
   }     for (tok = pathr; tok != NULL; ){
 /*   if((imk=mkdir(optionfilefiname))<0){ */        printf("Pathr |%s|\n",pathr);
 /*     perror("mkdir"); */        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 /*   } */        printf("val= |%s| pathr=%s\n",val,pathr);
         strcpy (pathtot, val);
   /*-------- arguments in the command line --------*/        if(pathr[0] == '\0') break; /* Dirty */
       }
   /* Log file */    }
   strcat(filelog, optionfilefiname);    else{
   strcat(filelog,".log");    /* */      strcpy(pathtot,argv[1]);
   if((ficlog=fopen(filelog,"w"))==NULL)    {    }
     printf("Problem with logfile %s\n",filelog);    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
     goto end;    /*cygwin_split_path(pathtot,path,optionfile);
   }      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
   fprintf(ficlog,"Log filename:%s\n",filelog);    /* cutv(path,optionfile,pathtot,'\\');*/
   fprintf(ficlog,"\n%s\n%s",version,fullversion);  
   fprintf(ficlog,"\nEnter the parameter file name: \n");    /* Split argv[0], imach program to get pathimach */
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
  path=%s \n\    split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
  optionfile=%s\n\    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
  optionfilext=%s\n\   /*   strcpy(pathimach,argv[0]); */
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
     split(pathtot,path,optionfile,optionfilext,optionfilefiname);
   printf("Local time (at start):%s",strstart);    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
   fprintf(ficlog,"Local time (at start): %s",strstart);    chdir(path); /* Can be a relative path */
   fflush(ficlog);    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 /*   (void) gettimeofday(&curr_time,&tzp); */      printf("Current directory %s!\n",pathcd);
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */    strcpy(command,"mkdir ");
     strcat(command,optionfilefiname);
   /* */    if((outcmd=system(command)) != 0){
   strcpy(fileres,"r");      printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
   strcat(fileres, optionfilefiname);      /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
   strcat(fileres,".txt");    /* Other files have txt extension */      /* fclose(ficlog); */
   /*     exit(1); */
   /*---------arguments file --------*/    }
   /*   if((imk=mkdir(optionfilefiname))<0){ */
   if((ficpar=fopen(optionfile,"r"))==NULL)    {  /*     perror("mkdir"); */
     printf("Problem with optionfile %s\n",optionfile);  /*   } */
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);  
     fflush(ficlog);    /*-------- arguments in the command line --------*/
     goto end;  
   }    /* Log file */
     strcat(filelog, optionfilefiname);
     strcat(filelog,".log");    /* */
     if((ficlog=fopen(filelog,"w"))==NULL)    {
   strcpy(filereso,"o");      printf("Problem with logfile %s\n",filelog);
   strcat(filereso,fileres);      goto end;
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */    }
     printf("Problem with Output resultfile: %s\n", filereso);    fprintf(ficlog,"Log filename:%s\n",filelog);
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);    fprintf(ficlog,"\n%s\n%s",version,fullversion);
     fflush(ficlog);    fprintf(ficlog,"\nEnter the parameter file name: \n");
     goto end;    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
   }   path=%s \n\
    optionfile=%s\n\
   /* Reads comments: lines beginning with '#' */   optionfilext=%s\n\
   numlinepar=0;   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
   while((c=getc(ficpar))=='#' && c!= EOF){  
     ungetc(c,ficpar);    printf("Local time (at start):%s",strstart);
     fgets(line, MAXLINE, ficpar);    fprintf(ficlog,"Local time (at start): %s",strstart);
     numlinepar++;    fflush(ficlog);
     puts(line);  /*   (void) gettimeofday(&curr_time,&tzp); */
     fputs(line,ficparo);  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
     fputs(line,ficlog);  
   }    /* */
   ungetc(c,ficpar);    strcpy(fileres,"r");
     strcat(fileres, optionfilefiname);
   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);    strcat(fileres,".txt");    /* Other files have txt extension */
   numlinepar++;  
   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);    /*---------arguments file --------*/
   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);    if((ficpar=fopen(optionfile,"r"))==NULL)    {
   fflush(ficlog);      printf("Problem with optionfile %s\n",optionfile);
   while((c=getc(ficpar))=='#' && c!= EOF){      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
     ungetc(c,ficpar);      fflush(ficlog);
     fgets(line, MAXLINE, ficpar);      goto end;
     numlinepar++;    }
     puts(line);  
     fputs(line,ficparo);  
     fputs(line,ficlog);  
   }    strcpy(filereso,"o");
   ungetc(c,ficpar);    strcat(filereso,fileres);
     if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
          printf("Problem with Output resultfile: %s\n", filereso);
   covar=matrix(0,NCOVMAX,1,n);       fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/      fflush(ficlog);
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;      goto end;
     }
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */  
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */    /* Reads comments: lines beginning with '#' */
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/    numlinepar=0;
     while((c=getc(ficpar))=='#' && c!= EOF){
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      ungetc(c,ficpar);
   delti=delti3[1][1];      fgets(line, MAXLINE, ficpar);
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/      numlinepar++;
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */      puts(line);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);      fputs(line,ficparo);
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);      fputs(line,ficlog);
     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);     ungetc(c,ficpar);
     fclose (ficparo);  
     fclose (ficlog);    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);
     exit(0);    numlinepar++;
   }    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);
   else if(mle==-3) {    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);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);    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);
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    fflush(ficlog);
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    while((c=getc(ficpar))=='#' && c!= EOF){
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      ungetc(c,ficpar);
     matcov=matrix(1,npar,1,npar);      fgets(line, MAXLINE, ficpar);
   }      numlinepar++;
   else{      puts(line);
     /* Read guess parameters */      fputs(line,ficparo);
     /* Reads comments: lines beginning with '#' */      fputs(line,ficlog);
     while((c=getc(ficpar))=='#' && c!= EOF){    }
       ungetc(c,ficpar);    ungetc(c,ficpar);
       fgets(line, MAXLINE, ficpar);  
       numlinepar++;     
       puts(line);    covar=matrix(0,NCOVMAX,1,n);
       fputs(line,ficparo);    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
       fputs(line,ficlog);    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
     }  
     ungetc(c,ficpar);    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
         nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
     for(i=1; i <=nlstate; i++){  
       j=0;    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
       for(jj=1; jj <=nlstate+ndeath; jj++){    delti=delti3[1][1];
         if(jj==i) continue;    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
         j++;    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
         fscanf(ficpar,"%1d%1d",&i1,&j1);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
         if ((i1 != i) && (j1 != j)){      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           exit(1);      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
         }      fclose (ficparo);
         fprintf(ficparo,"%1d%1d",i1,j1);      fclose (ficlog);
         if(mle==1)      goto end;
           printf("%1d%1d",i,j);      exit(0);
         fprintf(ficlog,"%1d%1d",i,j);    }
         for(k=1; k<=ncovmodel;k++){    else if(mle==-3) {
           fscanf(ficpar," %lf",&param[i][j][k]);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
           if(mle==1){      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
             printf(" %lf",param[i][j][k]);      fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
             fprintf(ficlog," %lf",param[i][j][k]);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
           }      matcov=matrix(1,npar,1,npar);
           else    }
             fprintf(ficlog," %lf",param[i][j][k]);    else{
           fprintf(ficparo," %lf",param[i][j][k]);      /* Read guess parameters */
         }      /* Reads comments: lines beginning with '#' */
         fscanf(ficpar,"\n");      while((c=getc(ficpar))=='#' && c!= EOF){
         numlinepar++;        ungetc(c,ficpar);
         if(mle==1)        fgets(line, MAXLINE, ficpar);
           printf("\n");        numlinepar++;
         fprintf(ficlog,"\n");        puts(line);
         fprintf(ficparo,"\n");        fputs(line,ficparo);
       }        fputs(line,ficlog);
     }        }
     fflush(ficlog);      ungetc(c,ficpar);
      
     p=param[1][1];      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
           for(i=1; i <=nlstate; i++){
     /* Reads comments: lines beginning with '#' */        j=0;
     while((c=getc(ficpar))=='#' && c!= EOF){        for(jj=1; jj <=nlstate+ndeath; jj++){
       ungetc(c,ficpar);          if(jj==i) continue;
       fgets(line, MAXLINE, ficpar);          j++;
       numlinepar++;          fscanf(ficpar,"%1d%1d",&i1,&j1);
       puts(line);          if ((i1 != i) && (j1 != j)){
       fputs(line,ficparo);            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
       fputs(line,ficlog);  It might be a problem of design; if ncovcol and the model are correct\n \
     }  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
     ungetc(c,ficpar);            exit(1);
           }
     for(i=1; i <=nlstate; i++){          fprintf(ficparo,"%1d%1d",i1,j1);
       for(j=1; j <=nlstate+ndeath-1; j++){          if(mle==1)
         fscanf(ficpar,"%1d%1d",&i1,&j1);            printf("%1d%1d",i,j);
         if ((i1-i)*(j1-j)!=0){          fprintf(ficlog,"%1d%1d",i,j);
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);          for(k=1; k<=ncovmodel;k++){
           exit(1);            fscanf(ficpar," %lf",&param[i][j][k]);
         }            if(mle==1){
         printf("%1d%1d",i,j);              printf(" %lf",param[i][j][k]);
         fprintf(ficparo,"%1d%1d",i1,j1);              fprintf(ficlog," %lf",param[i][j][k]);
         fprintf(ficlog,"%1d%1d",i1,j1);            }
         for(k=1; k<=ncovmodel;k++){            else
           fscanf(ficpar,"%le",&delti3[i][j][k]);              fprintf(ficlog," %lf",param[i][j][k]);
           printf(" %le",delti3[i][j][k]);            fprintf(ficparo," %lf",param[i][j][k]);
           fprintf(ficparo," %le",delti3[i][j][k]);          }
           fprintf(ficlog," %le",delti3[i][j][k]);          fscanf(ficpar,"\n");
         }          numlinepar++;
         fscanf(ficpar,"\n");          if(mle==1)
         numlinepar++;            printf("\n");
         printf("\n");          fprintf(ficlog,"\n");
         fprintf(ficparo,"\n");          fprintf(ficparo,"\n");
         fprintf(ficlog,"\n");        }
       }      }  
     }      fflush(ficlog);
     fflush(ficlog);  
       p=param[1][1];
     delti=delti3[1][1];     
       /* Reads comments: lines beginning with '#' */
       while((c=getc(ficpar))=='#' && c!= EOF){
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */        ungetc(c,ficpar);
           fgets(line, MAXLINE, ficpar);
     /* Reads comments: lines beginning with '#' */        numlinepar++;
     while((c=getc(ficpar))=='#' && c!= EOF){        puts(line);
       ungetc(c,ficpar);        fputs(line,ficparo);
       fgets(line, MAXLINE, ficpar);        fputs(line,ficlog);
       numlinepar++;      }
       puts(line);      ungetc(c,ficpar);
       fputs(line,ficparo);  
       fputs(line,ficlog);      for(i=1; i <=nlstate; i++){
     }        for(j=1; j <=nlstate+ndeath-1; j++){
     ungetc(c,ficpar);          fscanf(ficpar,"%1d%1d",&i1,&j1);
             if ((i1-i)*(j1-j)!=0){
     matcov=matrix(1,npar,1,npar);            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
     for(i=1; i <=npar; i++){            exit(1);
       fscanf(ficpar,"%s",&str);          }
       if(mle==1)          printf("%1d%1d",i,j);
         printf("%s",str);          fprintf(ficparo,"%1d%1d",i1,j1);
       fprintf(ficlog,"%s",str);          fprintf(ficlog,"%1d%1d",i1,j1);
       fprintf(ficparo,"%s",str);          for(k=1; k<=ncovmodel;k++){
       for(j=1; j <=i; j++){            fscanf(ficpar,"%le",&delti3[i][j][k]);
         fscanf(ficpar," %le",&matcov[i][j]);            printf(" %le",delti3[i][j][k]);
         if(mle==1){            fprintf(ficparo," %le",delti3[i][j][k]);
           printf(" %.5le",matcov[i][j]);            fprintf(ficlog," %le",delti3[i][j][k]);
         }          }
         fprintf(ficlog," %.5le",matcov[i][j]);          fscanf(ficpar,"\n");
         fprintf(ficparo," %.5le",matcov[i][j]);          numlinepar++;
       }          printf("\n");
       fscanf(ficpar,"\n");          fprintf(ficparo,"\n");
       numlinepar++;          fprintf(ficlog,"\n");
       if(mle==1)        }
         printf("\n");      }
       fprintf(ficlog,"\n");      fflush(ficlog);
       fprintf(ficparo,"\n");  
     }      delti=delti3[1][1];
     for(i=1; i <=npar; i++)  
       for(j=i+1;j<=npar;j++)  
         matcov[i][j]=matcov[j][i];      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
        
     if(mle==1)      /* Reads comments: lines beginning with '#' */
       printf("\n");      while((c=getc(ficpar))=='#' && c!= EOF){
     fprintf(ficlog,"\n");        ungetc(c,ficpar);
             fgets(line, MAXLINE, ficpar);
     fflush(ficlog);        numlinepar++;
             puts(line);
     /*-------- Rewriting parameter file ----------*/        fputs(line,ficparo);
     strcpy(rfileres,"r");    /* "Rparameterfile */        fputs(line,ficlog);
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/      }
     strcat(rfileres,".");    /* */      ungetc(c,ficpar);
     strcat(rfileres,optionfilext);    /* Other files have txt extension */   
     if((ficres =fopen(rfileres,"w"))==NULL) {      matcov=matrix(1,npar,1,npar);
       printf("Problem writing new parameter file: %s\n", fileres);goto end;      for(i=1; i <=npar; i++){
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;        fscanf(ficpar,"%s",&str);
     }        if(mle==1)
     fprintf(ficres,"#%s\n",version);          printf("%s",str);
   }    /* End of mle != -3 */        fprintf(ficlog,"%s",str);
         fprintf(ficparo,"%s",str);
   /*-------- data file ----------*/        for(j=1; j <=i; j++){
   if((fic=fopen(datafile,"r"))==NULL)    {          fscanf(ficpar," %le",&matcov[i][j]);
     printf("Problem while opening datafile: %s\n", datafile);goto end;          if(mle==1){
     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;            printf(" %.5le",matcov[i][j]);
   }          }
           fprintf(ficlog," %.5le",matcov[i][j]);
   n= lastobs;          fprintf(ficparo," %.5le",matcov[i][j]);
   severity = vector(1,maxwav);        }
   outcome=imatrix(1,maxwav+1,1,n);        fscanf(ficpar,"\n");
   num=lvector(1,n);        numlinepar++;
   moisnais=vector(1,n);        if(mle==1)
   annais=vector(1,n);          printf("\n");
   moisdc=vector(1,n);        fprintf(ficlog,"\n");
   andc=vector(1,n);        fprintf(ficparo,"\n");
   agedc=vector(1,n);      }
   cod=ivector(1,n);      for(i=1; i <=npar; i++)
   weight=vector(1,n);        for(j=i+1;j<=npar;j++)
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */          matcov[i][j]=matcov[j][i];
   mint=matrix(1,maxwav,1,n);     
   anint=matrix(1,maxwav,1,n);      if(mle==1)
   s=imatrix(1,maxwav+1,1,n);        printf("\n");
   tab=ivector(1,NCOVMAX);      fprintf(ficlog,"\n");
   ncodemax=ivector(1,8);     
       fflush(ficlog);
   i=1;     
   linei=0;      /*-------- Rewriting parameter file ----------*/
   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {      strcpy(rfileres,"r");    /* "Rparameterfile */
     linei=linei+1;      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
     for(j=strlen(line); j>=0;j--){  /* Untabifies line */      strcat(rfileres,".");    /* */
       if(line[j] == '\t')      strcat(rfileres,optionfilext);    /* Other files have txt extension */
         line[j] = ' ';      if((ficres =fopen(rfileres,"w"))==NULL) {
     }        printf("Problem writing new parameter file: %s\n", fileres);goto end;
     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
       ;      }
     };      fprintf(ficres,"#%s\n",version);
     line[j+1]=0;  /* Trims blanks at end of line */    }    /* End of mle != -3 */
     if(line[0]=='#'){  
       fprintf(ficlog,"Comment line\n%s\n",line);    /*-------- data file ----------*/
       printf("Comment line\n%s\n",line);    if((fic=fopen(datafile,"r"))==NULL)    {
       continue;      printf("Problem while opening datafile: %s\n", datafile);goto end;
     }      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
     }
     for (j=maxwav;j>=1;j--){  
       cutv(stra, strb,line,' ');     n= lastobs;
       errno=0;    severity = vector(1,maxwav);
       lval=strtol(strb,&endptr,10);     outcome=imatrix(1,maxwav+1,1,n);
       /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/    num=lvector(1,n);
       if( strb[0]=='\0' || (*endptr != '\0')){    moisnais=vector(1,n);
         printf("Error reading data around '%d' at line number %d %s for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);    annais=vector(1,n);
         exit(1);    moisdc=vector(1,n);
       }    andc=vector(1,n);
       s[j][i]=lval;    agedc=vector(1,n);
           cod=ivector(1,n);
       strcpy(line,stra);    weight=vector(1,n);
       cutv(stra, strb,line,' ');    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){    mint=matrix(1,maxwav,1,n);
       }    anint=matrix(1,maxwav,1,n);
       else  if(iout=sscanf(strb,"%s.") != 0){    s=imatrix(1,maxwav+1,1,n);
         month=99;    tab=ivector(1,NCOVMAX);
         year=9999;    ncodemax=ivector(1,8);
       }else{  
         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);    i=1;
         exit(1);    linei=0;
       }    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
       anint[j][i]= (double) year;       linei=linei+1;
       mint[j][i]= (double)month;       for(j=strlen(line); j>=0;j--){  /* Untabifies line */
       strcpy(line,stra);        if(line[j] == '\t')
     } /* ENd Waves */          line[j] = ' ';
           }
     cutv(stra, strb,line,' ');       for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){        ;
     }      };
     else  if(iout=sscanf(strb,"%s.",dummy) != 0){      line[j+1]=0;  /* Trims blanks at end of line */
       month=99;      if(line[0]=='#'){
       year=9999;        fprintf(ficlog,"Comment line\n%s\n",line);
     }else{        printf("Comment line\n%s\n",line);
       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);        continue;
       exit(1);      }
     }  
     andc[i]=(double) year;       for (j=maxwav;j>=1;j--){
     moisdc[i]=(double) month;         cutv(stra, strb,line,' ');
     strcpy(line,stra);        errno=0;
             lval=strtol(strb,&endptr,10);
     cutv(stra, strb,line,' ');         /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){        if( strb[0]=='\0' || (*endptr != '\0')){
     }          printf("Error reading data around '%d' at line number %d %s for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);
     else  if(iout=sscanf(strb,"%s.") != 0){          exit(1);
       month=99;        }
       year=9999;        s[j][i]=lval;
     }else{       
       printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line,j);        strcpy(line,stra);
       exit(1);        cutv(stra, strb,line,' ');
     }        if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     annais[i]=(double)(year);        }
     moisnais[i]=(double)(month);         else  if(iout=sscanf(strb,"%s.") != 0){
     strcpy(line,stra);          month=99;
               year=9999;
     cutv(stra, strb,line,' ');         }else{
     errno=0;          printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
     lval=strtol(strb,&endptr,10);           exit(1);
     if( strb[0]=='\0' || (*endptr != '\0')){        }
       printf("Error reading data around '%d' at line number %ld %s for individual %d\nShould be a weight.  Exiting.\n",lval, i,line,linei);        anint[j][i]= (double) year;
       exit(1);        mint[j][i]= (double)month;
     }        strcpy(line,stra);
     weight[i]=(double)(lval);       } /* ENd Waves */
     strcpy(line,stra);     
           cutv(stra, strb,line,' ');
     for (j=ncovcol;j>=1;j--){      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
       cutv(stra, strb,line,' ');       }
       errno=0;      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
       lval=strtol(strb,&endptr,10);         month=99;
       if( strb[0]=='\0' || (*endptr != '\0')){        year=9999;
         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);      }else{
         exit(1);        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);
       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);      andc[i]=(double) year;
         exit(1);      moisdc[i]=(double) month;
       }      strcpy(line,stra);
       covar[j][i]=(double)(lval);     
       strcpy(line,stra);      cutv(stra, strb,line,' ');
     }       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     lstra=strlen(stra);      }
           else  if(iout=sscanf(strb,"%s.") != 0){
     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */        month=99;
       stratrunc = &(stra[lstra-9]);        year=9999;
       num[i]=atol(stratrunc);      }else{
     }        printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line,j);
     else        exit(1);
       num[i]=atol(stra);      }
     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){      annais[i]=(double)(year);
       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;}*/      moisnais[i]=(double)(month);
           strcpy(line,stra);
     i=i+1;     
   } /* End loop reading  data */      cutv(stra, strb,line,' ');
   fclose(fic);      errno=0;
   /* printf("ii=%d", ij);      dval=strtod(strb,&endptr);
      scanf("%d",i);*/      if( strb[0]=='\0' || (*endptr != '\0')){
   imx=i-1; /* Number of individuals */        printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
         exit(1);
   /* for (i=1; i<=imx; i++){      }
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;      weight[i]=dval;
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;      strcpy(line,stra);
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;     
     }*/      for (j=ncovcol;j>=1;j--){
    /*  for (i=1; i<=imx; i++){        cutv(stra, strb,line,' ');
      if (s[4][i]==9)  s[4][i]=-1;         errno=0;
      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]));}*/        lval=strtol(strb,&endptr,10);
           if( strb[0]=='\0' || (*endptr != '\0')){
   /* for (i=1; i<=imx; i++) */          printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a covar (meaning 0 for the reference or 1).  Exiting.\n",lval, linei,i, line);
            exit(1);
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;        }
      else weight[i]=1;*/        if(lval <-1 || lval >1){
           printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
   /* Calculation of the number of parameters from char model */   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */   for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
   Tprod=ivector(1,15);    For example, for multinomial values like 1, 2 and 3,\n \
   Tvaraff=ivector(1,15);    build V1=0 V2=0 for the reference value (1),\n \
   Tvard=imatrix(1,15,1,2);          V1=1 V2=0 for (2) \n \
   Tage=ivector(1,15);         and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
       output of IMaCh is often meaningless.\n \
   if (strlen(model) >1){ /* If there is at least 1 covariate */   Exiting.\n",lval,linei, i,line,j);
     j=0, j1=0, k1=1, k2=1;          exit(1);
     j=nbocc(model,'+'); /* j=Number of '+' */        }
     j1=nbocc(model,'*'); /* j1=Number of '*' */        covar[j][i]=(double)(lval);
     cptcovn=j+1;         strcpy(line,stra);
     cptcovprod=j1; /*Number of products */      }
           lstra=strlen(stra);
     strcpy(modelsav,model);      
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
       printf("Error. Non available option model=%s ",model);        stratrunc = &(stra[lstra-9]);
       fprintf(ficlog,"Error. Non available option model=%s ",model);        num[i]=atol(stratrunc);
       goto end;      }
     }      else
             num[i]=atol(stra);
     /* This loop fills the array Tvar from the string 'model'.*/      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
         printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/
     for(i=(j+1); i>=1;i--){     
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */       i=i+1;
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */    } /* End loop reading  data */
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/    fclose(fic);
       /*scanf("%d",i);*/    /* printf("ii=%d", ij);
       if (strchr(strb,'*')) {  /* Model includes a product */       scanf("%d",i);*/
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/    imx=i-1; /* Number of individuals */
         if (strcmp(strc,"age")==0) { /* Vn*age */  
           cptcovprod--;    /* for (i=1; i<=imx; i++){
           cutv(strb,stre,strd,'V');      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/      if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
           cptcovage++;      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
             Tage[cptcovage]=i;      }*/
             /*printf("stre=%s ", stre);*/     /*  for (i=1; i<=imx; i++){
         }       if (s[4][i]==9)  s[4][i]=-1;
         else if (strcmp(strd,"age")==0) { /* or age*Vn */       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]));}*/
           cptcovprod--;   
           cutv(strb,stre,strc,'V');    /* for (i=1; i<=imx; i++) */
           Tvar[i]=atoi(stre);   
           cptcovage++;     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
           Tage[cptcovage]=i;       else weight[i]=1;*/
         }  
         else {  /* Age is not in the model */    /* Calculation of the number of parameters from char model */
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
           Tvar[i]=ncovcol+k1;    Tprod=ivector(1,15);
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */    Tvaraff=ivector(1,15);
           Tprod[k1]=i;    Tvard=imatrix(1,15,1,2);
           Tvard[k1][1]=atoi(strc); /* m*/    Tage=ivector(1,15);      
           Tvard[k1][2]=atoi(stre); /* n */     
           Tvar[cptcovn+k2]=Tvard[k1][1];    if (strlen(model) >1){ /* If there is at least 1 covariate */
           Tvar[cptcovn+k2+1]=Tvard[k1][2];       j=0, j1=0, k1=1, k2=1;
           for (k=1; k<=lastobs;k++)       j=nbocc(model,'+'); /* j=Number of '+' */
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];      j1=nbocc(model,'*'); /* j1=Number of '*' */
           k1++;      cptcovn=j+1;
           k2=k2+2;      cptcovprod=j1; /*Number of products */
         }     
       }      strcpy(modelsav,model);
       else { /* no more sum */      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/        printf("Error. Non available option model=%s ",model);
        /*  scanf("%d",i);*/        fprintf(ficlog,"Error. Non available option model=%s ",model);
       cutv(strd,strc,strb,'V');        goto end;
       Tvar[i]=atoi(strc);      }
       }     
       strcpy(modelsav,stra);        /* This loop fills the array Tvar from the string 'model'.*/
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);  
         scanf("%d",i);*/      for(i=(j+1); i>=1;i--){
     } /* end of loop + */        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
   } /* end model */        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
           /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.        /*scanf("%d",i);*/
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/        if (strchr(strb,'*')) {  /* Model includes a product */
           cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);          if (strcmp(strc,"age")==0) { /* Vn*age */
   printf("cptcovprod=%d ", cptcovprod);            cptcovprod--;
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);            cutv(strb,stre,strd,'V');
             Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
   scanf("%d ",i);*/            cptcovage++;
               Tage[cptcovage]=i;
     /*  if(mle==1){*/              /*printf("stre=%s ", stre);*/
   if (weightopt != 1) { /* Maximisation without weights*/          }
     for(i=1;i<=n;i++) weight[i]=1.0;          else if (strcmp(strd,"age")==0) { /* or age*Vn */
   }            cptcovprod--;
     /*-calculation of age at interview from date of interview and age at death -*/            cutv(strb,stre,strc,'V');
   agev=matrix(1,maxwav,1,imx);            Tvar[i]=atoi(stre);
             cptcovage++;
   for (i=1; i<=imx; i++) {            Tage[cptcovage]=i;
     for(m=2; (m<= maxwav); m++) {          }
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){          else {  /* Age is not in the model */
         anint[m][i]=9999;            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
         s[m][i]=-1;            Tvar[i]=ncovcol+k1;
       }            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){            Tprod[k1]=i;
         nberr++;            Tvard[k1][1]=atoi(strc); /* m*/
         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);            Tvard[k1][2]=atoi(stre); /* n */
         fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);            Tvar[cptcovn+k2]=Tvard[k1][1];
         s[m][i]=-1;            Tvar[cptcovn+k2+1]=Tvard[k1][2];
       }            for (k=1; k<=lastobs;k++)
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
         nberr++;            k1++;
         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]);             k2=k2+2;
         fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]);           }
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */        }
       }        else { /* no more sum */
     }          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
   }         /*  scanf("%d",i);*/
         cutv(strd,strc,strb,'V');
   for (i=1; i<=imx; i++)  {        Tvar[i]=atoi(strc);
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);        }
     for(m=firstpass; (m<= lastpass); m++){        strcpy(modelsav,stra);  
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
         if (s[m][i] >= nlstate+1) {          scanf("%d",i);*/
           if(agedc[i]>0)      } /* end of loop + */
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)    } /* end model */
               agev[m][i]=agedc[i];   
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][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.
             else {      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
               if ((int)andc[i]!=9999){  
                 nbwarn++;    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);    printf("cptcovprod=%d ", cptcovprod);
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                 agev[m][i]=-1;  
               }    scanf("%d ",i);*/
             }  
         }      /*  if(mle==1){*/
         else if(s[m][i] !=9){ /* Standard case, age in fractional    if (weightopt != 1) { /* Maximisation without weights*/
                                  years but with the precision of a month */      for(i=1;i<=n;i++) weight[i]=1.0;
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);    }
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)      /*-calculation of age at interview from date of interview and age at death -*/
             agev[m][i]=1;    agev=matrix(1,maxwav,1,imx);
           else if(agev[m][i] <agemin){   
             agemin=agev[m][i];    for (i=1; i<=imx; i++) {
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/      for(m=2; (m<= maxwav); m++) {
           }        if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
           else if(agev[m][i] >agemax){          anint[m][i]=9999;
             agemax=agev[m][i];          s[m][i]=-1;
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/        }
           }        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
           /*agev[m][i]=anint[m][i]-annais[i];*/          nberr++;
           /*     agev[m][i] = age[i]+2*m;*/          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);
         else { /* =9 */          s[m][i]=-1;
           agev[m][i]=1;        }
           s[m][i]=-1;        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
         }          nberr++;
       }          printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]);
       else /*= 0 Unknown */          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]);
         agev[m][i]=1;          s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
     }        }
           }
   }    }
   for (i=1; i<=imx; i++)  {  
     for(m=firstpass; (m<=lastpass); m++){    for (i=1; i<=imx; i++)  {
       if (s[m][i] > (nlstate+ndeath)) {      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
         nberr++;      for(m=firstpass; (m<= lastpass); m++){
         printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);             if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
         fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);               if (s[m][i] >= nlstate+1) {
         goto end;            if(agedc[i]>0)
       }              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
     }                agev[m][i]=agedc[i];
   }            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
               else {
   /*for (i=1; i<=imx; i++){                if ((int)andc[i]!=9999){
   for (m=firstpass; (m<lastpass); m++){                  nbwarn++;
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);                  printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 }                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   agev[m][i]=-1;
 }*/                }
               }
           }
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);          else if(s[m][i] !=9){ /* Standard case, age in fractional
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);                                    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]);
   agegomp=(int)agemin;            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
   free_vector(severity,1,maxwav);              agev[m][i]=1;
   free_imatrix(outcome,1,maxwav+1,1,n);            else if(agev[m][i] <agemin){
   free_vector(moisnais,1,n);              agemin=agev[m][i];
   free_vector(annais,1,n);              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
   /* free_matrix(mint,1,maxwav,1,n);            }
      free_matrix(anint,1,maxwav,1,n);*/            else if(agev[m][i] >agemax){
   free_vector(moisdc,1,n);              agemax=agev[m][i];
   free_vector(andc,1,n);              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
             }
                /*agev[m][i]=anint[m][i]-annais[i];*/
   wav=ivector(1,imx);            /*     agev[m][i] = age[i]+2*m;*/
   dh=imatrix(1,lastpass-firstpass+1,1,imx);          }
   bh=imatrix(1,lastpass-firstpass+1,1,imx);          else { /* =9 */
   mw=imatrix(1,lastpass-firstpass+1,1,imx);            agev[m][i]=1;
                s[m][i]=-1;
   /* Concatenates waves */          }
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);        }
         else /*= 0 Unknown */
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */          agev[m][i]=1;
       }
   Tcode=ivector(1,100);     
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);     }
   ncodemax[1]=1;    for (i=1; i<=imx; i++)  {
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);      for(m=firstpass; (m<=lastpass); m++){
               if (s[m][i] > (nlstate+ndeath)) {
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of           nberr++;
                                  the estimations*/          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);    
   h=0;          fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);    
   m=pow(2,cptcoveff);          goto end;
          }
   for(k=1;k<=cptcoveff; k++){      }
     for(i=1; i <=(m/pow(2,k));i++){    }
       for(j=1; j <= ncodemax[k]; j++){  
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){    /*for (i=1; i<=imx; i++){
           h++;    for (m=firstpass; (m<lastpass); m++){
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/  }
         }   
       }  }*/
     }  
   }   
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);     printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
      codtab[1][2]=1;codtab[2][2]=2; */    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
   /* for(i=1; i <=m ;i++){   
      for(k=1; k <=cptcovn; k++){    agegomp=(int)agemin;
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);    free_vector(severity,1,maxwav);
      }    free_imatrix(outcome,1,maxwav+1,1,n);
      printf("\n");    free_vector(moisnais,1,n);
      }    free_vector(annais,1,n);
      scanf("%d",i);*/    /* free_matrix(mint,1,maxwav,1,n);
            free_matrix(anint,1,maxwav,1,n);*/
   /*------------ gnuplot -------------*/    free_vector(moisdc,1,n);
   strcpy(optionfilegnuplot,optionfilefiname);    free_vector(andc,1,n);
   if(mle==-3)  
     strcat(optionfilegnuplot,"-mort");     
   strcat(optionfilegnuplot,".gp");    wav=ivector(1,imx);
     dh=imatrix(1,lastpass-firstpass+1,1,imx);
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {    bh=imatrix(1,lastpass-firstpass+1,1,imx);
     printf("Problem with file %s",optionfilegnuplot);    mw=imatrix(1,lastpass-firstpass+1,1,imx);
   }     
   else{    /* Concatenates waves */
     fprintf(ficgp,"\n# %s\n", version);     concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
     fprintf(ficgp,"# %s\n", optionfilegnuplot);   
     fprintf(ficgp,"set missing 'NaNq'\n");    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
   }  
   /*  fclose(ficgp);*/    Tcode=ivector(1,100);
   /*--------- index.htm --------*/    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
     ncodemax[1]=1;
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
   if(mle==-3)       
     strcat(optionfilehtm,"-mort");    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
   strcat(optionfilehtm,".htm");                                   the estimations*/
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {    h=0;
     printf("Problem with %s \n",optionfilehtm), exit(0);    m=pow(2,cptcoveff);
   }   
     for(k=1;k<=cptcoveff; k++){
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */      for(i=1; i <=(m/pow(2,k));i++){
   strcat(optionfilehtmcov,"-cov.htm");        for(j=1; j <= ncodemax[k]; j++){
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
     printf("Problem with %s \n",optionfilehtmcov), exit(0);            h++;
   }            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
   else{            /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \          }
 <hr size=\"2\" color=\"#EC5E5E\"> \n\        }
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\      }
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);    }
   }    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
        codtab[1][2]=1;codtab[2][2]=2; */
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \    /* for(i=1; i <=m ;i++){
 <hr size=\"2\" color=\"#EC5E5E\"> \n\       for(k=1; k <=cptcovn; k++){
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 \n\       }
 <hr  size=\"2\" color=\"#EC5E5E\">\       printf("\n");
  <ul><li><h4>Parameter files</h4>\n\       }
  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\       scanf("%d",i);*/
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\     
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\    /*------------ gnuplot -------------*/
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\    strcpy(optionfilegnuplot,optionfilefiname);
  - Date and time at start: %s</ul>\n",\    if(mle==-3)
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\      strcat(optionfilegnuplot,"-mort");
           optionfilefiname,optionfilext,optionfilefiname,optionfilext,\    strcat(optionfilegnuplot,".gp");
           fileres,fileres,\  
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
   fflush(fichtm);      printf("Problem with file %s",optionfilegnuplot);
     }
   strcpy(pathr,path);    else{
   strcat(pathr,optionfilefiname);      fprintf(ficgp,"\n# %s\n", version);
   chdir(optionfilefiname); /* Move to directory named optionfile */      fprintf(ficgp,"# %s\n", optionfilegnuplot);
         fprintf(ficgp,"set missing 'NaNq'\n");
   /* Calculates basic frequencies. Computes observed prevalence at single age    }
      and prints on file fileres'p'. */    /*  fclose(ficgp);*/
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);    /*--------- index.htm --------*/
   
   fprintf(fichtm,"\n");    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\    if(mle==-3)
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\      strcat(optionfilehtm,"-mort");
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\    strcat(optionfilehtm,".htm");
           imx,agemin,agemax,jmin,jmax,jmean);    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      printf("Problem with %s \n",optionfilehtm), exit(0);
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    }
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */    strcat(optionfilehtmcov,"-cov.htm");
         if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
          printf("Problem with %s \n",optionfilehtmcov), exit(0);
   /* For Powell, parameters are in a vector p[] starting at p[1]    }
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */    else{
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
   <hr size=\"2\" color=\"#EC5E5E\"> \n\
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
             optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
   if (mle==-3){    }
     ximort=matrix(1,NDIM,1,NDIM);  
     cens=ivector(1,n);    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
     ageexmed=vector(1,n);  <hr size=\"2\" color=\"#EC5E5E\"> \n\
     agecens=vector(1,n);  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
     dcwave=ivector(1,n);  \n\
    <hr  size=\"2\" color=\"#EC5E5E\">\
     for (i=1; i<=imx; i++){   <ul><li><h4>Parameter files</h4>\n\
       dcwave[i]=-1;   - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
       for (m=firstpass; m<=lastpass; m++)   - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
         if (s[m][i]>nlstate) {   - Log file of the run: <a href=\"%s\">%s</a><br>\n\
           dcwave[i]=m;   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/   - Date and time at start: %s</ul>\n",\
           break;            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
         }            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
     }            fileres,fileres,\
             filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
     for (i=1; i<=imx; i++) {    fflush(fichtm);
       if (wav[i]>0){  
         ageexmed[i]=agev[mw[1][i]][i];    strcpy(pathr,path);
         j=wav[i];    strcat(pathr,optionfilefiname);
         agecens[i]=1.;     chdir(optionfilefiname); /* Move to directory named optionfile */
    
         if (ageexmed[i]> 1 && wav[i] > 0){    /* Calculates basic frequencies. Computes observed prevalence at single age
           agecens[i]=agev[mw[j][i]][i];       and prints on file fileres'p'. */
           cens[i]= 1;    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
         }else if (ageexmed[i]< 1)   
           cens[i]= -1;    fprintf(fichtm,"\n");
         if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
           cens[i]=0 ;  Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
       }  Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
       else cens[i]=-1;            imx,agemin,agemax,jmin,jmax,jmean);
     }    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
           oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     for (i=1;i<=NDIM;i++) {      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       for (j=1;j<=NDIM;j++)      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
         ximort[i][j]=(i == j ? 1.0 : 0.0);      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
     }     
          
     p[1]=0.0268; p[NDIM]=0.083;    /* For Powell, parameters are in a vector p[] starting at p[1]
     /*printf("%lf %lf", p[1], p[2]);*/       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
         p=param[1][1]; /* *(*(*(param +1)+1)+0) */
       
     printf("Powell\n");  fprintf(ficlog,"Powell\n");    globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
     strcpy(filerespow,"pow-mort");   
     strcat(filerespow,fileres);    if (mle==-3){
     if((ficrespow=fopen(filerespow,"w"))==NULL) {      ximort=matrix(1,NDIM,1,NDIM);
       printf("Problem with resultfile: %s\n", filerespow);      cens=ivector(1,n);
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);      ageexmed=vector(1,n);
     }      agecens=vector(1,n);
     fprintf(ficrespow,"# Powell\n# iter -2*LL");      dcwave=ivector(1,n);
     /*  for (i=1;i<=nlstate;i++)   
         for(j=1;j<=nlstate+ndeath;j++)      for (i=1; i<=imx; i++){
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);        dcwave[i]=-1;
     */        for (m=firstpass; m<=lastpass; m++)
     fprintf(ficrespow,"\n");          if (s[m][i]>nlstate) {
                 dcwave[i]=m;
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);            /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
     fclose(ficrespow);            break;
               }
     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);       }
   
     for(i=1; i <=NDIM; i++)      for (i=1; i<=imx; i++) {
       for(j=i+1;j<=NDIM;j++)        if (wav[i]>0){
         matcov[i][j]=matcov[j][i];          ageexmed[i]=agev[mw[1][i]][i];
               j=wav[i];
     printf("\nCovariance matrix\n ");          agecens[i]=1.;
     for(i=1; i <=NDIM; i++) {  
       for(j=1;j<=NDIM;j++){           if (ageexmed[i]> 1 && wav[i] > 0){
         printf("%f ",matcov[i][j]);            agecens[i]=agev[mw[j][i]][i];
       }            cens[i]= 1;
       printf("\n ");          }else if (ageexmed[i]< 1)
     }            cens[i]= -1;
               if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);            cens[i]=0 ;
     for (i=1;i<=NDIM;i++)         }
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));        else cens[i]=-1;
       }
     lsurv=vector(1,AGESUP);     
     lpop=vector(1,AGESUP);      for (i=1;i<=NDIM;i++) {
     tpop=vector(1,AGESUP);        for (j=1;j<=NDIM;j++)
     lsurv[agegomp]=100000;          ximort[i][j]=(i == j ? 1.0 : 0.0);
           }
     for (k=agegomp;k<=AGESUP;k++) {     
       agemortsup=k;      p[1]=0.0268; p[NDIM]=0.083;
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;      /*printf("%lf %lf", p[1], p[2]);*/
     }     
          
     for (k=agegomp;k<agemortsup;k++)      printf("Powell\n");  fprintf(ficlog,"Powell\n");
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));      strcpy(filerespow,"pow-mort");
           strcat(filerespow,fileres);
     for (k=agegomp;k<agemortsup;k++){      if((ficrespow=fopen(filerespow,"w"))==NULL) {
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;        printf("Problem with resultfile: %s\n", filerespow);
       sumlpop=sumlpop+lpop[k];        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
     }      }
           fprintf(ficrespow,"# Powell\n# iter -2*LL");
     tpop[agegomp]=sumlpop;      /*  for (i=1;i<=nlstate;i++)
     for (k=agegomp;k<(agemortsup-3);k++){          for(j=1;j<=nlstate+ndeath;j++)
       /*  tpop[k+1]=2;*/          if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
       tpop[k+1]=tpop[k]-lpop[k];      */
     }      fprintf(ficrespow,"\n");
          
           powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");      fclose(ficrespow);
     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]);      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
       
           for(i=1; i <=NDIM; i++)
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */        for(j=i+1;j<=NDIM;j++)
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);          matcov[i][j]=matcov[j][i];
          
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \      printf("\nCovariance matrix\n ");
                      stepm, weightopt,\      for(i=1; i <=NDIM; i++) {
                      model,imx,p,matcov,agemortsup);        for(j=1;j<=NDIM;j++){
               printf("%f ",matcov[i][j]);
     free_vector(lsurv,1,AGESUP);        }
     free_vector(lpop,1,AGESUP);        printf("\n ");
     free_vector(tpop,1,AGESUP);      }
   } /* Endof if mle==-3 */     
         printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
   else{ /* For mle >=1 */      for (i=1;i<=NDIM;i++)
           printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
     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);      lsurv=vector(1,AGESUP);
     for (k=1; k<=npar;k++)      lpop=vector(1,AGESUP);
       printf(" %d %8.5f",k,p[k]);      tpop=vector(1,AGESUP);
     printf("\n");      lsurv[agegomp]=100000;
     globpr=1; /* to print the contributions */     
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */      for (k=agegomp;k<=AGESUP;k++) {
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);        agemortsup=k;
     for (k=1; k<=npar;k++)        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
       printf(" %d %8.5f",k,p[k]);      }
     printf("\n");     
     if(mle>=1){ /* Could be 1 or 2 */      for (k=agegomp;k<agemortsup;k++)
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
     }     
           for (k=agegomp;k<agemortsup;k++){
     /*--------- results files --------------*/        lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
     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);        sumlpop=sumlpop+lpop[k];
           }
          
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      tpop[agegomp]=sumlpop;
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      for (k=agegomp;k<(agemortsup-3);k++){
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        /*  tpop[k+1]=2;*/
     for(i=1,jk=1; i <=nlstate; i++){        tpop[k+1]=tpop[k]-lpop[k];
       for(k=1; k <=(nlstate+ndeath); k++){      }
         if (k != i) {     
           printf("%d%d ",i,k);     
           fprintf(ficlog,"%d%d ",i,k);      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
           fprintf(ficres,"%1d%1d ",i,k);      for (k=agegomp;k<(agemortsup-2);k++)
           for(j=1; j <=ncovmodel; j++){        printf("%d %.0lf %lf %.0lf %.0lf %.0lf %lf\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);
             printf("%f ",p[jk]);     
             fprintf(ficlog,"%f ",p[jk]);     
             fprintf(ficres,"%f ",p[jk]);      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
             jk++;       printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
           }     
           printf("\n");      printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
           fprintf(ficlog,"\n");                       stepm, weightopt,\
           fprintf(ficres,"\n");                       model,imx,p,matcov,agemortsup);
         }     
       }      free_vector(lsurv,1,AGESUP);
     }      free_vector(lpop,1,AGESUP);
     if(mle!=0){      free_vector(tpop,1,AGESUP);
       /* Computing hessian and covariance matrix */    } /* Endof if mle==-3 */
       ftolhess=ftol; /* Usually correct */   
       hesscov(matcov, p, npar, delti, ftolhess, func);    else{ /* For mle >=1 */
     }   
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
     printf("# Scales (for hessian or gradient estimation)\n");      printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");      for (k=1; k<=npar;k++)
     for(i=1,jk=1; i <=nlstate; i++){        printf(" %d %8.5f",k,p[k]);
       for(j=1; j <=nlstate+ndeath; j++){      printf("\n");
         if (j!=i) {      globpr=1; /* to print the contributions */
           fprintf(ficres,"%1d%1d",i,j);      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
           printf("%1d%1d",i,j);      printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
           fprintf(ficlog,"%1d%1d",i,j);      for (k=1; k<=npar;k++)
           for(k=1; k<=ncovmodel;k++){        printf(" %d %8.5f",k,p[k]);
             printf(" %.5e",delti[jk]);      printf("\n");
             fprintf(ficlog," %.5e",delti[jk]);      if(mle>=1){ /* Could be 1 or 2 */
             fprintf(ficres," %.5e",delti[jk]);        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
             jk++;      }
           }     
           printf("\n");      /*--------- results files --------------*/
           fprintf(ficlog,"\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);
           fprintf(ficres,"\n");     
         }     
       }      fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     }      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
           fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");      for(i=1,jk=1; i <=nlstate; i++){
     if(mle>=1)        for(k=1; k <=(nlstate+ndeath); k++){
       printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");          if (k != i) {
     fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");            printf("%d%d ",i,k);
     /* # 121 Var(a12)\n\ */            fprintf(ficlog,"%d%d ",i,k);
     /* # 122 Cov(b12,a12) Var(b12)\n\ */            fprintf(ficres,"%1d%1d ",i,k);
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */            for(j=1; j <=ncovmodel; j++){
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */              printf("%lf ",p[jk]);
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */              fprintf(ficlog,"%lf ",p[jk]);
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */              fprintf(ficres,"%lf ",p[jk]);
     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */              jk++;
     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */            }
                 printf("\n");
                 fprintf(ficlog,"\n");
     /* Just to have a covariance matrix which will be more understandable            fprintf(ficres,"\n");
        even is we still don't want to manage dictionary of variables          }
     */        }
     for(itimes=1;itimes<=2;itimes++){      }
       jj=0;      if(mle!=0){
       for(i=1; i <=nlstate; i++){        /* Computing hessian and covariance matrix */
         for(j=1; j <=nlstate+ndeath; j++){        ftolhess=ftol; /* Usually correct */
           if(j==i) continue;        hesscov(matcov, p, npar, delti, ftolhess, func);
           for(k=1; k<=ncovmodel;k++){      }
             jj++;      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
             ca[0]= k+'a'-1;ca[1]='\0';      printf("# Scales (for hessian or gradient estimation)\n");
             if(itimes==1){      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
               if(mle>=1)      for(i=1,jk=1; i <=nlstate; i++){
                 printf("#%1d%1d%d",i,j,k);        for(j=1; j <=nlstate+ndeath; j++){
               fprintf(ficlog,"#%1d%1d%d",i,j,k);          if (j!=i) {
               fprintf(ficres,"#%1d%1d%d",i,j,k);            fprintf(ficres,"%1d%1d",i,j);
             }else{            printf("%1d%1d",i,j);
               if(mle>=1)            fprintf(ficlog,"%1d%1d",i,j);
                 printf("%1d%1d%d",i,j,k);            for(k=1; k<=ncovmodel;k++){
               fprintf(ficlog,"%1d%1d%d",i,j,k);              printf(" %.5e",delti[jk]);
               fprintf(ficres,"%1d%1d%d",i,j,k);              fprintf(ficlog," %.5e",delti[jk]);
             }              fprintf(ficres," %.5e",delti[jk]);
             ll=0;              jk++;
             for(li=1;li <=nlstate; li++){            }
               for(lj=1;lj <=nlstate+ndeath; lj++){            printf("\n");
                 if(lj==li) continue;            fprintf(ficlog,"\n");
                 for(lk=1;lk<=ncovmodel;lk++){            fprintf(ficres,"\n");
                   ll++;          }
                   if(ll<=jj){        }
                     cb[0]= lk +'a'-1;cb[1]='\0';      }
                     if(ll<jj){     
                       if(itimes==1){      fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                         if(mle>=1)      if(mle>=1)
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);        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," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      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(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      /* # 121 Var(a12)\n\ */
                       }else{      /* # 122 Cov(b12,a12) Var(b12)\n\ */
                         if(mle>=1)      /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                           printf(" %.5e",matcov[jj][ll]);       /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                         fprintf(ficlog," %.5e",matcov[jj][ll]);       /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                         fprintf(ficres," %.5e",matcov[jj][ll]);       /* # 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\ */
                     }else{      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                       if(itimes==1){     
                         if(mle>=1)     
                           printf(" Var(%s%1d%1d)",ca,i,j);      /* Just to have a covariance matrix which will be more understandable
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);         even is we still don't want to manage dictionary of variables
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);      */
                       }else{      for(itimes=1;itimes<=2;itimes++){
                         if(mle>=1)        jj=0;
                           printf(" %.5e",matcov[jj][ll]);         for(i=1; i <=nlstate; i++){
                         fprintf(ficlog," %.5e",matcov[jj][ll]);           for(j=1; j <=nlstate+ndeath; j++){
                         fprintf(ficres," %.5e",matcov[jj][ll]);             if(j==i) continue;
                       }            for(k=1; k<=ncovmodel;k++){
                     }              jj++;
                   }              ca[0]= k+'a'-1;ca[1]='\0';
                 } /* end lk */              if(itimes==1){
               } /* end lj */                if(mle>=1)
             } /* end li */                  printf("#%1d%1d%d",i,j,k);
             if(mle>=1)                fprintf(ficlog,"#%1d%1d%d",i,j,k);
               printf("\n");                fprintf(ficres,"#%1d%1d%d",i,j,k);
             fprintf(ficlog,"\n");              }else{
             fprintf(ficres,"\n");                if(mle>=1)
             numlinepar++;                  printf("%1d%1d%d",i,j,k);
           } /* end k*/                fprintf(ficlog,"%1d%1d%d",i,j,k);
         } /*end j */                fprintf(ficres,"%1d%1d%d",i,j,k);
       } /* end i */              }
     } /* end itimes */              ll=0;
                   for(li=1;li <=nlstate; li++){
     fflush(ficlog);                for(lj=1;lj <=nlstate+ndeath; lj++){
     fflush(ficres);                  if(lj==li) continue;
                       for(lk=1;lk<=ncovmodel;lk++){
     while((c=getc(ficpar))=='#' && c!= EOF){                    ll++;
       ungetc(c,ficpar);                    if(ll<=jj){
       fgets(line, MAXLINE, ficpar);                      cb[0]= lk +'a'-1;cb[1]='\0';
       puts(line);                      if(ll<jj){
       fputs(line,ficparo);                        if(itimes==1){
     }                          if(mle>=1)
     ungetc(c,ficpar);                            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);
     estepm=0;                          fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);                        }else{
     if (estepm==0 || estepm < stepm) estepm=stepm;                          if(mle>=1)
     if (fage <= 2) {                            printf(" %.5e",matcov[jj][ll]);
       bage = ageminpar;                          fprintf(ficlog," %.5e",matcov[jj][ll]);
       fage = agemaxpar;                          fprintf(ficres," %.5e",matcov[jj][ll]);
     }                        }
                           }else{
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");                        if(itimes==1){
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);                          if(mle>=1)
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);                            printf(" Var(%s%1d%1d)",ca,i,j);
                               fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
     while((c=getc(ficpar))=='#' && c!= EOF){                          fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
       ungetc(c,ficpar);                        }else{
       fgets(line, MAXLINE, ficpar);                          if(mle>=1)
       puts(line);                            printf(" %.5e",matcov[jj][ll]);
       fputs(line,ficparo);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
     }                          fprintf(ficres," %.5e",matcov[jj][ll]);
     ungetc(c,ficpar);                        }
                           }
     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);                    }
     fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);                  } /* end lk */
     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);                } /* end lj */
     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);              } /* end li */
     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(mle>=1)
                     printf("\n");
     while((c=getc(ficpar))=='#' && c!= EOF){              fprintf(ficlog,"\n");
       ungetc(c,ficpar);              fprintf(ficres,"\n");
       fgets(line, MAXLINE, ficpar);              numlinepar++;
       puts(line);            } /* end k*/
       fputs(line,ficparo);          } /*end j */
     }        } /* end i */
     ungetc(c,ficpar);      } /* end itimes */
          
           fflush(ficlog);
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;      fflush(ficres);
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;     
           while((c=getc(ficpar))=='#' && c!= EOF){
     fscanf(ficpar,"pop_based=%d\n",&popbased);        ungetc(c,ficpar);
     fprintf(ficparo,"pop_based=%d\n",popbased);           fgets(line, MAXLINE, ficpar);
     fprintf(ficres,"pop_based=%d\n",popbased);           puts(line);
             fputs(line,ficparo);
     while((c=getc(ficpar))=='#' && c!= EOF){      }
       ungetc(c,ficpar);      ungetc(c,ficpar);
       fgets(line, MAXLINE, ficpar);     
       puts(line);      estepm=0;
       fputs(line,ficparo);      fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
     }      if (estepm==0 || estepm < stepm) estepm=stepm;
     ungetc(c,ficpar);      if (fage <= 2) {
             bage = ageminpar;
     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);        fage = agemaxpar;
     fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      }
     printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);     
     fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
     /* day and month of proj2 are not used but only year anproj2.*/      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
          
           while((c=getc(ficpar))=='#' && c!= EOF){
             ungetc(c,ficpar);
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/        fgets(line, MAXLINE, ficpar);
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/        puts(line);
             fputs(line,ficparo);
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      }
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);      ungetc(c,ficpar);
          
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\      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);
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\      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);
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);      fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
             printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
    /*------------ free_vector  -------------*/      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);
    /*  chdir(path); */     
        while((c=getc(ficpar))=='#' && c!= EOF){
     free_ivector(wav,1,imx);        ungetc(c,ficpar);
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);        fgets(line, MAXLINE, ficpar);
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);        puts(line);
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);           fputs(line,ficparo);
     free_lvector(num,1,n);      }
     free_vector(agedc,1,n);      ungetc(c,ficpar);
     /*free_matrix(covar,0,NCOVMAX,1,n);*/     
     /*free_matrix(covar,1,NCOVMAX,1,n);*/     
     fclose(ficparo);      dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
     fclose(ficres);      dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
      
       fscanf(ficpar,"pop_based=%d\n",&popbased);
     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/      fprintf(ficparo,"pop_based=%d\n",popbased);  
         fprintf(ficres,"pop_based=%d\n",popbased);  
     strcpy(filerespl,"pl");     
     strcat(filerespl,fileres);      while((c=getc(ficpar))=='#' && c!= EOF){
     if((ficrespl=fopen(filerespl,"w"))==NULL) {        ungetc(c,ficpar);
       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;        fgets(line, MAXLINE, ficpar);
       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;        puts(line);
     }        fputs(line,ficparo);
     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);      }
     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);      ungetc(c,ficpar);
     pstamp(ficrespl);     
     fprintf(ficrespl,"# Period (stable) prevalence \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(ficrespl,"#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);
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);      printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
     fprintf(ficrespl,"\n");      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);
     prlim=matrix(1,nlstate,1,nlstate);      /* day and month of proj2 are not used but only year anproj2.*/
      
     agebase=ageminpar;     
     agelim=agemaxpar;     
     ftolpl=1.e-10;      /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
     i1=cptcoveff;      /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
     if (cptcovn < 1){i1=1;}     
       replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){     
         k=k+1;      printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/                   model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
         fprintf(ficrespl,"\n#******");                   jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
         printf("\n#******");       
         fprintf(ficlog,"\n#******");     /*------------ free_vector  -------------*/
         for(j=1;j<=cptcoveff;j++) {     /*  chdir(path); */
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);   
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      free_ivector(wav,1,imx);
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
         }      free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
         fprintf(ficrespl,"******\n");      free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
         printf("******\n");      free_lvector(num,1,n);
         fprintf(ficlog,"******\n");      free_vector(agedc,1,n);
               /*free_matrix(covar,0,NCOVMAX,1,n);*/
         for (age=agebase; age<=agelim; age++){      /*free_matrix(covar,1,NCOVMAX,1,n);*/
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      fclose(ficparo);
           fprintf(ficrespl,"%.0f ",age );      fclose(ficres);
           for(j=1;j<=cptcoveff;j++)  
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
           for(i=1; i<=nlstate;i++)      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
             fprintf(ficrespl," %.5f", prlim[i][i]);   
           fprintf(ficrespl,"\n");      strcpy(filerespl,"pl");
         }      strcat(filerespl,fileres);
       }      if((ficrespl=fopen(filerespl,"w"))==NULL) {
     }        printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     fclose(ficrespl);        fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
       }
     /*------------- h Pij x at various ages ------------*/      printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
         fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);      pstamp(ficrespl);
     if((ficrespij=fopen(filerespij,"w"))==NULL) {      fprintf(ficrespl,"# Period (stable) prevalence \n");
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;      fprintf(ficrespl,"#Age ");
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;      for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
     }      fprintf(ficrespl,"\n");
     printf("Computing pij: result on file '%s' \n", filerespij);   
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);      prlim=matrix(1,nlstate,1,nlstate);
     
     stepsize=(int) (stepm+YEARM-1)/YEARM;      agebase=ageminpar;
     /*if (stepm<=24) stepsize=2;*/      agelim=agemaxpar;
       ftolpl=1.e-10;
     agelim=AGESUP;      i1=cptcoveff;
     hstepm=stepsize*YEARM; /* Every year of age */      if (cptcovn < 1){i1=1;}
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */   
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
     /* hstepm=1;   aff par mois*/        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
     pstamp(ficrespij);          k=k+1;
     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");          /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){          fprintf(ficrespl,"\n#******");
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){          printf("\n#******");
         k=k+1;          fprintf(ficlog,"\n#******");
         fprintf(ficrespij,"\n#****** ");          for(j=1;j<=cptcoveff;j++) {
         for(j=1;j<=cptcoveff;j++)             fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         fprintf(ficrespij,"******\n");            fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   }
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */          fprintf(ficrespl,"******\n");
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */           printf("******\n");
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */          fprintf(ficlog,"******\n");
          
           /*      nhstepm=nhstepm*YEARM; aff par mois*/          for (age=agebase; age<=agelim; age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            fprintf(ficrespl,"%.0f ",age );
           oldm=oldms;savm=savms;            for(j=1;j<=cptcoveff;j++)
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);                fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");            for(i=1; i<=nlstate;i++)
           for(i=1; i<=nlstate;i++)              fprintf(ficrespl," %.5f", prlim[i][i]);
             for(j=1; j<=nlstate+ndeath;j++)            fprintf(ficrespl,"\n");
               fprintf(ficrespij," %1d-%1d",i,j);          }
           fprintf(ficrespij,"\n");        }
           for (h=0; h<=nhstepm; h++){      }
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );      fclose(ficrespl);
             for(i=1; i<=nlstate;i++)  
               for(j=1; j<=nlstate+ndeath;j++)      /*------------- h Pij x at various ages ------------*/
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);   
             fprintf(ficrespij,"\n");      strcpy(filerespij,"pij");  strcat(filerespij,fileres);
           }      if((ficrespij=fopen(filerespij,"w"))==NULL) {
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
           fprintf(ficrespij,"\n");        fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
         }      }
       }      printf("Computing pij: result on file '%s' \n", filerespij);
     }      fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
    
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);      stepsize=(int) (stepm+YEARM-1)/YEARM;
       /*if (stepm<=24) stepsize=2;*/
     fclose(ficrespij);  
       agelim=AGESUP;
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);      hstepm=stepsize*YEARM; /* Every year of age */
     for(i=1;i<=AGESUP;i++)      hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
       for(j=1;j<=NCOVMAX;j++)  
         for(k=1;k<=NCOVMAX;k++)      /* hstepm=1;   aff par mois*/
           probs[i][j][k]=0.;      pstamp(ficrespij);
       fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
     /*---------- Forecasting ------------------*/      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
     if(prevfcast==1){          k=k+1;
       /*    if(stepm ==1){*/          fprintf(ficrespij,"\n#****** ");
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);          for(j=1;j<=cptcoveff;j++)
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/            fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
       /*      }  */          fprintf(ficrespij,"******\n");
       /*      else{ */         
       /*        erreur=108; */          for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
       /*        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); */            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
       /*        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); */            nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
       /*      } */  
     }            /*      nhstepm=nhstepm*YEARM; aff par mois*/
     
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     /*---------- Health expectancies and variances ------------*/            oldm=oldms;savm=savms;
             hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
     strcpy(filerest,"t");            fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
     strcat(filerest,fileres);            for(i=1; i<=nlstate;i++)
     if((ficrest=fopen(filerest,"w"))==NULL) {              for(j=1; j<=nlstate+ndeath;j++)
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;                fprintf(ficrespij," %1d-%1d",i,j);
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;            fprintf(ficrespij,"\n");
     }            for (h=0; h<=nhstepm; h++){
     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);               fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);               for(i=1; i<=nlstate;i++)
                 for(j=1; j<=nlstate+ndeath;j++)
                   fprintf(ficrespij," %.5f", p3mat[i][j][h]);
     strcpy(filerese,"e");              fprintf(ficrespij,"\n");
     strcat(filerese,fileres);            }
     if((ficreseij=fopen(filerese,"w"))==NULL) {            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);            fprintf(ficrespij,"\n");
       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);  
       varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
     strcpy(fileresstde,"stde");  
     strcat(fileresstde,fileres);      fclose(ficrespij);
     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {  
       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);      probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);      for(i=1;i<=AGESUP;i++)
     }        for(j=1;j<=NCOVMAX;j++)
     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);          for(k=1;k<=NCOVMAX;k++)
     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);            probs[i][j][k]=0.;
   
     strcpy(filerescve,"cve");      /*---------- Forecasting ------------------*/
     strcat(filerescve,fileres);      /*if((stepm == 1) && (strcmp(model,".")==0)){*/
     if((ficrescveij=fopen(filerescve,"w"))==NULL) {      if(prevfcast==1){
       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);        /*    if(stepm ==1){*/
       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);        prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
     }        /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
     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);        /*      else{ */
         /*        erreur=108; */
     strcpy(fileresv,"v");        /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
     strcat(fileresv,fileres);        /*        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((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);      /*---------- Health expectancies and variances ------------*/
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);  
       strcpy(filerest,"t");
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */      strcat(filerest,fileres);
     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);      if((ficrest=fopen(filerest,"w"))==NULL) {
     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\        printf("Problem with total LE resultfile: %s\n", filerest);goto end;
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);        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);
     if (mobilav!=0) {      fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
       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);      strcpy(filerese,"e");
         printf(" Error in movingaverage mobilav=%d\n",mobilav);      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);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      }
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      printf("Computing Health Expectancies: result on file '%s' \n", filerese);
         k=k+1;       fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
         fprintf(ficrest,"\n#****** ");  
         for(j=1;j<=cptcoveff;j++)       strcpy(fileresstde,"stde");
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      strcat(fileresstde,fileres);
         fprintf(ficrest,"******\n");      if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
         printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
         fprintf(ficreseij,"\n#****** ");        fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
         fprintf(ficresstdeij,"\n#****** ");      }
         fprintf(ficrescveij,"\n#****** ");      printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
         for(j=1;j<=cptcoveff;j++) {      fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
           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]]);      strcpy(filerescve,"cve");
           fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      strcat(filerescve,fileres);
         }      if((ficrescveij=fopen(filerescve,"w"))==NULL) {
         fprintf(ficreseij,"******\n");        printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
         fprintf(ficresstdeij,"******\n");        fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
         fprintf(ficrescveij,"******\n");      }
       printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
         fprintf(ficresvij,"\n#****** ");      fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
         for(j=1;j<=cptcoveff;j++)   
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      strcpy(fileresv,"v");
         fprintf(ficresvij,"******\n");      strcat(fileresv,fileres);
       if((ficresvij=fopen(fileresv,"w"))==NULL) {
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);        printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
         oldm=oldms;savm=savms;        fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
         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);        printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
        fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);  
         oldm=oldms;savm=savms;      /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
         varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);      prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
         if(popbased==1){      /*  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",\
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);          ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
         }      */
   
         pstamp(ficrest);      if (mobilav!=0) {
         fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");        mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);        if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
         fprintf(ficrest,"\n");          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
           printf(" Error in movingaverage mobilav=%d\n",mobilav);
         epj=vector(1,nlstate+1);        }
         for(age=bage; age <=fage ;age++){      }
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);  
           if (popbased==1) {      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
             if(mobilav ==0){        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
               for(i=1; i<=nlstate;i++)          k=k+1;
                 prlim[i][i]=probs[(int)age][i][k];          fprintf(ficrest,"\n#****** ");
             }else{ /* mobilav */           for(j=1;j<=cptcoveff;j++)
               for(i=1; i<=nlstate;i++)            fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                 prlim[i][i]=mobaverage[(int)age][i][k];          fprintf(ficrest,"******\n");
             }  
           }          fprintf(ficreseij,"\n#****** ");
                   fprintf(ficresstdeij,"\n#****** ");
           fprintf(ficrest," %4.0f",age);          fprintf(ficrescveij,"\n#****** ");
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){          for(j=1;j<=cptcoveff;j++) {
             for(i=1, epj[j]=0.;i <=nlstate;i++) {            fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
               epj[j] += prlim[i][i]*eij[i][j][(int)age];            fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/            fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             }          }
             epj[nlstate+1] +=epj[j];          fprintf(ficreseij,"******\n");
           }          fprintf(ficresstdeij,"******\n");
           fprintf(ficrescveij,"******\n");
           for(i=1, vepp=0.;i <=nlstate;i++)  
             for(j=1;j <=nlstate;j++)          fprintf(ficresvij,"\n#****** ");
               vepp += vareij[i][j][(int)age];          for(j=1;j<=cptcoveff;j++)
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));            fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           for(j=1;j <=nlstate;j++){          fprintf(ficresvij,"******\n");
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));  
           }          eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
           fprintf(ficrest,"\n");          oldm=oldms;savm=savms;
         }          evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);          cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);   
         free_vector(epj,1,nlstate+1);          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);
     free_vector(weight,1,n);          if(popbased==1){
     free_imatrix(Tvard,1,15,1,2);            varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);
     free_imatrix(s,1,maxwav+1,1,n);          }
     free_matrix(anint,1,maxwav,1,n);   
     free_matrix(mint,1,maxwav,1,n);          pstamp(ficrest);
     free_ivector(cod,1,n);          fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");
     free_ivector(tab,1,NCOVMAX);          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
     fclose(ficreseij);          fprintf(ficrest,"\n");
     fclose(ficresstdeij);  
     fclose(ficrescveij);          epj=vector(1,nlstate+1);
     fclose(ficresvij);          for(age=bage; age <=fage ;age++){
     fclose(ficrest);            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
     fclose(ficpar);            if (popbased==1) {
                 if(mobilav ==0){
     /*------- Variance of period (stable) prevalence------*/                   for(i=1; i<=nlstate;i++)
                   prlim[i][i]=probs[(int)age][i][k];
     strcpy(fileresvpl,"vpl");              }else{ /* mobilav */
     strcat(fileresvpl,fileres);                for(i=1; i<=nlstate;i++)
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {                  prlim[i][i]=mobaverage[(int)age][i][k];
       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);            fprintf(ficrest," %4.0f",age);
             for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){              for(i=1, epj[j]=0.;i <=nlstate;i++) {
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){                epj[j] += prlim[i][i]*eij[i][j][(int)age];
         k=k+1;                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
         fprintf(ficresvpl,"\n#****** ");              }
         for(j=1;j<=cptcoveff;j++)               epj[nlstate+1] +=epj[j];
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);            }
         fprintf(ficresvpl,"******\n");  
                   for(i=1, vepp=0.;i <=nlstate;i++)
         varpl=matrix(1,nlstate,(int) bage, (int) fage);              for(j=1;j <=nlstate;j++)
         oldm=oldms;savm=savms;                vepp += vareij[i][j][(int)age];
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);            for(j=1;j <=nlstate;j++){
       }              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
     }            }
             fprintf(ficrest,"\n");
     fclose(ficresvpl);          }
           free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     /*---------- End : free ----------------*/          free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          free_vector(epj,1,nlstate+1);
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);        }
       }
   }  /* mle==-3 arrives here for freeing */      free_vector(weight,1,n);
   free_matrix(prlim,1,nlstate,1,nlstate);      free_imatrix(Tvard,1,15,1,2);
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);      free_imatrix(s,1,maxwav+1,1,n);
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);      free_matrix(anint,1,maxwav,1,n);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);      free_matrix(mint,1,maxwav,1,n);
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);      free_ivector(cod,1,n);
     free_matrix(covar,0,NCOVMAX,1,n);      free_ivector(tab,1,NCOVMAX);
     free_matrix(matcov,1,npar,1,npar);      fclose(ficreseij);
     /*free_vector(delti,1,npar);*/      fclose(ficresstdeij);
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);       fclose(ficrescveij);
     free_matrix(agev,1,maxwav,1,imx);      fclose(ficresvij);
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);      fclose(ficrest);
       fclose(ficpar);
     free_ivector(ncodemax,1,8);   
     free_ivector(Tvar,1,15);      /*------- Variance of period (stable) prevalence------*/  
     free_ivector(Tprod,1,15);  
     free_ivector(Tvaraff,1,15);      strcpy(fileresvpl,"vpl");
     free_ivector(Tage,1,15);      strcat(fileresvpl,fileres);
     free_ivector(Tcode,1,100);      if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
         printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);        exit(0);
     free_imatrix(codtab,1,100,1,10);      }
   fflush(fichtm);      printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
   fflush(ficgp);  
         for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
   if((nberr >0) || (nbwarn>0)){          k=k+1;
     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);          fprintf(ficresvpl,"\n#****** ");
     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);          for(j=1;j<=cptcoveff;j++)
   }else{            fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     printf("End of Imach\n");          fprintf(ficresvpl,"******\n");
     fprintf(ficlog,"End of Imach\n");       
   }          varpl=matrix(1,nlstate,(int) bage, (int) fage);
   printf("See log file on %s\n",filelog);          oldm=oldms;savm=savms;
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */          varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
   (void) gettimeofday(&end_time,&tzp);          free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
   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);       fclose(ficresvpl);
   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));      /*---------- End : free ----------------*/
       if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
   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);    }  /* mle==-3 arrives here for freeing */
   /*  printf("Total time was %d uSec.\n", total_usecs);*/    free_matrix(prlim,1,nlstate,1,nlstate);
 /*   if(fileappend(fichtm,optionfilehtm)){ */      free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);      free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
   fclose(fichtm);      free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
   fclose(fichtmcov);      free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
   fclose(ficgp);      free_matrix(covar,0,NCOVMAX,1,n);
   fclose(ficlog);      free_matrix(matcov,1,npar,1,npar);
   /*------ End -----------*/      /*free_vector(delti,1,npar);*/
       free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
       free_matrix(agev,1,maxwav,1,imx);
    printf("Before Current directory %s!\n",pathcd);      free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
    if(chdir(pathcd) != 0)  
     printf("Can't move to directory %s!\n",path);      free_ivector(ncodemax,1,8);
   if(getcwd(pathcd,MAXLINE) > 0)      free_ivector(Tvar,1,15);
     printf("Current directory %s!\n",pathcd);      free_ivector(Tprod,1,15);
   /*strcat(plotcmd,CHARSEPARATOR);*/      free_ivector(Tvaraff,1,15);
   sprintf(plotcmd,"gnuplot");      free_ivector(Tage,1,15);
 #ifndef UNIX      free_ivector(Tcode,1,100);
   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);  
 #endif      free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
   if(!stat(plotcmd,&info)){      free_imatrix(codtab,1,100,1,10);
     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);    fflush(fichtm);
     if(!stat(getenv("GNUPLOTBIN"),&info)){    fflush(ficgp);
       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);   
     }else  
       strcpy(pplotcmd,plotcmd);    if((nberr >0) || (nbwarn>0)){
 #ifdef UNIX      printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
     strcpy(plotcmd,GNUPLOTPROGRAM);      fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
     if(!stat(plotcmd,&info)){    }else{
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);      printf("End of Imach\n");
     }else      fprintf(ficlog,"End of Imach\n");
       strcpy(pplotcmd,plotcmd);    }
 #endif    printf("See log file on %s\n",filelog);
   }else    /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
     strcpy(pplotcmd,plotcmd);    (void) gettimeofday(&end_time,&tzp);
       tm = *localtime(&end_time.tv_sec);
   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);    tmg = *gmtime(&end_time.tv_sec);
   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);    strcpy(strtend,asctime(&tm));
     printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);
   if((outcmd=system(plotcmd)) != 0){    fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);
     printf("\n Problem with gnuplot\n");    printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
   }  
   printf(" Wait...");    printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
   while (z[0] != 'q') {    fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     /* chdir(path); */    fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     printf("\nType e to edit output files, g to graph again and q for exiting: ");    /*  printf("Total time was %d uSec.\n", total_usecs);*/
     scanf("%s",z);  /*   if(fileappend(fichtm,optionfilehtm)){ */
 /*     if (z[0] == 'c') system("./imach"); */    fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     if (z[0] == 'e') {    fclose(fichtm);
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);    fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
       system(optionfilehtm);    fclose(fichtmcov);
     }    fclose(ficgp);
     else if (z[0] == 'g') system(plotcmd);    fclose(ficlog);
     else if (z[0] == 'q') exit(0);    /*------ End -----------*/
   }  
   end:  
   while (z[0] != 'q') {     printf("Before Current directory %s!\n",pathcd);
     printf("\nType  q for exiting: ");     if(chdir(pathcd) != 0)
     scanf("%s",z);      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.121  
changed lines
  Added in v.1.125


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