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

version 1.119, 2006/03/15 17:42:26 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.119  2006/03/15 17:42:26  brouard    Revision 1.125  2006/04/04 15:20:31  lievre
   (Module): Bug if status = -2, the loglikelihood was    Errors in calculation of health expectancies. Age was not initialized.
   computed as likelihood omitting the logarithm. Version O.98e    Forecasting file added.
   
   Revision 1.118  2006/03/14 18:20:07  brouard    Revision 1.124  2006/03/22 17:13:53  lievre
   (Module): varevsij Comments added explaining the second    Parameters are printed with %lf instead of %f (more numbers after the comma).
   table of variances if popbased=1 .    The log-likelihood is printed in the log file
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.  
   (Module): Function pstamp added    Revision 1.123  2006/03/20 10:52:43  brouard
   (Module): Version 0.98d    * imach.c (Module): <title> changed, corresponds to .htm file
     name. <head> headers where missing.
   Revision 1.117  2006/03/14 17:16:22  brouard  
   (Module): varevsij Comments added explaining the second    * imach.c (Module): Weights can have a decimal point as for
   table of variances if popbased=1 .    English (a comma might work with a correct LC_NUMERIC environment,
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.    otherwise the weight is truncated).
   (Module): Function pstamp added    Modification of warning when the covariates values are not 0 or
   (Module): Version 0.98d    1.
     Version 0.98g
   Revision 1.116  2006/03/06 10:29:27  brouard  
   (Module): Variance-covariance wrong links and    Revision 1.122  2006/03/20 09:45:41  brouard
   varian-covariance of ej. is needed (Saito).    (Module): Weights can have a decimal point as for
     English (a comma might work with a correct LC_NUMERIC environment,
   Revision 1.115  2006/02/27 12:17:45  brouard    otherwise the weight is truncated).
   (Module): One freematrix added in mlikeli! 0.98c    Modification of warning when the covariates values are not 0 or
     1.
   Revision 1.114  2006/02/26 12:57:58  brouard    Version 0.98g
   (Module): Some improvements in processing parameter  
   filename with strsep.    Revision 1.121  2006/03/16 17:45:01  lievre
     * imach.c (Module): Comments concerning covariates added
   Revision 1.113  2006/02/24 14:20:24  brouard  
   (Module): Memory leaks checks with valgrind and:    * imach.c (Module): refinements in the computation of lli if
   datafile was not closed, some imatrix were not freed and on matrix    status=-2 in order to have more reliable computation if stepm is
   allocation too.    not 1 month. Version 0.98f
   
   Revision 1.112  2006/01/30 09:55:26  brouard    Revision 1.120  2006/03/16 15:10:38  lievre
   (Module): Back to gnuplot.exe instead of wgnuplot.exe    (Module): refinements in the computation of lli if
     status=-2 in order to have more reliable computation if stepm is
   Revision 1.111  2006/01/25 20:38:18  brouard    not 1 month. Version 0.98f
   (Module): Lots of cleaning and bugs added (Gompertz)  
   (Module): Comments can be added in data file. Missing date values    Revision 1.119  2006/03/15 17:42:26  brouard
   can be a simple dot '.'.    (Module): Bug if status = -2, the loglikelihood was
     computed as likelihood omitting the logarithm. Version O.98e
   Revision 1.110  2006/01/25 00:51:50  brouard  
   (Module): Lots of cleaning and bugs added (Gompertz)    Revision 1.118  2006/03/14 18:20:07  brouard
     (Module): varevsij Comments added explaining the second
   Revision 1.109  2006/01/24 19:37:15  brouard    table of variances if popbased=1 .
   (Module): Comments (lines starting with a #) are allowed in data.    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
     (Module): Function pstamp added
   Revision 1.108  2006/01/19 18:05:42  lievre    (Module): Version 0.98d
   Gnuplot problem appeared...  
   To be fixed    Revision 1.117  2006/03/14 17:16:22  brouard
     (Module): varevsij Comments added explaining the second
   Revision 1.107  2006/01/19 16:20:37  brouard    table of variances if popbased=1 .
   Test existence of gnuplot in imach path    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
     (Module): Function pstamp added
   Revision 1.106  2006/01/19 13:24:36  brouard    (Module): Version 0.98d
   Some cleaning and links added in html output  
     Revision 1.116  2006/03/06 10:29:27  brouard
   Revision 1.105  2006/01/05 20:23:19  lievre    (Module): Variance-covariance wrong links and
   *** empty log message ***    varian-covariance of ej. is needed (Saito).
   
   Revision 1.104  2005/09/30 16:11:43  lievre    Revision 1.115  2006/02/27 12:17:45  brouard
   (Module): sump fixed, loop imx fixed, and simplifications.    (Module): One freematrix added in mlikeli! 0.98c
   (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.114  2006/02/26 12:57:58  brouard
   (instead of missing=-1 in earlier versions) and his/her    (Module): Some improvements in processing parameter
   contributions to the likelihood is 1 - Prob of dying from last    filename with strsep.
   health status (= 1-p13= p11+p12 in the easiest case of somebody in  
   the healthy state at last known wave). Version is 0.98    Revision 1.113  2006/02/24 14:20:24  brouard
     (Module): Memory leaks checks with valgrind and:
   Revision 1.103  2005/09/30 15:54:49  lievre    datafile was not closed, some imatrix were not freed and on matrix
   (Module): sump fixed, loop imx fixed, and simplifications.    allocation too.
   
   Revision 1.102  2004/09/15 17:31:30  brouard    Revision 1.112  2006/01/30 09:55:26  brouard
   Add the possibility to read data file including tab characters.    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   
   Revision 1.101  2004/09/15 10:38:38  brouard    Revision 1.111  2006/01/25 20:38:18  brouard
   Fix on curr_time    (Module): Lots of cleaning and bugs added (Gompertz)
     (Module): Comments can be added in data file. Missing date values
   Revision 1.100  2004/07/12 18:29:06  brouard    can be a simple dot '.'.
   Add version for Mac OS X. Just define UNIX in Makefile  
     Revision 1.110  2006/01/25 00:51:50  brouard
   Revision 1.99  2004/06/05 08:57:40  brouard    (Module): Lots of cleaning and bugs added (Gompertz)
   *** empty log message ***  
     Revision 1.109  2006/01/24 19:37:15  brouard
   Revision 1.98  2004/05/16 15:05:56  brouard    (Module): Comments (lines starting with a #) are allowed in data.
   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.108  2006/01/19 18:05:42  lievre
   state at each age, but using a Gompertz model: log u =a + b*age .    Gnuplot problem appeared...
   This is the basic analysis of mortality and should be done before any    To be fixed
   other analysis, in order to test if the mortality estimated from the  
   cross-longitudinal survey is different from the mortality estimated    Revision 1.107  2006/01/19 16:20:37  brouard
   from other sources like vital statistic data.    Test existence of gnuplot in imach path
   
   The same imach parameter file can be used but the option for mle should be -3.    Revision 1.106  2006/01/19 13:24:36  brouard
     Some cleaning and links added in html output
   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.105  2006/01/05 20:23:19  lievre
     *** empty log message ***
   The output is very simple: only an estimate of the intercept and of  
   the slope with 95% confident intervals.    Revision 1.104  2005/09/30 16:11:43  lievre
     (Module): sump fixed, loop imx fixed, and simplifications.
   Current limitations:    (Module): If the status is missing at the last wave but we know
   A) Even if you enter covariates, i.e. with the    that the person is alive, then we can code his/her status as -2
   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.    (instead of missing=-1 in earlier versions) and his/her
   B) There is no computation of Life Expectancy nor Life Table.    contributions to the likelihood is 1 - Prob of dying from last
     health status (= 1-p13= p11+p12 in the easiest case of somebody in
   Revision 1.97  2004/02/20 13:25:42  lievre    the healthy state at last known wave). Version is 0.98
   Version 0.96d. Population forecasting command line is (temporarily)  
   suppressed.    Revision 1.103  2005/09/30 15:54:49  lievre
     (Module): sump fixed, loop imx fixed, and simplifications.
   Revision 1.96  2003/07/15 15:38:55  brouard  
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is    Revision 1.102  2004/09/15 17:31:30  brouard
   rewritten within the same printf. Workaround: many printfs.    Add the possibility to read data file including tab characters.
   
   Revision 1.95  2003/07/08 07:54:34  brouard    Revision 1.101  2004/09/15 10:38:38  brouard
   * imach.c (Repository):    Fix on curr_time
   (Repository): Using imachwizard code to output a more meaningful covariance  
   matrix (cov(a12,c31) instead of numbers.    Revision 1.100  2004/07/12 18:29:06  brouard
     Add version for Mac OS X. Just define UNIX in Makefile
   Revision 1.94  2003/06/27 13:00:02  brouard  
   Just cleaning    Revision 1.99  2004/06/05 08:57:40  brouard
     *** empty log message ***
   Revision 1.93  2003/06/25 16:33:55  brouard  
   (Module): On windows (cygwin) function asctime_r doesn't    Revision 1.98  2004/05/16 15:05:56  brouard
   exist so I changed back to asctime which exists.    New version 0.97 . First attempt to estimate force of mortality
   (Module): Version 0.96b    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.92  2003/06/25 16:30:45  brouard    This is the basic analysis of mortality and should be done before any
   (Module): On windows (cygwin) function asctime_r doesn't    other analysis, in order to test if the mortality estimated from the
   exist so I changed back to asctime which exists.    cross-longitudinal survey is different from the mortality estimated
     from other sources like vital statistic data.
   Revision 1.91  2003/06/25 15:30:29  brouard  
   * imach.c (Repository): Duplicated warning errors corrected.    The same imach parameter file can be used but the option for mle should be -3.
   (Repository): Elapsed time after each iteration is now output. It  
   helps to forecast when convergence will be reached. Elapsed time    Agnès, who wrote this part of the code, tried to keep most of the
   is stamped in powell.  We created a new html file for the graphs    former routines in order to include the new code within the former code.
   concerning matrix of covariance. It has extension -cov.htm.  
     The output is very simple: only an estimate of the intercept and of
   Revision 1.90  2003/06/24 12:34:15  brouard    the slope with 95% confident intervals.
   (Module): Some bugs corrected for windows. Also, when  
   mle=-1 a template is output in file "or"mypar.txt with the design    Current limitations:
   of the covariance matrix to be input.    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.89  2003/06/24 12:30:52  brouard    B) There is no computation of Life Expectancy nor Life Table.
   (Module): Some bugs corrected for windows. Also, when  
   mle=-1 a template is output in file "or"mypar.txt with the design    Revision 1.97  2004/02/20 13:25:42  lievre
   of the covariance matrix to be input.    Version 0.96d. Population forecasting command line is (temporarily)
     suppressed.
   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.96  2003/07/15 15:38:55  brouard
     * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   Revision 1.87  2003/06/18 12:26:01  brouard    rewritten within the same printf. Workaround: many printfs.
   Version 0.96  
     Revision 1.95  2003/07/08 07:54:34  brouard
   Revision 1.86  2003/06/17 20:04:08  brouard    * imach.c (Repository):
   (Module): Change position of html and gnuplot routines and added    (Repository): Using imachwizard code to output a more meaningful covariance
   routine fileappend.    matrix (cov(a12,c31) instead of numbers.
   
   Revision 1.85  2003/06/17 13:12:43  brouard    Revision 1.94  2003/06/27 13:00:02  brouard
   * imach.c (Repository): Check when date of death was earlier that    Just cleaning
   current date of interview. It may happen when the death was just  
   prior to the death. In this case, dh was negative and likelihood    Revision 1.93  2003/06/25 16:33:55  brouard
   was wrong (infinity). We still send an "Error" but patch by    (Module): On windows (cygwin) function asctime_r doesn't
   assuming that the date of death was just one stepm after the    exist so I changed back to asctime which exists.
   interview.    (Module): Version 0.96b
   (Repository): Because some people have very long ID (first column)  
   we changed int to long in num[] and we added a new lvector for    Revision 1.92  2003/06/25 16:30:45  brouard
   memory allocation. But we also truncated to 8 characters (left    (Module): On windows (cygwin) function asctime_r doesn't
   truncation)    exist so I changed back to asctime which exists.
   (Repository): No more line truncation errors.  
     Revision 1.91  2003/06/25 15:30:29  brouard
   Revision 1.84  2003/06/13 21:44:43  brouard    * imach.c (Repository): Duplicated warning errors corrected.
   * imach.c (Repository): Replace "freqsummary" at a correct    (Repository): Elapsed time after each iteration is now output. It
   place. It differs from routine "prevalence" which may be called    helps to forecast when convergence will be reached. Elapsed time
   many times. Probs is memory consuming and must be used with    is stamped in powell.  We created a new html file for the graphs
   parcimony.    concerning matrix of covariance. It has extension -cov.htm.
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)  
     Revision 1.90  2003/06/24 12:34:15  brouard
   Revision 1.83  2003/06/10 13:39:11  lievre    (Module): Some bugs corrected for windows. Also, when
   *** empty log message ***    mle=-1 a template is output in file "or"mypar.txt with the design
     of the covariance matrix to be input.
   Revision 1.82  2003/06/05 15:57:20  brouard  
   Add log in  imach.c and  fullversion number is now printed.    Revision 1.89  2003/06/24 12:30:52  brouard
     (Module): Some bugs corrected for windows. Also, when
 */    mle=-1 a template is output in file "or"mypar.txt with the design
 /*    of the covariance matrix to be input.
    Interpolated Markov Chain  
     Revision 1.88  2003/06/23 17:54:56  brouard
   Short summary of the programme:    * 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.
     
   This program computes Healthy Life Expectancies from    Revision 1.87  2003/06/18 12:26:01  brouard
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    Version 0.96
   first survey ("cross") where individuals from different ages are  
   interviewed on their health status or degree of disability (in the    Revision 1.86  2003/06/17 20:04:08  brouard
   case of a health survey which is our main interest) -2- at least a    (Module): Change position of html and gnuplot routines and added
   second wave of interviews ("longitudinal") which measure each change    routine fileappend.
   (if any) in individual health status.  Health expectancies are  
   computed from the time spent in each health state according to a    Revision 1.85  2003/06/17 13:12:43  brouard
   model. More health states you consider, more time is necessary to reach the    * imach.c (Repository): Check when date of death was earlier that
   Maximum Likelihood of the parameters involved in the model.  The    current date of interview. It may happen when the death was just
   simplest model is the multinomial logistic model where pij is the    prior to the death. In this case, dh was negative and likelihood
   probability to be observed in state j at the second wave    was wrong (infinity). We still send an "Error" but patch by
   conditional to be observed in state i at the first wave. Therefore    assuming that the date of death was just one stepm after the
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    interview.
   'age' is age and 'sex' is a covariate. If you want to have a more    (Repository): Because some people have very long ID (first column)
   complex model than "constant and age", you should modify the program    we changed int to long in num[] and we added a new lvector for
   where the markup *Covariates have to be included here again* invites    memory allocation. But we also truncated to 8 characters (left
   you to do it.  More covariates you add, slower the    truncation)
   convergence.    (Repository): No more line truncation errors.
   
   The advantage of this computer programme, compared to a simple    Revision 1.84  2003/06/13 21:44:43  brouard
   multinomial logistic model, is clear when the delay between waves is not    * imach.c (Repository): Replace "freqsummary" at a correct
   identical for each individual. Also, if a individual missed an    place. It differs from routine "prevalence" which may be called
   intermediate interview, the information is lost, but taken into    many times. Probs is memory consuming and must be used with
   account using an interpolation or extrapolation.      parcimony.
     Version 0.95a3 (should output exactly the same maximization than 0.8a2)
   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    Revision 1.83  2003/06/10 13:39:11  lievre
   split into an exact number (nh*stepm) of unobserved intermediate    *** empty log message ***
   states. This elementary transition (by month, quarter,  
   semester or year) is modelled as a multinomial logistic.  The hPx    Revision 1.82  2003/06/05 15:57:20  brouard
   matrix is simply the matrix product of nh*stepm elementary matrices    Add log in  imach.c and  fullversion number is now printed.
   and the contribution of each individual to the likelihood is simply  
   hPijx.  */
   /*
   Also this programme outputs the covariance matrix of the parameters but also     Interpolated Markov Chain
   of the life expectancies. It also computes the period (stable) prevalence.   
       Short summary of the programme:
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).   
            Institut national d'études démographiques, Paris.    This program computes Healthy Life Expectancies from
   This software have been partly granted by Euro-REVES, a concerted action    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
   from the European Union.    first survey ("cross") where individuals from different ages are
   It is copyrighted identically to a GNU software product, ie programme and    interviewed on their health status or degree of disability (in the
   software can be distributed freely for non commercial use. Latest version    case of a health survey which is our main interest) -2- at least a
   can be accessed at http://euroreves.ined.fr/imach .    second wave of interviews ("longitudinal") which measure each change
     (if any) in individual health status.  Health expectancies are
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    computed from the time spent in each health state according to a
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    model. More health states you consider, more time is necessary to reach the
       Maximum Likelihood of the parameters involved in the model.  The
   **********************************************************************/    simplest model is the multinomial logistic model where pij is the
 /*    probability to be observed in state j at the second wave
   main    conditional to be observed in state i at the first wave. Therefore
   read parameterfile    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
   read datafile    'age' is age and 'sex' is a covariate. If you want to have a more
   concatwav    complex model than "constant and age", you should modify the program
   freqsummary    where the markup *Covariates have to be included here again* invites
   if (mle >= 1)    you to do it.  More covariates you add, slower the
     mlikeli    convergence.
   print results files  
   if mle==1     The advantage of this computer programme, compared to a simple
      computes hessian    multinomial logistic model, is clear when the delay between waves is not
   read end of parameter file: agemin, agemax, bage, fage, estepm    identical for each individual. Also, if a individual missed an
       begin-prev-date,...    intermediate interview, the information is lost, but taken into
   open gnuplot file    account using an interpolation or extrapolation.  
   open html file  
   period (stable) prevalence    hPijx is the probability to be observed in state i at age x+h
    for age prevalim()    conditional to the observed state i at age x. The delay 'h' can be
   h Pij x    split into an exact number (nh*stepm) of unobserved intermediate
   variance of p varprob    states. This elementary transition (by month, quarter,
   forecasting if prevfcast==1 prevforecast call prevalence()    semester or year) is modelled as a multinomial logistic.  The hPx
   health expectancies    matrix is simply the matrix product of nh*stepm elementary matrices
   Variance-covariance of DFLE    and the contribution of each individual to the likelihood is simply
   prevalence()    hPijx.
    movingaverage()  
   varevsij()     Also this programme outputs the covariance matrix of the parameters but also
   if popbased==1 varevsij(,popbased)    of the life expectancies. It also computes the period (stable) prevalence.
   total life expectancies   
   Variance of period (stable) prevalence    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  end             Institut national d'études démographiques, Paris.
 */    This software have been partly granted by Euro-REVES, a concerted action
     from the European Union.
     It is copyrighted identically to a GNU software product, ie programme and
     software can be distributed freely for non commercial use. Latest version
      can be accessed at http://euroreves.ined.fr/imach .
 #include <math.h>  
 #include <stdio.h>    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 #include <stdlib.h>    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 #include <string.h>   
 #include <unistd.h>    **********************************************************************/
   /*
 #include <limits.h>    main
 #include <sys/types.h>    read parameterfile
 #include <sys/stat.h>    read datafile
 #include <errno.h>    concatwav
 extern int errno;    freqsummary
     if (mle >= 1)
 /* #include <sys/time.h> */      mlikeli
 #include <time.h>    print results files
 #include "timeval.h"    if mle==1
        computes hessian
 /* #include <libintl.h> */    read end of parameter file: agemin, agemax, bage, fage, estepm
 /* #define _(String) gettext (String) */        begin-prev-date,...
     open gnuplot file
 #define MAXLINE 256    open html file
     period (stable) prevalence
 #define GNUPLOTPROGRAM "gnuplot"     for age prevalim()
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/    h Pij x
 #define FILENAMELENGTH 132    variance of p varprob
     forecasting if prevfcast==1 prevforecast call prevalence()
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */    health expectancies
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */    Variance-covariance of DFLE
     prevalence()
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */     movingaverage()
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */    varevsij()
     if popbased==1 varevsij(,popbased)
 #define NINTERVMAX 8    total life expectancies
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */    Variance of period (stable) prevalence
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */   end
 #define NCOVMAX 8 /* Maximum number of covariates */  */
 #define MAXN 20000  
 #define YEARM 12. /* Number of months per year */  
 #define AGESUP 130  
 #define AGEBASE 40   
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */  #include <math.h>
 #ifdef UNIX  #include <stdio.h>
 #define DIRSEPARATOR '/'  #include <stdlib.h>
 #define CHARSEPARATOR "/"  #include <string.h>
 #define ODIRSEPARATOR '\\'  #include <unistd.h>
 #else  
 #define DIRSEPARATOR '\\'  #include <limits.h>
 #define CHARSEPARATOR "\\"  #include <sys/types.h>
 #define ODIRSEPARATOR '/'  #include <sys/stat.h>
 #endif  #include <errno.h>
   extern int errno;
 /* $Id$ */  
 /* $State$ */  /* #include <sys/time.h> */
   #include <time.h>
 char version[]="Imach version 0.98e, March 2006, INED-EUROREVES-Institut de longevite ";  #include "timeval.h"
 char fullversion[]="$Revision$ $Date$";   
 char strstart[80];  /* #include <libintl.h> */
 char optionfilext[10], optionfilefiname[FILENAMELENGTH];  /* #define _(String) gettext (String) */
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */  
 int nvar;  #define MAXLINE 256
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;  
 int npar=NPARMAX;  #define GNUPLOTPROGRAM "gnuplot"
 int nlstate=2; /* Number of live states */  /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 int ndeath=1; /* Number of dead states */  #define FILENAMELENGTH 132
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */  
 int popbased=0;  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
   #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 int *wav; /* Number of waves for this individuual 0 is possible */  
 int maxwav; /* Maxim number of waves */  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 int jmin, jmax; /* min, max spacing between 2 waves */  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
 int ijmin, ijmax; /* Individuals having jmin and jmax */   
 int gipmx, gsw; /* Global variables on the number of contributions   #define NINTERVMAX 8
                    to the likelihood and the sum of weights (done by funcone)*/  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 int mle, weightopt;  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */  #define NCOVMAX 8 /* Maximum number of covariates */
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */  #define MAXN 20000
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between  #define YEARM 12. /* Number of months per year */
            * wave mi and wave mi+1 is not an exact multiple of stepm. */  #define AGESUP 130
 double jmean; /* Mean space between 2 waves */  #define AGEBASE 40
 double **oldm, **newm, **savm; /* Working pointers to matrices */  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */  #ifdef UNIX
 FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;  #define DIRSEPARATOR '/'
 FILE *ficlog, *ficrespow;  #define CHARSEPARATOR "/"
 int globpr; /* Global variable for printing or not */  #define ODIRSEPARATOR '\\'
 double fretone; /* Only one call to likelihood */  #else
 long ipmx; /* Number of contributions */  #define DIRSEPARATOR '\\'
 double sw; /* Sum of weights */  #define CHARSEPARATOR "\\"
 char filerespow[FILENAMELENGTH];  #define ODIRSEPARATOR '/'
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */  #endif
 FILE *ficresilk;  
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;  /* $Id$ */
 FILE *ficresprobmorprev;  /* $State$ */
 FILE *fichtm, *fichtmcov; /* Html File */  
 FILE *ficreseij;  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
 char filerese[FILENAMELENGTH];  char fullversion[]="$Revision$ $Date$";
 FILE *ficresstdeij;  char strstart[80];
 char fileresstde[FILENAMELENGTH];  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 FILE *ficrescveij;  int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 char filerescve[FILENAMELENGTH];  int nvar;
 FILE  *ficresvij;  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 char fileresv[FILENAMELENGTH];  int npar=NPARMAX;
 FILE  *ficresvpl;  int nlstate=2; /* Number of live states */
 char fileresvpl[FILENAMELENGTH];  int ndeath=1; /* Number of dead states */
 char title[MAXLINE];  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];  int popbased=0;
 char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];  
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];   int *wav; /* Number of waves for this individuual 0 is possible */
 char command[FILENAMELENGTH];  int maxwav; /* Maxim number of waves */
 int  outcmd=0;  int jmin, jmax; /* min, max spacing between 2 waves */
   int ijmin, ijmax; /* Individuals having jmin and jmax */
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  int gipmx, gsw; /* Global variables on the number of contributions
                      to the likelihood and the sum of weights (done by funcone)*/
 char filelog[FILENAMELENGTH]; /* Log file */  int mle, weightopt;
 char filerest[FILENAMELENGTH];  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 char fileregp[FILENAMELENGTH];  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 char popfile[FILENAMELENGTH];  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
              * wave mi and wave mi+1 is not an exact multiple of stepm. */
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  double jmean; /* Mean space between 2 waves */
   double **oldm, **newm, **savm; /* Working pointers to matrices */
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 struct timezone tzp;  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
 extern int gettimeofday();  FILE *ficlog, *ficrespow;
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  int globpr; /* Global variable for printing or not */
 long time_value;  double fretone; /* Only one call to likelihood */
 extern long time();  long ipmx; /* Number of contributions */
 char strcurr[80], strfor[80];  double sw; /* Sum of weights */
   char filerespow[FILENAMELENGTH];
 char *endptr;  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 long lval;  FILE *ficresilk;
   FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 #define NR_END 1  FILE *ficresprobmorprev;
 #define FREE_ARG char*  FILE *fichtm, *fichtmcov; /* Html File */
 #define FTOL 1.0e-10  FILE *ficreseij;
   char filerese[FILENAMELENGTH];
 #define NRANSI   FILE *ficresstdeij;
 #define ITMAX 200   char fileresstde[FILENAMELENGTH];
   FILE *ficrescveij;
 #define TOL 2.0e-4   char filerescve[FILENAMELENGTH];
   FILE  *ficresvij;
 #define CGOLD 0.3819660   char fileresv[FILENAMELENGTH];
 #define ZEPS 1.0e-10   FILE  *ficresvpl;
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   char fileresvpl[FILENAMELENGTH];
   char title[MAXLINE];
 #define GOLD 1.618034   char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 #define GLIMIT 100.0   char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 #define TINY 1.0e-20   char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
   char command[FILENAMELENGTH];
 static double maxarg1,maxarg2;  int  outcmd=0;
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
     
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  char filelog[FILENAMELENGTH]; /* Log file */
 #define rint(a) floor(a+0.5)  char filerest[FILENAMELENGTH];
   char fileregp[FILENAMELENGTH];
 static double sqrarg;  char popfile[FILENAMELENGTH];
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 int agegomp= AGEGOMP;  
   struct timeval start_time, end_time, curr_time, last_time, forecast_time;
 int imx;   struct timezone tzp;
 int stepm=1;  extern int gettimeofday();
 /* Stepm, step in month: minimum step interpolation*/  struct tm tmg, tm, tmf, *gmtime(), *localtime();
   long time_value;
 int estepm;  extern long time();
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  char strcurr[80], strfor[80];
   
 int m,nb;  char *endptr;
 long *num;  long lval;
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  double dval;
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  
 double **pmmij, ***probs;  #define NR_END 1
 double *ageexmed,*agecens;  #define FREE_ARG char*
 double dateintmean=0;  #define FTOL 1.0e-10
   
 double *weight;  #define NRANSI
 int **s; /* Status */  #define ITMAX 200
 double *agedc, **covar, idx;  
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  #define TOL 2.0e-4
 double *lsurv, *lpop, *tpop;  
   #define CGOLD 0.3819660
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  #define ZEPS 1.0e-10
 double ftolhess; /* Tolerance for computing hessian */  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
   
 /**************** split *************************/  #define GOLD 1.618034
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  #define GLIMIT 100.0
 {  #define TINY 1.0e-20
   /* 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)  static double maxarg1,maxarg2;
   */   #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
   char  *ss;                            /* pointer */  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
   int   l1, l2;                         /* length counters */   
   #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
   l1 = strlen(path );                   /* length of path */  #define rint(a) floor(a+0.5)
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  static double sqrarg;
   if ( ss == NULL ) {                   /* no directory, so determine current directory */  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
     strcpy( name, path );               /* we got the fullname name because no directory */  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  int agegomp= AGEGOMP;
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  
     /* get current working directory */  int imx;
     /*    extern  char* getcwd ( char *buf , int len);*/  int stepm=1;
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  /* Stepm, step in month: minimum step interpolation*/
       return( GLOCK_ERROR_GETCWD );  
     }  int estepm;
     /* got dirc from getcwd*/  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
     printf(" DIRC = %s \n",dirc);  
   } else {                              /* strip direcotry from path */  int m,nb;
     ss++;                               /* after this, the filename */  long *num;
     l2 = strlen( ss );                  /* length of filename */  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
     strcpy( name, ss );         /* save file name */  double **pmmij, ***probs;
     strncpy( dirc, path, l1 - l2 );     /* now the directory */  double *ageexmed,*agecens;
     dirc[l1-l2] = 0;                    /* add zero */  double dateintmean=0;
     printf(" DIRC2 = %s \n",dirc);  
   }  double *weight;
   /* We add a separator at the end of dirc if not exists */  int **s; /* Status */
   l1 = strlen( dirc );                  /* length of directory */  double *agedc, **covar, idx;
   if( dirc[l1-1] != DIRSEPARATOR ){  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
     dirc[l1] =  DIRSEPARATOR;  double *lsurv, *lpop, *tpop;
     dirc[l1+1] = 0;   
     printf(" DIRC3 = %s \n",dirc);  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
   }  double ftolhess; /* Tolerance for computing hessian */
   ss = strrchr( name, '.' );            /* find last / */  
   if (ss >0){  /**************** split *************************/
     ss++;  static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
     strcpy(ext,ss);                     /* save extension */  {
     l1= strlen( name);    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
     l2= strlen(ss)+1;       the name of the file (name), its extension only (ext) and its first part of the name (finame)
     strncpy( finame, name, l1-l2);    */
     finame[l1-l2]= 0;    char  *ss;                            /* pointer */
   }    int   l1, l2;                         /* length counters */
   
   return( 0 );                          /* we're done */    l1 = strlen(path );                   /* length of path */
 }    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
     ss= strrchr( path, DIRSEPARATOR );            /* find last / */
     if ( ss == NULL ) {                   /* no directory, so determine current directory */
 /******************************************/      strcpy( name, path );               /* we got the fullname name because no directory */
       /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 void replace_back_to_slash(char *s, char*t)        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 {      /* get current working directory */
   int i;      /*    extern  char* getcwd ( char *buf , int len);*/
   int lg=0;      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
   i=0;        return( GLOCK_ERROR_GETCWD );
   lg=strlen(t);      }
   for(i=0; i<= lg; i++) {      /* got dirc from getcwd*/
     (s[i] = t[i]);      printf(" DIRC = %s \n",dirc);
     if (t[i]== '\\') s[i]='/';    } else {                              /* strip direcotry from path */
   }      ss++;                               /* after this, the filename */
 }      l2 = strlen( ss );                  /* length of filename */
       if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 int nbocc(char *s, char occ)      strcpy( name, ss );         /* save file name */
 {      strncpy( dirc, path, l1 - l2 );     /* now the directory */
   int i,j=0;      dirc[l1-l2] = 0;                    /* add zero */
   int lg=20;      printf(" DIRC2 = %s \n",dirc);
   i=0;    }
   lg=strlen(s);    /* We add a separator at the end of dirc if not exists */
   for(i=0; i<= lg; i++) {    l1 = strlen( dirc );                  /* length of directory */
   if  (s[i] == occ ) j++;    if( dirc[l1-1] != DIRSEPARATOR ){
   }      dirc[l1] =  DIRSEPARATOR;
   return j;      dirc[l1+1] = 0;
 }      printf(" DIRC3 = %s \n",dirc);
     }
 void cutv(char *u,char *v, char*t, char occ)    ss = strrchr( name, '.' );            /* find last / */
 {    if (ss >0){
   /* cuts string t into u and v where u ends before first occurence of char 'occ'       ss++;
      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')      strcpy(ext,ss);                     /* save extension */
      gives u="abcedf" and v="ghi2j" */      l1= strlen( name);
   int i,lg,j,p=0;      l2= strlen(ss)+1;
   i=0;      strncpy( finame, name, l1-l2);
   for(j=0; j<=strlen(t)-1; j++) {      finame[l1-l2]= 0;
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;    }
   }  
     return( 0 );                          /* we're done */
   lg=strlen(t);  }
   for(j=0; j<p; j++) {  
     (u[j] = t[j]);  
   }  /******************************************/
      u[p]='\0';  
   void replace_back_to_slash(char *s, char*t)
    for(j=0; j<= lg; j++) {  {
     if (j>=(p+1))(v[j-p-1] = t[j]);    int i;
   }    int lg=0;
 }    i=0;
     lg=strlen(t);
 /********************** nrerror ********************/    for(i=0; i<= lg; i++) {
       (s[i] = t[i]);
 void nrerror(char error_text[])      if (t[i]== '\\') s[i]='/';
 {    }
   fprintf(stderr,"ERREUR ...\n");  }
   fprintf(stderr,"%s\n",error_text);  
   exit(EXIT_FAILURE);  int nbocc(char *s, char occ)
 }  {
 /*********************** vector *******************/    int i,j=0;
 double *vector(int nl, int nh)    int lg=20;
 {    i=0;
   double *v;    lg=strlen(s);
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));    for(i=0; i<= lg; i++) {
   if (!v) nrerror("allocation failure in vector");    if  (s[i] == occ ) j++;
   return v-nl+NR_END;    }
 }    return j;
   }
 /************************ free vector ******************/  
 void free_vector(double*v, int nl, int nh)  void cutv(char *u,char *v, char*t, char occ)
 {  {
   free((FREE_ARG)(v+nl-NR_END));    /* 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" */
 /************************ivector *******************************/    int i,lg,j,p=0;
 int *ivector(long nl,long nh)    i=0;
 {    for(j=0; j<=strlen(t)-1; j++) {
   int *v;      if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));    }
   if (!v) nrerror("allocation failure in ivector");  
   return v-nl+NR_END;    lg=strlen(t);
 }    for(j=0; j<p; j++) {
       (u[j] = t[j]);
 /******************free ivector **************************/    }
 void free_ivector(int *v, long nl, long nh)       u[p]='\0';
 {  
   free((FREE_ARG)(v+nl-NR_END));     for(j=0; j<= lg; j++) {
 }      if (j>=(p+1))(v[j-p-1] = t[j]);
     }
 /************************lvector *******************************/  }
 long *lvector(long nl,long nh)  
 {  /********************** nrerror ********************/
   long *v;  
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));  void nrerror(char error_text[])
   if (!v) nrerror("allocation failure in ivector");  {
   return v-nl+NR_END;    fprintf(stderr,"ERREUR ...\n");
 }    fprintf(stderr,"%s\n",error_text);
     exit(EXIT_FAILURE);
 /******************free lvector **************************/  }
 void free_lvector(long *v, long nl, long nh)  /*********************** vector *******************/
 {  double *vector(int nl, int nh)
   free((FREE_ARG)(v+nl-NR_END));  {
 }    double *v;
     v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 /******************* imatrix *******************************/    if (!v) nrerror("allocation failure in vector");
 int **imatrix(long nrl, long nrh, long ncl, long nch)     return v-nl+NR_END;
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */   }
 {   
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;   /************************ free vector ******************/
   int **m;   void free_vector(double*v, int nl, int nh)
     {
   /* allocate pointers to rows */     free((FREE_ARG)(v+nl-NR_END));
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));   }
   if (!m) nrerror("allocation failure 1 in matrix()");   
   m += NR_END;   /************************ivector *******************************/
   m -= nrl;   int *ivector(long nl,long nh)
     {
       int *v;
   /* allocate rows and set pointers to them */     v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));     if (!v) nrerror("allocation failure in ivector");
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");     return v-nl+NR_END;
   m[nrl] += NR_END;   }
   m[nrl] -= ncl;   
     /******************free ivector **************************/
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;   void free_ivector(int *v, long nl, long nh)
     {
   /* return pointer to array of pointers to rows */     free((FREE_ARG)(v+nl-NR_END));
   return m;   }
 }   
   /************************lvector *******************************/
 /****************** free_imatrix *************************/  long *lvector(long nl,long nh)
 void free_imatrix(m,nrl,nrh,ncl,nch)  {
       int **m;    long *v;
       long nch,ncl,nrh,nrl;     v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
      /* free an int matrix allocated by imatrix() */     if (!v) nrerror("allocation failure in ivector");
 {     return v-nl+NR_END;
   free((FREE_ARG) (m[nrl]+ncl-NR_END));   }
   free((FREE_ARG) (m+nrl-NR_END));   
 }   /******************free lvector **************************/
   void free_lvector(long *v, long nl, long nh)
 /******************* matrix *******************************/  {
 double **matrix(long nrl, long nrh, long ncl, long nch)    free((FREE_ARG)(v+nl-NR_END));
 {  }
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;  
   double **m;  /******************* imatrix *******************************/
   int **imatrix(long nrl, long nrh, long ncl, long nch)
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));       /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
   if (!m) nrerror("allocation failure 1 in matrix()");  {
   m += NR_END;    long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
   m -= nrl;    int **m;
    
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));    /* allocate pointers to rows */
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
   m[nrl] += NR_END;    if (!m) nrerror("allocation failure 1 in matrix()");
   m[nrl] -= ncl;    m += NR_END;
     m -= nrl;
   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])     /* allocate rows and set pointers to them */
    */    m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
 }    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     m[nrl] += NR_END;
 /*************************free matrix ************************/    m[nrl] -= ncl;
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)   
 {    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));   
   free((FREE_ARG)(m+nrl-NR_END));    /* return pointer to array of pointers to rows */
 }    return m;
   }
 /******************* ma3x *******************************/  
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)  /****************** free_imatrix *************************/
 {  void free_imatrix(m,nrl,nrh,ncl,nch)
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;        int **m;
   double ***m;        long nch,ncl,nrh,nrl;
        /* free an int matrix allocated by imatrix() */
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  {
   if (!m) nrerror("allocation failure 1 in matrix()");    free((FREE_ARG) (m[nrl]+ncl-NR_END));
   m += NR_END;    free((FREE_ARG) (m+nrl-NR_END));
   m -= nrl;  }
   
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  /******************* matrix *******************************/
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  double **matrix(long nrl, long nrh, long ncl, long nch)
   m[nrl] += NR_END;  {
   m[nrl] -= ncl;    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
     double **m;
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;  
     m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));    if (!m) nrerror("allocation failure 1 in matrix()");
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");    m += NR_END;
   m[nrl][ncl] += NR_END;    m -= nrl;
   m[nrl][ncl] -= nll;  
   for (j=ncl+1; j<=nch; j++)     m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
     m[nrl][j]=m[nrl][j-1]+nlay;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
       m[nrl] += NR_END;
   for (i=nrl+1; i<=nrh; i++) {    m[nrl] -= ncl;
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;  
     for (j=ncl+1; j<=nch; j++)     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
       m[i][j]=m[i][j-1]+nlay;    return m;
   }    /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
   return m;      */
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])  }
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)  
   */  /*************************free matrix ************************/
 }  void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   {
 /*************************free ma3x ************************/    free((FREE_ARG)(m[nrl]+ncl-NR_END));
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)    free((FREE_ARG)(m+nrl-NR_END));
 {  }
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));  
   free((FREE_ARG)(m[nrl]+ncl-NR_END));  /******************* ma3x *******************************/
   free((FREE_ARG)(m+nrl-NR_END));  double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 }  {
     long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 /*************** function subdirf ***********/    double ***m;
 char *subdirf(char fileres[])  
 {    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   /* Caution optionfilefiname is hidden */    if (!m) nrerror("allocation failure 1 in matrix()");
   strcpy(tmpout,optionfilefiname);    m += NR_END;
   strcat(tmpout,"/"); /* Add to the right */    m -= nrl;
   strcat(tmpout,fileres);  
   return tmpout;    m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 }    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     m[nrl] += NR_END;
 /*************** function subdirf2 ***********/    m[nrl] -= ncl;
 char *subdirf2(char fileres[], char *preop)  
 {    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
     
   /* Caution optionfilefiname is hidden */    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
   strcpy(tmpout,optionfilefiname);    if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
   strcat(tmpout,"/");    m[nrl][ncl] += NR_END;
   strcat(tmpout,preop);    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 subdirf3 ***********/      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 char *subdirf3(char fileres[], char *preop, char *preop2)      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,preop2);  }
   strcat(tmpout,fileres);  
   return tmpout;  /*************************free ma3x ************************/
 }  void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
   {
 /***************** f1dim *************************/    free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 extern int ncom;     free((FREE_ARG)(m[nrl]+ncl-NR_END));
 extern double *pcom,*xicom;    free((FREE_ARG)(m+nrl-NR_END));
 extern double (*nrfunc)(double []);   }
    
 double f1dim(double x)   /*************** function subdirf ***********/
 {   char *subdirf(char fileres[])
   int j;   {
   double f;    /* Caution optionfilefiname is hidden */
   double *xt;     strcpy(tmpout,optionfilefiname);
      strcat(tmpout,"/"); /* Add to the right */
   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 subdirf2 ***********/
 }   char *subdirf2(char fileres[], char *preop)
   {
 /*****************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,fileres);
   double ftemp;    return tmpout;
   double p,q,r,tol1,tol2,u,v,w,x,xm;   }
   double e=0.0;   
    /*************** function subdirf3 ***********/
   a=(ax < cx ? ax : cx);   char *subdirf3(char fileres[], char *preop, char *preop2)
   b=(ax > cx ? ax : cx);   {
   x=w=v=bx;    
   fw=fv=fx=(*f)(x);     /* Caution optionfilefiname is hidden */
   for (iter=1;iter<=ITMAX;iter++) {     strcpy(tmpout,optionfilefiname);
     xm=0.5*(a+b);     strcat(tmpout,"/");
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     strcat(tmpout,preop);
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/    strcat(tmpout,preop2);
     printf(".");fflush(stdout);    strcat(tmpout,fileres);
     fprintf(ficlog,".");fflush(ficlog);    return tmpout;
 #ifdef DEBUG  }
     printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);  
     fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);  /***************** f1dim *************************/
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */  extern int ncom;
 #endif  extern double *pcom,*xicom;
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){   extern double (*nrfunc)(double []);
       *xmin=x;    
       return fx;   double f1dim(double x)
     }   {
     ftemp=fu;    int j;
     if (fabs(e) > tol1) {     double f;
       r=(x-w)*(fx-fv);     double *xt;
       q=(x-v)*(fx-fw);    
       p=(x-v)*q-(x-w)*r;     xt=vector(1,ncom);
       q=2.0*(q-r);     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
       if (q > 0.0) p = -p;     f=(*nrfunc)(xt);
       q=fabs(q);     free_vector(xt,1,ncom);
       etemp=e;     return f;
       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));   /*****************brent *************************/
       else {   double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
         d=p/q;   {
         u=x+d;     int iter;
         if (u-a < tol2 || b-u < tol2)     double a,b,d,etemp;
           d=SIGN(tol1,xm-x);     double fu,fv,fw,fx;
       }     double ftemp;
     } else {     double p,q,r,tol1,tol2,u,v,w,x,xm;
       d=CGOLD*(e=(x >= xm ? a-x : b-x));     double e=0.0;
     }    
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));     a=(ax < cx ? ax : cx);
     fu=(*f)(u);     b=(ax > cx ? ax : cx);
     if (fu <= fx) {     x=w=v=bx;
       if (u >= x) a=x; else b=x;     fw=fv=fx=(*f)(x);
       SHFT(v,w,x,u)     for (iter=1;iter<=ITMAX;iter++) {
         SHFT(fv,fw,fx,fu)       xm=0.5*(a+b);
         } else {       tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
           if (u < x) a=u; else b=u;       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
           if (fu <= fw || w == x) {       printf(".");fflush(stdout);
             v=w;       fprintf(ficlog,".");fflush(ficlog);
             w=u;   #ifdef DEBUG
             fv=fw;       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);
             fw=fu;       fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
           } else if (fu <= fv || v == x || v == w) {       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
             v=u;   #endif
             fv=fu;       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
           }         *xmin=x;
         }         return fx;
   }       }
   nrerror("Too many iterations in brent");       ftemp=fu;
   *xmin=x;       if (fabs(e) > tol1) {
   return fx;         r=(x-w)*(fx-fv);
 }         q=(x-v)*(fx-fw);
         p=(x-v)*q-(x-w)*r;
 /****************** mnbrak ***********************/        q=2.0*(q-r);
         if (q > 0.0) p = -p;
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,         q=fabs(q);
             double (*func)(double))         etemp=e;
 {         e=d;
   double ulim,u,r,q, dum;        if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
   double fu;           d=CGOLD*(e=(x >= xm ? a-x : b-x));
          else {
   *fa=(*func)(*ax);           d=p/q;
   *fb=(*func)(*bx);           u=x+d;
   if (*fb > *fa) {           if (u-a < tol2 || b-u < tol2)
     SHFT(dum,*ax,*bx,dum)             d=SIGN(tol1,xm-x);
       SHFT(dum,*fb,*fa,dum)         }
       }       } else {
   *cx=(*bx)+GOLD*(*bx-*ax);         d=CGOLD*(e=(x >= xm ? a-x : b-x));
   *fc=(*func)(*cx);       }
   while (*fb > *fc) {       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
     r=(*bx-*ax)*(*fb-*fc);       fu=(*f)(u);
     q=(*bx-*cx)*(*fb-*fa);       if (fu <= fx) {
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/         if (u >= x) a=x; else b=x;
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));         SHFT(v,w,x,u)
     ulim=(*bx)+GLIMIT*(*cx-*bx);           SHFT(fv,fw,fx,fu)
     if ((*bx-u)*(u-*cx) > 0.0) {           } else {
       fu=(*func)(u);             if (u < x) a=u; else b=u;
     } else if ((*cx-u)*(u-ulim) > 0.0) {             if (fu <= fw || w == x) {
       fu=(*func)(u);               v=w;
       if (fu < *fc) {               w=u;
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))               fv=fw;
           SHFT(*fb,*fc,fu,(*func)(u))               fw=fu;
           }             } else if (fu <= fv || v == x || v == w) {
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {               v=u;
       u=ulim;               fv=fu;
       fu=(*func)(u);             }
     } else {           }
       u=(*cx)+GOLD*(*cx-*bx);     }
       fu=(*func)(u);     nrerror("Too many iterations in brent");
     }     *xmin=x;
     SHFT(*ax,*bx,*cx,u)     return fx;
       SHFT(*fa,*fb,*fc,fu)   }
       }   
 }   /****************** mnbrak ***********************/
   
 /*************** linmin ************************/  void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
               double (*func)(double))
 int ncom;   {
 double *pcom,*xicom;    double ulim,u,r,q, dum;
 double (*nrfunc)(double []);     double fu;
     
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))     *fa=(*func)(*ax);
 {     *fb=(*func)(*bx);
   double brent(double ax, double bx, double cx,     if (*fb > *fa) {
                double (*f)(double), double tol, double *xmin);       SHFT(dum,*ax,*bx,dum)
   double f1dim(double x);         SHFT(dum,*fb,*fa,dum)
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,         }
               double *fc, double (*func)(double));     *cx=(*bx)+GOLD*(*bx-*ax);
   int j;     *fc=(*func)(*cx);
   double xx,xmin,bx,ax;     while (*fb > *fc) {
   double fx,fb,fa;      r=(*bx-*ax)*(*fb-*fc);
        q=(*bx-*cx)*(*fb-*fa);
   ncom=n;       u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
   pcom=vector(1,n);         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
   xicom=vector(1,n);       ulim=(*bx)+GLIMIT*(*cx-*bx);
   nrfunc=func;       if ((*bx-u)*(u-*cx) > 0.0) {
   for (j=1;j<=n;j++) {         fu=(*func)(u);
     pcom[j]=p[j];       } else if ((*cx-u)*(u-ulim) > 0.0) {
     xicom[j]=xi[j];         fu=(*func)(u);
   }         if (fu < *fc) {
   ax=0.0;           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
   xx=1.0;             SHFT(*fb,*fc,fu,(*func)(u))
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);             }
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);       } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
 #ifdef DEBUG        u=ulim;
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);        fu=(*func)(u);
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);      } else {
 #endif        u=(*cx)+GOLD*(*cx-*bx);
   for (j=1;j<=n;j++) {         fu=(*func)(u);
     xi[j] *= xmin;       }
     p[j] += xi[j];       SHFT(*ax,*bx,*cx,u)
   }         SHFT(*fa,*fb,*fc,fu)
   free_vector(xicom,1,n);         }
   free_vector(pcom,1,n);   }
 }   
   /*************** linmin ************************/
 char *asc_diff_time(long time_sec, char ascdiff[])  
 {  int ncom;
   long sec_left, days, hours, minutes;  double *pcom,*xicom;
   days = (time_sec) / (60*60*24);  double (*nrfunc)(double []);
   sec_left = (time_sec) % (60*60*24);   
   hours = (sec_left) / (60*60) ;  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
   sec_left = (sec_left) %(60*60);  {
   minutes = (sec_left) /60;    double brent(double ax, double bx, double cx,
   sec_left = (sec_left) % (60);                 double (*f)(double), double tol, double *xmin);
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);      double f1dim(double x);
   return ascdiff;    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
 }                double *fc, double (*func)(double));
     int j;
 /*************** powell ************************/    double xx,xmin,bx,ax;
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,     double fx,fb,fa;
             double (*func)(double []))    
 {     ncom=n;
   void linmin(double p[], double xi[], int n, double *fret,     pcom=vector(1,n);
               double (*func)(double []));     xicom=vector(1,n);
   int i,ibig,j;     nrfunc=func;
   double del,t,*pt,*ptt,*xit;    for (j=1;j<=n;j++) {
   double fp,fptt;      pcom[j]=p[j];
   double *xits;      xicom[j]=xi[j];
   int niterf, itmp;    }
     ax=0.0;
   pt=vector(1,n);     xx=1.0;
   ptt=vector(1,n);     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
   xit=vector(1,n);     *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
   xits=vector(1,n);   #ifdef DEBUG
   *fret=(*func)(p);     printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   for (j=1;j<=n;j++) pt[j]=p[j];     fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   for (*iter=1;;++(*iter)) {   #endif
     fp=(*fret);     for (j=1;j<=n;j++) {
     ibig=0;       xi[j] *= xmin;
     del=0.0;       p[j] += xi[j];
     last_time=curr_time;    }
     (void) gettimeofday(&curr_time,&tzp);    free_vector(xicom,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);    free_vector(pcom,1,n);
     /*    fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);  }
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);  
     */  char *asc_diff_time(long time_sec, char ascdiff[])
    for (i=1;i<=n;i++) {  {
       printf(" %d %.12f",i, p[i]);    long sec_left, days, hours, minutes;
       fprintf(ficlog," %d %.12lf",i, p[i]);    days = (time_sec) / (60*60*24);
       fprintf(ficrespow," %.12lf", p[i]);    sec_left = (time_sec) % (60*60*24);
     }    hours = (sec_left) / (60*60) ;
     printf("\n");    sec_left = (sec_left) %(60*60);
     fprintf(ficlog,"\n");    minutes = (sec_left) /60;
     fprintf(ficrespow,"\n");fflush(ficrespow);    sec_left = (sec_left) % (60);
     if(*iter <=3){    sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
       tm = *localtime(&curr_time.tv_sec);    return ascdiff;
       strcpy(strcurr,asctime(&tm));  }
 /*       asctime_r(&tm,strcurr); */  
       forecast_time=curr_time;   /*************** powell ************************/
       itmp = strlen(strcurr);  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */              double (*func)(double []))
         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);    void linmin(double p[], double xi[], int n, double *fret,
       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);                double (*func)(double []));
       for(niterf=10;niterf<=30;niterf+=10){    int i,ibig,j;
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);    double del,t,*pt,*ptt,*xit;
         tmf = *localtime(&forecast_time.tv_sec);    double fp,fptt;
 /*      asctime_r(&tmf,strfor); */    double *xits;
         strcpy(strfor,asctime(&tmf));    int niterf, itmp;
         itmp = strlen(strfor);  
         if(strfor[itmp-1]=='\n')    pt=vector(1,n);
         strfor[itmp-1]='\0';    ptt=vector(1,n);
         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);    xit=vector(1,n);
         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);    xits=vector(1,n);
       }    *fret=(*func)(p);
     }    for (j=1;j<=n;j++) pt[j]=p[j];
     for (i=1;i<=n;i++) {     for (*iter=1;;++(*iter)) {
       for (j=1;j<=n;j++) xit[j]=xi[j][i];       fp=(*fret);
       fptt=(*fret);       ibig=0;
 #ifdef DEBUG      del=0.0;
       printf("fret=%lf \n",*fret);      last_time=curr_time;
       fprintf(ficlog,"fret=%lf \n",*fret);      (void) gettimeofday(&curr_time,&tzp);
 #endif      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);
       printf("%d",i);fflush(stdout);      fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
       fprintf(ficlog,"%d",i);fflush(ficlog);  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
       linmin(p,xit,n,fret,func);      for (i=1;i<=n;i++) {
       if (fabs(fptt-(*fret)) > del) {         printf(" %d %.12f",i, p[i]);
         del=fabs(fptt-(*fret));         fprintf(ficlog," %d %.12lf",i, p[i]);
         ibig=i;         fprintf(ficrespow," %.12lf", p[i]);
       }       }
 #ifdef DEBUG      printf("\n");
       printf("%d %.12e",i,(*fret));      fprintf(ficlog,"\n");
       fprintf(ficlog,"%d %.12e",i,(*fret));      fprintf(ficrespow,"\n");fflush(ficrespow);
       for (j=1;j<=n;j++) {      if(*iter <=3){
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);        tm = *localtime(&curr_time.tv_sec);
         printf(" x(%d)=%.12e",j,xit[j]);        strcpy(strcurr,asctime(&tm));
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);  /*       asctime_r(&tm,strcurr); */
       }        forecast_time=curr_time;
       for(j=1;j<=n;j++) {        itmp = strlen(strcurr);
         printf(" p=%.12e",p[j]);        if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
         fprintf(ficlog," p=%.12e",p[j]);          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);
       printf("\n");        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       fprintf(ficlog,"\n");        for(niterf=10;niterf<=30;niterf+=10){
 #endif          forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
     }           tmf = *localtime(&forecast_time.tv_sec);
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {  /*      asctime_r(&tmf,strfor); */
 #ifdef DEBUG          strcpy(strfor,asctime(&tmf));
       int k[2],l;          itmp = strlen(strfor);
       k[0]=1;          if(strfor[itmp-1]=='\n')
       k[1]=-1;          strfor[itmp-1]='\0';
       printf("Max: %.12e",(*func)(p));          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,"Max: %.12e",(*func)(p));          fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
       for (j=1;j<=n;j++) {        }
         printf(" %.12e",p[j]);      }
         fprintf(ficlog," %.12e",p[j]);      for (i=1;i<=n;i++) {
       }        for (j=1;j<=n;j++) xit[j]=xi[j][i];
       printf("\n");        fptt=(*fret);
       fprintf(ficlog,"\n");  #ifdef DEBUG
       for(l=0;l<=1;l++) {        printf("fret=%lf \n",*fret);
         for (j=1;j<=n;j++) {        fprintf(ficlog,"fret=%lf \n",*fret);
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];  #endif
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        printf("%d",i);fflush(stdout);
           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,"%d",i);fflush(ficlog);
         }        linmin(p,xit,n,fret,func);
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        if (fabs(fptt-(*fret)) > del) {
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));          del=fabs(fptt-(*fret));
       }          ibig=i;
 #endif        }
   #ifdef DEBUG
         printf("%d %.12e",i,(*fret));
       free_vector(xit,1,n);         fprintf(ficlog,"%d %.12e",i,(*fret));
       free_vector(xits,1,n);         for (j=1;j<=n;j++) {
       free_vector(ptt,1,n);           xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
       free_vector(pt,1,n);           printf(" x(%d)=%.12e",j,xit[j]);
       return;           fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
     }         }
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");         for(j=1;j<=n;j++) {
     for (j=1;j<=n;j++) {           printf(" p=%.12e",p[j]);
       ptt[j]=2.0*p[j]-pt[j];           fprintf(ficlog," p=%.12e",p[j]);
       xit[j]=p[j]-pt[j];         }
       pt[j]=p[j];         printf("\n");
     }         fprintf(ficlog,"\n");
     fptt=(*func)(ptt);   #endif
     if (fptt < fp) {       }
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);       if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
       if (t < 0.0) {   #ifdef DEBUG
         linmin(p,xit,n,fret,func);         int k[2],l;
         for (j=1;j<=n;j++) {         k[0]=1;
           xi[j][ibig]=xi[j][n];         k[1]=-1;
           xi[j][n]=xit[j];         printf("Max: %.12e",(*func)(p));
         }        fprintf(ficlog,"Max: %.12e",(*func)(p));
 #ifdef DEBUG        for (j=1;j<=n;j++) {
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);          printf(" %.12e",p[j]);
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);          fprintf(ficlog," %.12e",p[j]);
         for(j=1;j<=n;j++){        }
           printf(" %.12e",xit[j]);        printf("\n");
           fprintf(ficlog," %.12e",xit[j]);        fprintf(ficlog,"\n");
         }        for(l=0;l<=1;l++) {
         printf("\n");          for (j=1;j<=n;j++) {
         fprintf(ficlog,"\n");            ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 #endif            printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
       }            fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
     }           }
   }           printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 }           fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
         }
 /**** Prevalence limit (stable or period prevalence)  ****************/  #endif
   
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)  
 {        free_vector(xit,1,n);
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit        free_vector(xits,1,n);
      matrix by transitions matrix until convergence is reached */        free_vector(ptt,1,n);
         free_vector(pt,1,n);
   int i, ii,j,k;        return;
   double min, max, maxmin, maxmax,sumnew=0.;      }
   double **matprod2();      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
   double **out, cov[NCOVMAX], **pmij();      for (j=1;j<=n;j++) {
   double **newm;        ptt[j]=2.0*p[j]-pt[j];
   double agefin, delaymax=50 ; /* Max number of years to converge */        xit[j]=p[j]-pt[j];
         pt[j]=p[j];
   for (ii=1;ii<=nlstate+ndeath;ii++)      }
     for (j=1;j<=nlstate+ndeath;j++){      fptt=(*func)(ptt);
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);      if (fptt < fp) {
     }        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
         if (t < 0.0) {
    cov[1]=1.;          linmin(p,xit,n,fret,func);
            for (j=1;j<=n;j++) {
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */            xi[j][ibig]=xi[j][n];
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){            xi[j][n]=xit[j];
     newm=savm;          }
     /* Covariates have to be included here again */  #ifdef DEBUG
      cov[2]=agefin;          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
             fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
       for (k=1; k<=cptcovn;k++) {          for(j=1;j<=n;j++){
         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];            printf(" %.12e",xit[j]);
         /*      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]]);*/            fprintf(ficlog," %.12e",xit[j]);
       }          }
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          printf("\n");
       for (k=1; k<=cptcovprod;k++)          fprintf(ficlog,"\n");
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];  #endif
         }
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/      }
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/    }
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/  }
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);  
   /**** Prevalence limit (stable or period prevalence)  ****************/
     savm=oldm;  
     oldm=newm;  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
     maxmax=0.;  {
     for(j=1;j<=nlstate;j++){    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
       min=1.;       matrix by transitions matrix until convergence is reached */
       max=0.;  
       for(i=1; i<=nlstate; i++) {    int i, ii,j,k;
         sumnew=0;    double min, max, maxmin, maxmax,sumnew=0.;
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];    double **matprod2();
         prlim[i][j]= newm[i][j]/(1-sumnew);    double **out, cov[NCOVMAX], **pmij();
         max=FMAX(max,prlim[i][j]);    double **newm;
         min=FMIN(min,prlim[i][j]);    double agefin, delaymax=50 ; /* Max number of years to converge */
       }  
       maxmin=max-min;    for (ii=1;ii<=nlstate+ndeath;ii++)
       maxmax=FMAX(maxmax,maxmin);      for (j=1;j<=nlstate+ndeath;j++){
     }        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     if(maxmax < ftolpl){      }
       return prlim;  
     }     cov[1]=1.;
   }   
 }   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
     for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 /*************** transition probabilities ***************/       newm=savm;
       /* Covariates have to be included here again */
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )       cov[2]=agefin;
 {   
   double s1, s2;        for (k=1; k<=cptcovn;k++) {
   /*double t34;*/          cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
   int i,j,j1, nc, ii, jj;          /*      printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
         }
     for(i=1; i<= nlstate; i++){        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
       for(j=1; j<i;j++){        for (k=1; k<=cptcovprod;k++)
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
           /*s2 += param[i][j][nc]*cov[nc];*/  
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
         }        /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
         ps[i][j]=s2;      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */  
       }      savm=oldm;
       for(j=i+1; j<=nlstate+ndeath;j++){      oldm=newm;
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){      maxmax=0.;
           s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];      for(j=1;j<=nlstate;j++){
 /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */        min=1.;
         }        max=0.;
         ps[i][j]=s2;        for(i=1; i<=nlstate; i++) {
       }          sumnew=0;
     }          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
     /*ps[3][2]=1;*/          prlim[i][j]= newm[i][j]/(1-sumnew);
               max=FMAX(max,prlim[i][j]);
     for(i=1; i<= nlstate; i++){          min=FMIN(min,prlim[i][j]);
       s1=0;        }
       for(j=1; j<i; j++)        maxmin=max-min;
         s1+=exp(ps[i][j]);        maxmax=FMAX(maxmax,maxmin);
       for(j=i+1; j<=nlstate+ndeath; j++)      }
         s1+=exp(ps[i][j]);      if(maxmax < ftolpl){
       ps[i][i]=1./(s1+1.);        return prlim;
       for(j=1; j<i; j++)      }
         ps[i][j]= exp(ps[i][j])*ps[i][i];    }
       for(j=i+1; j<=nlstate+ndeath; j++)  }
         ps[i][j]= exp(ps[i][j])*ps[i][i];  
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */  /*************** transition probabilities ***************/
     } /* end i */  
       double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){  {
       for(jj=1; jj<= nlstate+ndeath; jj++){    double s1, s2;
         ps[ii][jj]=0;    /*double t34;*/
         ps[ii][ii]=1;    int i,j,j1, nc, ii, jj;
       }  
     }      for(i=1; i<= nlstate; i++){
             for(j=1; j<i;j++){
           for (nc=1, s2=0.;nc <=ncovmodel; nc++){
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */            /*s2 += param[i][j][nc]*cov[nc];*/
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
 /*         printf("ddd %lf ",ps[ii][jj]); */  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
 /*       } */          }
 /*       printf("\n "); */          ps[i][j]=s2;
 /*        } */  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
 /*        printf("\n ");printf("%lf ",cov[2]); */        }
        /*        for(j=i+1; j<=nlstate+ndeath;j++){
       for(i=1; i<= npar; i++) printf("%f ",x[i]);          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
       goto end;*/            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
     return ps;  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
 }          }
           ps[i][j]=s2;
 /**************** Product of 2 matrices ******************/        }
       }
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)      /*ps[3][2]=1;*/
 {     
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times      for(i=1; i<= nlstate; i++){
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */        s1=0;
   /* in, b, out are matrice of pointers which should have been initialized         for(j=1; j<i; j++)
      before: only the contents of out is modified. The function returns          s1+=exp(ps[i][j]);
      a pointer to pointers identical to out */        for(j=i+1; j<=nlstate+ndeath; j++)
   long i, j, k;          s1+=exp(ps[i][j]);
   for(i=nrl; i<= nrh; i++)        ps[i][i]=1./(s1+1.);
     for(k=ncolol; k<=ncoloh; k++)        for(j=1; j<i; j++)
       for(j=ncl,out[i][k]=0.; j<=nch; j++)          ps[i][j]= exp(ps[i][j])*ps[i][i];
         out[i][k] +=in[i][j]*b[j][k];        for(j=i+1; j<=nlstate+ndeath; j++)
           ps[i][j]= exp(ps[i][j])*ps[i][i];
   return out;        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 }      } /* end i */
      
       for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 /************* Higher Matrix Product ***************/        for(jj=1; jj<= nlstate+ndeath; jj++){
           ps[ii][jj]=0;
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )          ps[ii][ii]=1;
 {        }
   /* Computes the transition matrix starting at age 'age' over       }
      'nhstepm*hstepm*stepm' months (i.e. until     
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying   
      nhstepm*hstepm matrices.   /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step   /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
      (typically every 2 years instead of every month which is too big   /*         printf("ddd %lf ",ps[ii][jj]); */
      for the memory).  /*       } */
      Model is determined by parameters x and covariates have to be   /*       printf("\n "); */
      included manually here.   /*        } */
   /*        printf("\n ");printf("%lf ",cov[2]); */
      */         /*
         for(i=1; i<= npar; i++) printf("%f ",x[i]);
   int i, j, d, h, k;        goto end;*/
   double **out, cov[NCOVMAX];      return ps;
   double **newm;  }
   
   /* Hstepm could be zero and should return the unit matrix */  /**************** Product of 2 matrices ******************/
   for (i=1;i<=nlstate+ndeath;i++)  
     for (j=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)
       oldm[i][j]=(i==j ? 1.0 : 0.0);  {
       po[i][j][0]=(i==j ? 1.0 : 0.0);    /* 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(...) */
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */    /* in, b, out are matrice of pointers which should have been initialized
   for(h=1; h <=nhstepm; h++){       before: only the contents of out is modified. The function returns
     for(d=1; d <=hstepm; d++){       a pointer to pointers identical to out */
       newm=savm;    long i, j, k;
       /* Covariates have to be included here again */    for(i=nrl; i<= nrh; i++)
       cov[1]=1.;      for(k=ncolol; k<=ncoloh; k++)
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;        for(j=ncl,out[i][k]=0.; j<=nch; j++)
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];          out[i][k] +=in[i][j]*b[j][k];
       for (k=1; k<=cptcovage;k++)  
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];    return out;
       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]]];  
   
   /************* Higher Matrix Product ***************/
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/  
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/  double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,   {
                    pmij(pmmij,cov,ncovmodel,x,nlstate));    /* Computes the transition matrix starting at age 'age' over
       savm=oldm;       'nhstepm*hstepm*stepm' months (i.e. until
       oldm=newm;       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
     }       nhstepm*hstepm matrices.
     for(i=1; i<=nlstate+ndeath; i++)       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
       for(j=1;j<=nlstate+ndeath;j++) {       (typically every 2 years instead of every month which is too big
         po[i][j][h]=newm[i][j];       for the memory).
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);       Model is determined by parameters x and covariates have to be
          */       included manually here.
       }  
   } /* end h */       */
   return po;  
 }    int i, j, d, h, k;
     double **out, cov[NCOVMAX];
     double **newm;
 /*************** log-likelihood *************/  
 double func( double *x)    /* Hstepm could be zero and should return the unit matrix */
 {    for (i=1;i<=nlstate+ndeath;i++)
   int i, ii, j, k, mi, d, kk;      for (j=1;j<=nlstate+ndeath;j++){
   double l, ll[NLSTATEMAX], cov[NCOVMAX];        oldm[i][j]=(i==j ? 1.0 : 0.0);
   double **out;        po[i][j][0]=(i==j ? 1.0 : 0.0);
   double sw; /* Sum of weights */      }
   double lli; /* Individual log likelihood */    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
   int s1, s2;    for(h=1; h <=nhstepm; h++){
   double bbh, survp;      for(d=1; d <=hstepm; d++){
   long ipmx;        newm=savm;
   /*extern weight */        /* Covariates have to be included here again */
   /* We are differentiating ll according to initial status */        cov[1]=1.;
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
   /*for(i=1;i<imx;i++)         for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
     printf(" %d\n",s[4][i]);        for (k=1; k<=cptcovage;k++)
   */          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
   cov[1]=1.;        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(k=1; k<=nlstate; k++) ll[k]=0.;  
   
   if(mle==1){        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
       for(mi=1; mi<= wav[i]-1; mi++){                     pmij(pmmij,cov,ncovmodel,x,nlstate));
         for (ii=1;ii<=nlstate+ndeath;ii++)        savm=oldm;
           for (j=1;j<=nlstate+ndeath;j++){        oldm=newm;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);      }
             savm[ii][j]=(ii==j ? 1.0 : 0.0);      for(i=1; i<=nlstate+ndeath; i++)
           }        for(j=1;j<=nlstate+ndeath;j++) {
         for(d=0; d<dh[mi][i]; d++){          po[i][j][h]=newm[i][j];
           newm=savm;          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;           */
           for (kk=1; kk<=cptcovage;kk++) {        }
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    } /* end h */
           }    return po;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,  }
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));  
           savm=oldm;  
           oldm=newm;  /*************** log-likelihood *************/
         } /* end mult */  double func( double *x)
         {
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */    int i, ii, j, k, mi, d, kk;
         /* But now since version 0.9 we anticipate for bias at large stepm.    double l, ll[NLSTATEMAX], cov[NCOVMAX];
          * If stepm is larger than one month (smallest stepm) and if the exact delay     double **out;
          * (in months) between two waves is not a multiple of stepm, we rounded to     double sw; /* Sum of weights */
          * the nearest (and in case of equal distance, to the lowest) interval but now    double lli; /* Individual log likelihood */
          * we keep into memory the bias bh[mi][i] and also the previous matrix product    int s1, s2;
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the    double bbh, survp;
          * probability in order to take into account the bias as a fraction of the way    long ipmx;
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies    /*extern weight */
          * -stepm/2 to stepm/2 .    /* We are differentiating ll according to initial status */
          * For stepm=1 the results are the same as for previous versions of Imach.    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
          * For stepm > 1 the results are less biased than in previous versions.     /*for(i=1;i<imx;i++)
          */      printf(" %d\n",s[4][i]);
         s1=s[mw[mi][i]][i];    */
         s2=s[mw[mi+1][i]][i];    cov[1]=1.;
         bbh=(double)bh[mi][i]/(double)stepm;   
         /* bias bh is positive if real duration    for(k=1; k<=nlstate; k++) ll[k]=0.;
          * is higher than the multiple of stepm and negative otherwise.  
          */    if(mle==1){
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         if( s2 > nlstate){         for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           /* i.e. if s2 is a death state and if the date of death is known         for(mi=1; mi<= wav[i]-1; mi++){
              then the contribution to the likelihood is the probability to           for (ii=1;ii<=nlstate+ndeath;ii++)
              die between last step unit time and current  step unit time,             for (j=1;j<=nlstate+ndeath;j++){
              which is also equal to probability to die before dh               oldm[ii][j]=(ii==j ? 1.0 : 0.0);
              minus probability to die before dh-stepm .               savm[ii][j]=(ii==j ? 1.0 : 0.0);
              In version up to 0.92 likelihood was computed            }
         as if date of death was unknown. Death was treated as any other          for(d=0; d<dh[mi][i]; d++){
         health state: the date of the interview describes the actual state            newm=savm;
         and not the date of a change in health state. The former idea was            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         to consider that at each interview the state was recorded            for (kk=1; kk<=cptcovage;kk++) {
         (healthy, disable or death) and IMaCh was corrected; but when we              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         introduced the exact date of death then we should have modified            }
         the contribution of an exact death to the likelihood. This new            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         contribution is smaller and very dependent of the step unit                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         stepm. It is no more the probability to die between last interview            savm=oldm;
         and month of death but the probability to survive from last            oldm=newm;
         interview up to one month before death multiplied by the          } /* end mult */
         probability to die within a month. Thanks to Chris       
         Jackson for correcting this bug.  Former versions increased          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
         mortality artificially. The bad side is that we add another loop          /* But now since version 0.9 we anticipate for bias at large stepm.
         which slows down the processing. The difference can be up to 10%           * If stepm is larger than one month (smallest stepm) and if the exact delay
         lower mortality.           * (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
           lli=log(out[s1][s2] - savm[s1][s2]);           * 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
            * probability in order to take into account the bias as a fraction of the way
         } else if  (s2==-2) {           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
           for (j=1,survp=0. ; j<=nlstate; j++)            * -stepm/2 to stepm/2 .
             survp += out[s1][j];           * For stepm=1 the results are the same as for previous versions of Imach.
           lli= log(survp);           * For stepm > 1 the results are less biased than in previous versions.
         }           */
                   s1=s[mw[mi][i]][i];
 /*      else if  (s2==-4) { */          s2=s[mw[mi+1][i]][i];
 /*        for (j=3,survp=0. ; j<=nlstate; j++)  */          bbh=(double)bh[mi][i]/(double)stepm;
 /*          survp += out[s1][j]; */          /* bias bh is positive if real duration
 /*        lli= survp; */           * 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==-5) { */          if( s2 > nlstate){
 /*        for (j=1,survp=0. ; j<=2; j++)  */            /* i.e. if s2 is a death state and if the date of death is known
 /*          survp += out[s1][j]; */               then the contribution to the likelihood is the probability to
 /*        lli= survp; */               die between last step unit time and current  step unit time,
 /*      } */               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{          as if date of death was unknown. Death was treated as any other
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */          health state: the date of the interview describes the actual state
           /*  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 */          and not the date of a change in health state. The former idea was
         }           to consider that at each interview the state was recorded
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/          (healthy, disable or death) and IMaCh was corrected; but when we
         /*if(lli ==000.0)*/          introduced the exact date of death then we should have modified
         /*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); */          the contribution of an exact death to the likelihood. This new
         ipmx +=1;          contribution is smaller and very dependent of the step unit
         sw += weight[i];          stepm. It is no more the probability to die between last interview
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          and month of death but the probability to survive from last
       } /* end of wave */          interview up to one month before death multiplied by the
     } /* end of individual */          probability to die within a month. Thanks to Chris
   }  else if(mle==2){          Jackson for correcting this bug.  Former versions increased
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          mortality artificially. The bad side is that we add another loop
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          which slows down the processing. The difference can be up to 10%
       for(mi=1; mi<= wav[i]-1; mi++){          lower mortality.
         for (ii=1;ii<=nlstate+ndeath;ii++)            */
           for (j=1;j<=nlstate+ndeath;j++){            lli=log(out[s1][s2] - savm[s1][s2]);
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);  
             savm[ii][j]=(ii==j ? 1.0 : 0.0);  
           }          } else if  (s2==-2) {
         for(d=0; d<=dh[mi][i]; d++){            for (j=1,survp=0. ; j<=nlstate; j++)
           newm=savm;              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;            /*survp += out[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 if  (s2==-4) {
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            for (j=3,survp=0. ; j<=nlstate; j++)  
           savm=oldm;              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           oldm=newm;            lli= log(survp);
         } /* end mult */          }
         
         s1=s[mw[mi][i]][i];          else if  (s2==-5) {
         s2=s[mw[mi+1][i]][i];            for (j=1,survp=0. ; j<=2; j++)  
         bbh=(double)bh[mi][i]/(double)stepm;               survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */            lli= log(survp);
         ipmx +=1;          }
         sw += weight[i];         
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          else{
       } /* end of wave */            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
     } /* end of individual */            /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
   }  else if(mle==3){  /* exponential inter-extrapolation */          }
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          /*if(lli ==000.0)*/
       for(mi=1; mi<= wav[i]-1; mi++){          /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
         for (ii=1;ii<=nlstate+ndeath;ii++)          ipmx +=1;
           for (j=1;j<=nlstate+ndeath;j++){          sw += weight[i];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);        } /* end of wave */
           }      } /* end of individual */
         for(d=0; d<dh[mi][i]; d++){    }  else if(mle==2){
           newm=savm;      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           for (kk=1; kk<=cptcovage;kk++) {        for(mi=1; mi<= wav[i]-1; mi++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          for (ii=1;ii<=nlstate+ndeath;ii++)
           }            for (j=1;j<=nlstate+ndeath;j++){
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           savm=oldm;            }
           oldm=newm;          for(d=0; d<=dh[mi][i]; d++){
         } /* end mult */            newm=savm;
                   cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         s1=s[mw[mi][i]][i];            for (kk=1; kk<=cptcovage;kk++) {
         s2=s[mw[mi+1][i]][i];              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         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 */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         ipmx +=1;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         sw += weight[i];            savm=oldm;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            oldm=newm;
       } /* end of wave */          } /* end mult */
     } /* end of individual */       
   }else if (mle==4){  /* ml=4 no inter-extrapolation */          s1=s[mw[mi][i]][i];
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          s2=s[mw[mi+1][i]][i];
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          bbh=(double)bh[mi][i]/(double)stepm;
       for(mi=1; mi<= wav[i]-1; mi++){          lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
         for (ii=1;ii<=nlstate+ndeath;ii++)          ipmx +=1;
           for (j=1;j<=nlstate+ndeath;j++){          sw += weight[i];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);        } /* end of wave */
           }      } /* end of individual */
         for(d=0; d<dh[mi][i]; d++){    }  else if(mle==3){  /* exponential inter-extrapolation */
           newm=savm;      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           for (kk=1; kk<=cptcovage;kk++) {        for(mi=1; mi<= wav[i]-1; mi++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          for (ii=1;ii<=nlstate+ndeath;ii++)
           }            for (j=1;j<=nlstate+ndeath;j++){
                       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,              savm[ii][j]=(ii==j ? 1.0 : 0.0);
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            }
           savm=oldm;          for(d=0; d<dh[mi][i]; d++){
           oldm=newm;            newm=savm;
         } /* end mult */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   for (kk=1; kk<=cptcovage;kk++) {
         s1=s[mw[mi][i]][i];              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         s2=s[mw[mi+1][i]][i];            }
         if( s2 > nlstate){             out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
           lli=log(out[s1][s2] - savm[s1][s2]);                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         }else{            savm=oldm;
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */            oldm=newm;
         }          } /* end mult */
         ipmx +=1;       
         sw += weight[i];          s1=s[mw[mi][i]][i];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          s2=s[mw[mi+1][i]][i];
 /*      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]); */          bbh=(double)bh[mi][i]/(double)stepm;
       } /* end of wave */          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 */
     } /* end of individual */          ipmx +=1;
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */          sw += weight[i];
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];        } /* end of wave */
       for(mi=1; mi<= wav[i]-1; mi++){      } /* end of individual */
         for (ii=1;ii<=nlstate+ndeath;ii++)    }else if (mle==4){  /* ml=4 no inter-extrapolation */
           for (j=1;j<=nlstate+ndeath;j++){      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
             savm[ii][j]=(ii==j ? 1.0 : 0.0);        for(mi=1; mi<= wav[i]-1; mi++){
           }          for (ii=1;ii<=nlstate+ndeath;ii++)
         for(d=0; d<dh[mi][i]; d++){            for (j=1;j<=nlstate+ndeath;j++){
           newm=savm;              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           for (kk=1; kk<=cptcovage;kk++) {            }
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          for(d=0; d<dh[mi][i]; d++){
           }            newm=savm;
                     cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,            for (kk=1; kk<=cptcovage;kk++) {
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
           savm=oldm;            }
           oldm=newm;         
         } /* end mult */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                                1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         s1=s[mw[mi][i]][i];            savm=oldm;
         s2=s[mw[mi+1][i]][i];            oldm=newm;
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */          } /* end mult */
         ipmx +=1;       
         sw += weight[i];          s1=s[mw[mi][i]][i];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          s2=s[mw[mi+1][i]][i];
         /*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( s2 > nlstate){
       } /* end of wave */            lli=log(out[s1][s2] - savm[s1][s2]);
     } /* end of individual */          }else{
   } /* End of if */            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];          }
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */          ipmx +=1;
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          sw += weight[i];
   return -l;          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]); */
         } /* end of wave */
 /*************** log-likelihood *************/      } /* end of individual */
 double funcone( double *x)    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 {      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
   /* Same as likeli but slower because of a lot of printf and if */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
   int i, ii, j, k, mi, d, kk;        for(mi=1; mi<= wav[i]-1; mi++){
   double l, ll[NLSTATEMAX], cov[NCOVMAX];          for (ii=1;ii<=nlstate+ndeath;ii++)
   double **out;            for (j=1;j<=nlstate+ndeath;j++){
   double lli; /* Individual log likelihood */              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
   double llt;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
   int s1, s2;            }
   double bbh, survp;          for(d=0; d<dh[mi][i]; d++){
   /*extern weight */            newm=savm;
   /* We are differentiating ll according to initial status */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/            for (kk=1; kk<=cptcovage;kk++) {
   /*for(i=1;i<imx;i++)               cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     printf(" %d\n",s[4][i]);            }
   */         
   cov[1]=1.;            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
   for(k=1; k<=nlstate; k++) ll[k]=0.;            savm=oldm;
             oldm=newm;
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){          } /* end mult */
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];       
     for(mi=1; mi<= wav[i]-1; mi++){          s1=s[mw[mi][i]][i];
       for (ii=1;ii<=nlstate+ndeath;ii++)          s2=s[mw[mi+1][i]][i];
         for (j=1;j<=nlstate+ndeath;j++){          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);          ipmx +=1;
           savm[ii][j]=(ii==j ? 1.0 : 0.0);          sw += weight[i];
         }          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       for(d=0; d<dh[mi][i]; d++){          /*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]);*/
         newm=savm;        } /* end of wave */
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;      } /* end of individual */
         for (kk=1; kk<=cptcovage;kk++) {    } /* End of if */
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
         }    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    return -l;
         savm=oldm;  }
         oldm=newm;  
       } /* end mult */  /*************** log-likelihood *************/
         double funcone( double *x)
       s1=s[mw[mi][i]][i];  {
       s2=s[mw[mi+1][i]][i];    /* Same as likeli but slower because of a lot of printf and if */
       bbh=(double)bh[mi][i]/(double)stepm;     int i, ii, j, k, mi, d, kk;
       /* bias is positive if real duration    double l, ll[NLSTATEMAX], cov[NCOVMAX];
        * is higher than the multiple of stepm and negative otherwise.    double **out;
        */    double lli; /* Individual log likelihood */
       if( s2 > nlstate && (mle <5) ){  /* Jackson */    double llt;
         lli=log(out[s1][s2] - savm[s1][s2]);    int s1, s2;
       } else if  (s2==-2) {    double bbh, survp;
         for (j=1,survp=0. ; j<=nlstate; j++)     /*extern weight */
           survp += out[s1][j];    /* We are differentiating ll according to initial status */
         lli= log(survp);    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
       }else if (mle==1){    /*for(i=1;i<imx;i++)
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */      printf(" %d\n",s[4][i]);
       } 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 */    cov[1]=1.;
       } else if(mle==3){  /* exponential inter-extrapolation */  
         lli= (savm[s1][s2]>(double)1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */    for(k=1; k<=nlstate; k++) ll[k]=0.;
       } else if (mle==4){  /* mle=4 no inter-extrapolation */  
         lli=log(out[s1][s2]); /* Original formula */    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         lli=log(out[s1][s2]); /* Original formula */      for(mi=1; mi<= wav[i]-1; mi++){
       } /* End of if */        for (ii=1;ii<=nlstate+ndeath;ii++)
       ipmx +=1;          for (j=1;j<=nlstate+ndeath;j++){
       sw += weight[i];            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            savm[ii][j]=(ii==j ? 1.0 : 0.0);
 /*       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){        for(d=0; d<dh[mi][i]; d++){
         fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\          newm=savm;
  %11.6f %11.6f %11.6f ", \          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],          for (kk=1; kk<=cptcovage;kk++) {
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){          }
           llt +=ll[k]*gipmx/gsw;          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         }          savm=oldm;
         fprintf(ficresilk," %10.6f\n", -llt);          oldm=newm;
       }        } /* end mult */
     } /* end of wave */       
   } /* end of individual */        s1=s[mw[mi][i]][i];
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];        s2=s[mw[mi+1][i]][i];
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */        bbh=(double)bh[mi][i]/(double)stepm;
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */        /* bias is positive if real duration
   if(globpr==0){ /* First time we count the contributions and weights */         * is higher than the multiple of stepm and negative otherwise.
     gipmx=ipmx;         */
     gsw=sw;        if( s2 > nlstate && (mle <5) ){  /* Jackson */
   }          lli=log(out[s1][s2] - savm[s1][s2]);
   return -l;        } else if  (s2==-2) {
 }          for (j=1,survp=0. ; j<=nlstate; j++)
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           lli= log(survp);
 /*************** function likelione ***********/        }else if (mle==1){
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 {        } else if(mle==2){
   /* This routine should help understanding what is done with           lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
      the selection of individuals/waves and        } else if(mle==3){  /* exponential inter-extrapolation */
      to check the exact contribution to the likelihood.          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 */
      Plotting could be done.        } else if (mle==4){  /* mle=4 no inter-extrapolation */
    */          lli=log(out[s1][s2]); /* Original formula */
   int k;        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
           lli=log(out[s1][s2]); /* Original formula */
   if(*globpri !=0){ /* Just counts and sums, no printings */        } /* End of if */
     strcpy(fileresilk,"ilk");         ipmx +=1;
     strcat(fileresilk,fileres);        sw += weight[i];
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
       printf("Problem with resultfile: %s\n", fileresilk);  /*       printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);        if(globpr){
     }          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
     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");   %11.6f %11.6f %11.6f ", \
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[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]); */                  2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
     for(k=1; k<=nlstate; k++)           for(k=1,llt=0.,l=0.; k<=nlstate; k++){
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);            llt +=ll[k]*gipmx/gsw;
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
   }          }
           fprintf(ficresilk," %10.6f\n", -llt);
   *fretone=(*funcone)(p);        }
   if(*globpri !=0){      } /* end of wave */
     fclose(ficresilk);    } /* end of individual */
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
     fflush(fichtm);     /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   }     l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
   return;    if(globpr==0){ /* First time we count the contributions and weights */
 }      gipmx=ipmx;
       gsw=sw;
     }
 /*********** Maximum Likelihood Estimation ***************/    return -l;
   }
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))  
 {  
   int i,j, iter;  /*************** function likelione ***********/
   double **xi;  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
   double fret;  {
   double fretone; /* Only one call to likelihood */    /* This routine should help understanding what is done with
   /*  char filerespow[FILENAMELENGTH];*/       the selection of individuals/waves and
   xi=matrix(1,npar,1,npar);       to check the exact contribution to the likelihood.
   for (i=1;i<=npar;i++)       Plotting could be done.
     for (j=1;j<=npar;j++)     */
       xi[i][j]=(i==j ? 1.0 : 0.0);    int k;
   printf("Powell\n");  fprintf(ficlog,"Powell\n");  
   strcpy(filerespow,"pow");     if(*globpri !=0){ /* Just counts and sums, no printings */
   strcat(filerespow,fileres);      strcpy(fileresilk,"ilk");
   if((ficrespow=fopen(filerespow,"w"))==NULL) {      strcat(fileresilk,fileres);
     printf("Problem with resultfile: %s\n", filerespow);      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);        printf("Problem with resultfile: %s\n", fileresilk);
   }        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
   fprintf(ficrespow,"# Powell\n# iter -2*LL");      }
   for (i=1;i<=nlstate;i++)      fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
     for(j=1;j<=nlstate+ndeath;j++)      fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,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]); */
   fprintf(ficrespow,"\n");      for(k=1; k<=nlstate; k++)
         fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
   powell(p,xi,npar,ftol,&iter,&fret,func);      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
     }
   free_matrix(xi,1,npar,1,npar);  
   fclose(ficrespow);    *fretone=(*funcone)(p);
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));    if(*globpri !=0){
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));      fclose(ficresilk);
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
       fflush(fichtm);
 }    }
     return;
 /**** Computes Hessian and covariance matrix ***/  }
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))  
 {  
   double  **a,**y,*x,pd;  /*********** Maximum Likelihood Estimation ***************/
   double **hess;  
   int i, j,jk;  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   int *indx;  {
     int i,j, iter;
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);    double **xi;
   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);    double fret;
   void lubksb(double **a, int npar, int *indx, double b[]) ;    double fretone; /* Only one call to likelihood */
   void ludcmp(double **a, int npar, int *indx, double *d) ;    /*  char filerespow[FILENAMELENGTH];*/
   double gompertz(double p[]);    xi=matrix(1,npar,1,npar);
   hess=matrix(1,npar,1,npar);    for (i=1;i<=npar;i++)
       for (j=1;j<=npar;j++)
   printf("\nCalculation of the hessian matrix. Wait...\n");        xi[i][j]=(i==j ? 1.0 : 0.0);
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");    printf("Powell\n");  fprintf(ficlog,"Powell\n");
   for (i=1;i<=npar;i++){    strcpy(filerespow,"pow");
     printf("%d",i);fflush(stdout);    strcat(filerespow,fileres);
     fprintf(ficlog,"%d",i);fflush(ficlog);    if((ficrespow=fopen(filerespow,"w"))==NULL) {
          printf("Problem with resultfile: %s\n", filerespow);
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
         }
     /*  printf(" %f ",p[i]);    fprintf(ficrespow,"# Powell\n# iter -2*LL");
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/    for (i=1;i<=nlstate;i++)
   }      for(j=1;j<=nlstate+ndeath;j++)
           if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   for (i=1;i<=npar;i++) {    fprintf(ficrespow,"\n");
     for (j=1;j<=npar;j++)  {  
       if (j>i) {     powell(p,xi,npar,ftol,&iter,&fret,func);
         printf(".%d%d",i,j);fflush(stdout);  
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);    free_matrix(xi,1,npar,1,npar);
         hess[i][j]=hessij(p,delti,i,j,func,npar);    fclose(ficrespow);
             printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
         hess[j][i]=hess[i][j];        fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
         /*printf(" %lf ",hess[i][j]);*/    fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
       }  
     }  }
   }  
   printf("\n");  /**** Computes Hessian and covariance matrix ***/
   fprintf(ficlog,"\n");  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
   {
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");    double  **a,**y,*x,pd;
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");    double **hess;
       int i, j,jk;
   a=matrix(1,npar,1,npar);    int *indx;
   y=matrix(1,npar,1,npar);  
   x=vector(1,npar);    double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
   indx=ivector(1,npar);    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
   for (i=1;i<=npar;i++)    void lubksb(double **a, int npar, int *indx, double b[]) ;
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];    void ludcmp(double **a, int npar, int *indx, double *d) ;
   ludcmp(a,npar,indx,&pd);    double gompertz(double p[]);
     hess=matrix(1,npar,1,npar);
   for (j=1;j<=npar;j++) {  
     for (i=1;i<=npar;i++) x[i]=0;    printf("\nCalculation of the hessian matrix. Wait...\n");
     x[j]=1;    fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
     lubksb(a,npar,indx,x);    for (i=1;i<=npar;i++){
     for (i=1;i<=npar;i++){       printf("%d",i);fflush(stdout);
       matcov[i][j]=x[i];      fprintf(ficlog,"%d",i);fflush(ficlog);
     }     
   }       hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
      
   printf("\n#Hessian matrix#\n");      /*  printf(" %f ",p[i]);
   fprintf(ficlog,"\n#Hessian matrix#\n");          printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
   for (i=1;i<=npar;i++) {     }
     for (j=1;j<=npar;j++) {    
       printf("%.3e ",hess[i][j]);    for (i=1;i<=npar;i++) {
       fprintf(ficlog,"%.3e ",hess[i][j]);      for (j=1;j<=npar;j++)  {
     }        if (j>i) {
     printf("\n");          printf(".%d%d",i,j);fflush(stdout);
     fprintf(ficlog,"\n");          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
   }          hess[i][j]=hessij(p,delti,i,j,func,npar);
          
   /* Recompute Inverse */          hess[j][i]=hess[i][j];    
   for (i=1;i<=npar;i++)          /*printf(" %lf ",hess[i][j]);*/
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];        }
   ludcmp(a,npar,indx,&pd);      }
     }
   /*  printf("\n#Hessian matrix recomputed#\n");    printf("\n");
     fprintf(ficlog,"\n");
   for (j=1;j<=npar;j++) {  
     for (i=1;i<=npar;i++) x[i]=0;    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
     x[j]=1;    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
     lubksb(a,npar,indx,x);   
     for (i=1;i<=npar;i++){     a=matrix(1,npar,1,npar);
       y[i][j]=x[i];    y=matrix(1,npar,1,npar);
       printf("%.3e ",y[i][j]);    x=vector(1,npar);
       fprintf(ficlog,"%.3e ",y[i][j]);    indx=ivector(1,npar);
     }    for (i=1;i<=npar;i++)
     printf("\n");      for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
     fprintf(ficlog,"\n");    ludcmp(a,npar,indx,&pd);
   }  
   */    for (j=1;j<=npar;j++) {
       for (i=1;i<=npar;i++) x[i]=0;
   free_matrix(a,1,npar,1,npar);      x[j]=1;
   free_matrix(y,1,npar,1,npar);      lubksb(a,npar,indx,x);
   free_vector(x,1,npar);      for (i=1;i<=npar;i++){
   free_ivector(indx,1,npar);        matcov[i][j]=x[i];
   free_matrix(hess,1,npar,1,npar);      }
     }
   
 }    printf("\n#Hessian matrix#\n");
     fprintf(ficlog,"\n#Hessian matrix#\n");
 /*************** hessian matrix ****************/    for (i=1;i<=npar;i++) {
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)      for (j=1;j<=npar;j++) {
 {        printf("%.3e ",hess[i][j]);
   int i;        fprintf(ficlog,"%.3e ",hess[i][j]);
   int l=1, lmax=20;      }
   double k1,k2;      printf("\n");
   double p2[NPARMAX+1];      fprintf(ficlog,"\n");
   double res;    }
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;  
   double fx;    /* Recompute Inverse */
   int k=0,kmax=10;    for (i=1;i<=npar;i++)
   double l1;      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
     ludcmp(a,npar,indx,&pd);
   fx=func(x);  
   for (i=1;i<=npar;i++) p2[i]=x[i];    /*  printf("\n#Hessian matrix recomputed#\n");
   for(l=0 ; l <=lmax; l++){  
     l1=pow(10,l);    for (j=1;j<=npar;j++) {
     delts=delt;      for (i=1;i<=npar;i++) x[i]=0;
     for(k=1 ; k <kmax; k=k+1){      x[j]=1;
       delt = delta*(l1*k);      lubksb(a,npar,indx,x);
       p2[theta]=x[theta] +delt;      for (i=1;i<=npar;i++){
       k1=func(p2)-fx;        y[i][j]=x[i];
       p2[theta]=x[theta]-delt;        printf("%.3e ",y[i][j]);
       k2=func(p2)-fx;        fprintf(ficlog,"%.3e ",y[i][j]);
       /*res= (k1-2.0*fx+k2)/delt/delt; */      }
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */      printf("\n");
             fprintf(ficlog,"\n");
 #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);    */
       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    free_matrix(a,1,npar,1,npar);
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */    free_matrix(y,1,npar,1,npar);
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){    free_vector(x,1,npar);
         k=kmax;    free_ivector(indx,1,npar);
       }    free_matrix(hess,1,npar,1,npar);
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */  
         k=kmax; l=lmax*10.;  
       }  }
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){   
         delts=delt;  /*************** hessian matrix ****************/
       }  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
     }  {
   }    int i;
   delti[theta]=delts;    int l=1, lmax=20;
   return res;     double k1,k2;
       double p2[NPARMAX+1];
 }    double res;
     double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)    double fx;
 {    int k=0,kmax=10;
   int i;    double l1;
   int l=1, l1, lmax=20;  
   double k1,k2,k3,k4,res,fx;    fx=func(x);
   double p2[NPARMAX+1];    for (i=1;i<=npar;i++) p2[i]=x[i];
   int k;    for(l=0 ; l <=lmax; l++){
       l1=pow(10,l);
   fx=func(x);      delts=delt;
   for (k=1; k<=2; k++) {      for(k=1 ; k <kmax; k=k+1){
     for (i=1;i<=npar;i++) p2[i]=x[i];        delt = delta*(l1*k);
     p2[thetai]=x[thetai]+delti[thetai]/k;        p2[theta]=x[theta] +delt;
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;        k1=func(p2)-fx;
     k1=func(p2)-fx;        p2[theta]=x[theta]-delt;
           k2=func(p2)-fx;
     p2[thetai]=x[thetai]+delti[thetai]/k;        /*res= (k1-2.0*fx+k2)/delt/delt; */
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;        res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
     k2=func(p2)-fx;       
     #ifdef DEBUG
     p2[thetai]=x[thetai]-delti[thetai]/k;        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);
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;        fprintf(ficlog,"%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
     k3=func(p2)-fx;  #endif
           /*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;
     k4=func(p2)-fx;        }
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */        else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 #ifdef DEBUG          k=kmax; l=lmax*10.;
     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);        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
 #endif          delts=delt;
   }        }
   return res;      }
 }    }
     delti[theta]=delts;
 /************** Inverse of matrix **************/    return res;
 void ludcmp(double **a, int n, int *indx, double *d)    
 {   }
   int i,imax,j,k;   
   double big,dum,sum,temp;   double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
   double *vv;   {
      int i;
   vv=vector(1,n);     int l=1, l1, lmax=20;
   *d=1.0;     double k1,k2,k3,k4,res,fx;
   for (i=1;i<=n;i++) {     double p2[NPARMAX+1];
     big=0.0;     int k;
     for (j=1;j<=n;j++)   
       if ((temp=fabs(a[i][j])) > big) big=temp;     fx=func(x);
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");     for (k=1; k<=2; k++) {
     vv[i]=1.0/big;       for (i=1;i<=npar;i++) p2[i]=x[i];
   }       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++) {       k1=func(p2)-fx;
       sum=a[i][j];    
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];       p2[thetai]=x[thetai]+delti[thetai]/k;
       a[i][j]=sum;       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
     }       k2=func(p2)-fx;
     big=0.0;    
     for (i=j;i<=n;i++) {       p2[thetai]=x[thetai]-delti[thetai]/k;
       sum=a[i][j];       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
       for (k=1;k<j;k++)       k3=func(p2)-fx;
         sum -= a[i][k]*a[k][j];    
       a[i][j]=sum;       p2[thetai]=x[thetai]-delti[thetai]/k;
       if ( (dum=vv[i]*fabs(sum)) >= big) {       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
         big=dum;       k4=func(p2)-fx;
         imax=i;       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
       }   #ifdef DEBUG
     }       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
     if (j != imax) {       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);
       for (k=1;k<=n;k++) {   #endif
         dum=a[imax][k];     }
         a[imax][k]=a[j][k];     return res;
         a[j][k]=dum;   }
       }   
       *d = -(*d);   /************** Inverse of matrix **************/
       vv[imax]=vv[j];   void ludcmp(double **a, int n, int *indx, double *d)
     }   {
     indx[j]=imax;     int i,imax,j,k;
     if (a[j][j] == 0.0) a[j][j]=TINY;     double big,dum,sum,temp;
     if (j != n) {     double *vv;
       dum=1.0/(a[j][j]);    
       for (i=j+1;i<=n;i++) a[i][j] *= dum;     vv=vector(1,n);
     }     *d=1.0;
   }     for (i=1;i<=n;i++) {
   free_vector(vv,1,n);  /* Doesn't work */      big=0.0;
 ;      for (j=1;j<=n;j++)
 }         if ((temp=fabs(a[i][j])) > big) big=temp;
       if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
 void lubksb(double **a, int n, int *indx, double b[])       vv[i]=1.0/big;
 {     }
   int i,ii=0,ip,j;     for (j=1;j<=n;j++) {
   double sum;       for (i=1;i<j;i++) {
          sum=a[i][j];
   for (i=1;i<=n;i++) {         for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
     ip=indx[i];         a[i][j]=sum;
     sum=b[ip];       }
     b[ip]=b[i];       big=0.0;
     if (ii)       for (i=j;i<=n;i++) {
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];         sum=a[i][j];
     else if (sum) ii=i;         for (k=1;k<j;k++)
     b[i]=sum;           sum -= a[i][k]*a[k][j];
   }         a[i][j]=sum;
   for (i=n;i>=1;i--) {         if ( (dum=vv[i]*fabs(sum)) >= big) {
     sum=b[i];           big=dum;
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];           imax=i;
     b[i]=sum/a[i][i];         }
   }       }
 }       if (j != imax) {
         for (k=1;k<=n;k++) {
 void pstamp(FILE *fichier)          dum=a[imax][k];
 {          a[imax][k]=a[j][k];
   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);          a[j][k]=dum;
 }        }
         *d = -(*d);
 /************ Frequencies ********************/        vv[imax]=vv[j];
 void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])      }
 {  /* Some frequencies */      indx[j]=imax;
         if (a[j][j] == 0.0) a[j][j]=TINY;
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;      if (j != n) {
   int first;        dum=1.0/(a[j][j]);
   double ***freq; /* Frequencies */        for (i=j+1;i<=n;i++) a[i][j] *= dum;
   double *pp, **prop;      }
   double pos,posprop, k2, dateintsum=0,k2cpt=0;    }
   char fileresp[FILENAMELENGTH];    free_vector(vv,1,n);  /* Doesn't work */
     ;
   pp=vector(1,nlstate);  }
   prop=matrix(1,nlstate,iagemin,iagemax+3);  
   strcpy(fileresp,"p");  void lubksb(double **a, int n, int *indx, double b[])
   strcat(fileresp,fileres);  {
   if((ficresp=fopen(fileresp,"w"))==NULL) {    int i,ii=0,ip,j;
     printf("Problem with prevalence resultfile: %s\n", fileresp);    double sum;
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);   
     exit(0);    for (i=1;i<=n;i++) {
   }      ip=indx[i];
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);      sum=b[ip];
   j1=0;      b[ip]=b[i];
         if (ii)
   j=cptcoveff;        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
   if (cptcovn<1) {j=1;ncodemax[1]=1;}      else if (sum) ii=i;
       b[i]=sum;
   first=1;    }
     for (i=n;i>=1;i--) {
   for(k1=1; k1<=j;k1++){      sum=b[i];
     for(i1=1; i1<=ncodemax[k1];i1++){      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
       j1++;      b[i]=sum/a[i][i];
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    }
         scanf("%d", i);*/  }
       for (i=-5; i<=nlstate+ndeath; i++)    
         for (jk=-5; jk<=nlstate+ndeath; jk++)    void pstamp(FILE *fichier)
           for(m=iagemin; m <= iagemax+3; m++)  {
             freq[i][jk][m]=0;    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
   }
     for (i=1; i<=nlstate; i++)    
       for(m=iagemin; m <= iagemax+3; m++)  /************ Frequencies ********************/
         prop[i][m]=0;  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
         {  /* Some frequencies */
       dateintsum=0;   
       k2cpt=0;    int i, m, jk, k1,i1, j1, bool, z1,z2,j;
       for (i=1; i<=imx; i++) {    int first;
         bool=1;    double ***freq; /* Frequencies */
         if  (cptcovn>0) {    double *pp, **prop;
           for (z1=1; z1<=cptcoveff; z1++)     double pos,posprop, k2, dateintsum=0,k2cpt=0;
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     char fileresp[FILENAMELENGTH];
               bool=0;   
         }    pp=vector(1,nlstate);
         if (bool==1){    prop=matrix(1,nlstate,iagemin,iagemax+3);
           for(m=firstpass; m<=lastpass; m++){    strcpy(fileresp,"p");
             k2=anint[m][i]+(mint[m][i]/12.);    strcat(fileresp,fileres);
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/    if((ficresp=fopen(fileresp,"w"))==NULL) {
               if(agev[m][i]==0) agev[m][i]=iagemax+1;      printf("Problem with prevalence resultfile: %s\n", fileresp);
               if(agev[m][i]==1) agev[m][i]=iagemax+2;      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];      exit(0);
               if (m<lastpass) {    }
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];    freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];    j1=0;
               }   
                   j=cptcoveff;
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {    if (cptcovn<1) {j=1;ncodemax[1]=1;}
                 dateintsum=dateintsum+k2;  
                 k2cpt++;    first=1;
               }  
               /*}*/    for(k1=1; k1<=j;k1++){
           }      for(i1=1; i1<=ncodemax[k1];i1++){
         }        j1++;
       }        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                  scanf("%d", i);*/
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/        for (i=-5; i<=nlstate+ndeath; i++)  
       pstamp(ficresp);          for (jk=-5; jk<=nlstate+ndeath; jk++)  
       if  (cptcovn>0) {            for(m=iagemin; m <= iagemax+3; m++)
         fprintf(ficresp, "\n#********** Variable ");               freq[i][jk][m]=0;
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);  
         fprintf(ficresp, "**********\n#");      for (i=1; i<=nlstate; i++)  
       }        for(m=iagemin; m <= iagemax+3; m++)
       for(i=1; i<=nlstate;i++)           prop[i][m]=0;
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);       
       fprintf(ficresp, "\n");        dateintsum=0;
               k2cpt=0;
       for(i=iagemin; i <= iagemax+3; i++){        for (i=1; i<=imx; i++) {
         if(i==iagemax+3){          bool=1;
           fprintf(ficlog,"Total");          if  (cptcovn>0) {
         }else{            for (z1=1; z1<=cptcoveff; z1++)
           if(first==1){              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
             first=0;                bool=0;
             printf("See log file for details...\n");          }
           }          if (bool==1){
           fprintf(ficlog,"Age %d", i);            for(m=firstpass; m<=lastpass; m++){
         }              k2=anint[m][i]+(mint[m][i]/12.);
         for(jk=1; jk <=nlstate ; jk++){              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)                if(agev[m][i]==0) agev[m][i]=iagemax+1;
             pp[jk] += freq[jk][m][i];                 if(agev[m][i]==1) agev[m][i]=iagemax+2;
         }                if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
         for(jk=1; jk <=nlstate ; jk++){                if (m<lastpass) {
           for(m=-1, pos=0; m <=0 ; m++)                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
             pos += freq[jk][m][i];                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
           if(pp[jk]>=1.e-10){                }
             if(first==1){               
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
             }                  dateintsum=dateintsum+k2;
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);                  k2cpt++;
           }else{                }
             if(first==1)                /*}*/
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);            }
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);          }
           }        }
         }         
         /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
         for(jk=1; jk <=nlstate ; jk++){        pstamp(ficresp);
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)        if  (cptcovn>0) {
             pp[jk] += freq[jk][m][i];          fprintf(ficresp, "\n#********** Variable ");
         }                 for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){          fprintf(ficresp, "**********\n#");
           pos += pp[jk];        }
           posprop += prop[jk][i];        for(i=1; i<=nlstate;i++)
         }          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
         for(jk=1; jk <=nlstate ; jk++){        fprintf(ficresp, "\n");
           if(pos>=1.e-5){       
             if(first==1)        for(i=iagemin; i <= iagemax+3; i++){
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);          if(i==iagemax+3){
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);            fprintf(ficlog,"Total");
           }else{          }else{
             if(first==1)            if(first==1){
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);              first=0;
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);              printf("See log file for details...\n");
           }            }
           if( i <= iagemax){            fprintf(ficlog,"Age %d", i);
             if(pos>=1.e-5){          }
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);          for(jk=1; jk <=nlstate ; jk++){
               /*probs[i][jk][j1]= pp[jk]/pos;*/            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/              pp[jk] += freq[jk][m][i];
             }          }
             else          for(jk=1; jk <=nlstate ; jk++){
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);            for(m=-1, pos=0; m <=0 ; m++)
           }              pos += freq[jk][m][i];
         }            if(pp[jk]>=1.e-10){
                       if(first==1){
         for(jk=-1; jk <=nlstate+ndeath; jk++)              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
           for(m=-1; m <=nlstate+ndeath; m++)              }
             if(freq[jk][m][i] !=0 ) {              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
             if(first==1)            }else{
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);              if(first==1)
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             }              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
         if(i <= iagemax)            }
           fprintf(ficresp,"\n");          }
         if(first==1)  
           printf("Others in log...\n");          for(jk=1; jk <=nlstate ; jk++){
         fprintf(ficlog,"\n");            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
       }              pp[jk] += freq[jk][m][i];
     }          }      
   }          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
   dateintmean=dateintsum/k2cpt;             pos += pp[jk];
              posprop += prop[jk][i];
   fclose(ficresp);          }
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);          for(jk=1; jk <=nlstate ; jk++){
   free_vector(pp,1,nlstate);            if(pos>=1.e-5){
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);              if(first==1)
   /* End of Freq */                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 }              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             }else{
 /************ Prevalence ********************/              if(first==1)
 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)                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 {                fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people            }
      in each health status at the date of interview (if between dateprev1 and dateprev2).            if( i <= iagemax){
      We still use firstpass and lastpass as another selection.              if(pos>=1.e-5){
   */                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                  /*probs[i][jk][j1]= pp[jk]/pos;*/
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
   double ***freq; /* Frequencies */              }
   double *pp, **prop;              else
   double pos,posprop;                 fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
   double  y2; /* in fractional years */            }
   int iagemin, iagemax;          }
          
   iagemin= (int) agemin;          for(jk=-1; jk <=nlstate+ndeath; jk++)
   iagemax= (int) agemax;            for(m=-1; m <=nlstate+ndeath; m++)
   /*pp=vector(1,nlstate);*/              if(freq[jk][m][i] !=0 ) {
   prop=matrix(1,nlstate,iagemin,iagemax+3);               if(first==1)
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
   j1=0;                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                 }
   j=cptcoveff;          if(i <= iagemax)
   if (cptcovn<1) {j=1;ncodemax[1]=1;}            fprintf(ficresp,"\n");
             if(first==1)
   for(k1=1; k1<=j;k1++){            printf("Others in log...\n");
     for(i1=1; i1<=ncodemax[k1];i1++){          fprintf(ficlog,"\n");
       j1++;        }
             }
       for (i=1; i<=nlstate; i++)      }
         for(m=iagemin; m <= iagemax+3; m++)    dateintmean=dateintsum/k2cpt;
           prop[i][m]=0.0;   
          fclose(ficresp);
       for (i=1; i<=imx; i++) { /* Each individual */    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
         bool=1;    free_vector(pp,1,nlstate);
         if  (cptcovn>0) {    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
           for (z1=1; z1<=cptcoveff; z1++)     /* End of Freq */
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])   }
               bool=0;  
         }   /************ Prevalence ********************/
         if (bool==1) {   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(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 */    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */       in each health status at the date of interview (if between dateprev1 and dateprev2).
               if(agev[m][i]==0) agev[m][i]=iagemax+1;       We still use firstpass and lastpass as another selection.
               if(agev[m][i]==1) agev[m][i]=iagemax+2;    */
               if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m);    
               if (s[m][i]>0 && s[m][i]<=nlstate) {     int i, m, jk, k1, i1, j1, bool, z1,z2,j;
                 /*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]]);*/    double ***freq; /* Frequencies */
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];    double *pp, **prop;
                 prop[s[m][i]][iagemax+3] += weight[i];     double pos,posprop;
               }     double  y2; /* in fractional years */
             }    int iagemin, iagemax;
           } /* end selection of waves */  
         }    iagemin= (int) agemin;
       }    iagemax= (int) agemax;
       for(i=iagemin; i <= iagemax+3; i++){      /*pp=vector(1,nlstate);*/
             prop=matrix(1,nlstate,iagemin,iagemax+3);
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {     /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
           posprop += prop[jk][i];     j1=0;
         }    
     j=cptcoveff;
         for(jk=1; jk <=nlstate ; jk++){         if (cptcovn<1) {j=1;ncodemax[1]=1;}
           if( i <=  iagemax){    
             if(posprop>=1.e-5){     for(k1=1; k1<=j;k1++){
               probs[i][jk][j1]= prop[jk][i]/posprop;      for(i1=1; i1<=ncodemax[k1];i1++){
             }         j1++;
           }        
         }/* end jk */         for (i=1; i<=nlstate; i++)  
       }/* end i */           for(m=iagemin; m <= iagemax+3; m++)
     } /* end i1 */            prop[i][m]=0.0;
   } /* end k1 */       
           for (i=1; i<=imx; i++) { /* Each individual */
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/          bool=1;
   /*free_vector(pp,1,nlstate);*/          if  (cptcovn>0) {
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);            for (z1=1; z1<=cptcoveff; z1++)
 }  /* End of prevalence */              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
                 bool=0;
 /************* Waves Concatenation ***************/          }
           if (bool==1) {
 void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)            for(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 */
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.              if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
      Death is a valid wave (if date is known).                if(agev[m][i]==0) agev[m][i]=iagemax+1;
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i                if(agev[m][i]==1) agev[m][i]=iagemax+2;
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]                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);
      and mw[mi+1][i]. dh depends on stepm.                if (s[m][i]>0 && s[m][i]<=nlstate) {
      */                  /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
                   prop[s[m][i]][(int)agev[m][i]] += weight[i];
   int i, mi, m;                  prop[s[m][i]][iagemax+3] += weight[i];
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;                }
      double sum=0., jmean=0.;*/              }
   int first;            } /* end selection of waves */
   int j, k=0,jk, ju, jl;          }
   double sum=0.;        }
   first=0;        for(i=iagemin; i <= iagemax+3; i++){  
   jmin=1e+5;         
   jmax=-1;          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
   jmean=0.;            posprop += prop[jk][i];
   for(i=1; i<=imx; i++){          }
     mi=0;  
     m=firstpass;          for(jk=1; jk <=nlstate ; jk++){    
     while(s[m][i] <= nlstate){            if( i <=  iagemax){
       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)              if(posprop>=1.e-5){
         mw[++mi][i]=m;                probs[i][jk][j1]= prop[jk][i]/posprop;
       if(m >=lastpass)              }
         break;            }
       else          }/* end jk */
         m++;        }/* end i */
     }/* end while */      } /* end i1 */
     if (s[m][i] > nlstate){    } /* end k1 */
       mi++;     /* Death is another wave */   
       /* if(mi==0)  never been interviewed correctly before death */    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
          /* Only death is a correct wave */    /*free_vector(pp,1,nlstate);*/
       mw[mi][i]=m;    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
     }  }  /* End of prevalence */
   
     wav[i]=mi;  /************* Waves Concatenation ***************/
     if(mi==0){  
       nbwarn++;  void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
       if(first==0){  {
         printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
         first=1;       Death is a valid wave (if date is known).
       }       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
       if(first==1){       dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
         fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);       and mw[mi+1][i]. dh depends on stepm.
       }       */
     } /* end mi==0 */  
   } /* End individuals */    int i, mi, m;
     /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
   for(i=1; i<=imx; i++){       double sum=0., jmean=0.;*/
     for(mi=1; mi<wav[i];mi++){    int first;
       if (stepm <=0)    int j, k=0,jk, ju, jl;
         dh[mi][i]=1;    double sum=0.;
       else{    first=0;
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */    jmin=1e+5;
           if (agedc[i] < 2*AGESUP) {    jmax=-1;
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);     jmean=0.;
             if(j==0) j=1;  /* Survives at least one month after exam */    for(i=1; i<=imx; i++){
             else if(j<0){      mi=0;
               nberr++;      m=firstpass;
               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]);      while(s[m][i] <= nlstate){
               j=1; /* Temporary Dangerous patch */        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);          mw[++mi][i]=m;
               fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);        if(m >=lastpass)
               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);          break;
             }        else
             k=k+1;          m++;
             if (j >= jmax){      }/* end while */
               jmax=j;      if (s[m][i] > nlstate){
               ijmax=i;        mi++;     /* Death is another wave */
             }        /* if(mi==0)  never been interviewed correctly before death */
             if (j <= jmin){           /* Only death is a correct wave */
               jmin=j;        mw[mi][i]=m;
               ijmin=i;      }
             }  
             sum=sum+j;      wav[i]=mi;
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/      if(mi==0){
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/        nbwarn++;
           }        if(first==0){
         }          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
         else{          first=1;
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));        }
 /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */        if(first==1){
           fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
           k=k+1;        }
           if (j >= jmax) {      } /* end mi==0 */
             jmax=j;    } /* End individuals */
             ijmax=i;  
           }    for(i=1; i<=imx; i++){
           else if (j <= jmin){      for(mi=1; mi<wav[i];mi++){
             jmin=j;        if (stepm <=0)
             ijmin=i;          dh[mi][i]=1;
           }        else{
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
           /*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 (agedc[i] < 2*AGESUP) {
           if(j<0){              j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
             nberr++;              if(j==0) j=1;  /* Survives at least one month after exam */
             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]);              else if(j<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]);                nberr++;
           }                printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
           sum=sum+j;                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);
         jk= j/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]);
         jl= j -jk*stepm;                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);
         ju= j -(jk+1)*stepm;              }
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */              k=k+1;
           if(jl==0){              if (j >= jmax){
             dh[mi][i]=jk;                jmax=j;
             bh[mi][i]=0;                ijmax=i;
           }else{ /* We want a negative bias in order to only have interpolation ie              }
                   * at the price of an extra matrix product in likelihood */              if (j <= jmin){
             dh[mi][i]=jk+1;                jmin=j;
             bh[mi][i]=ju;                ijmin=i;
           }              }
         }else{              sum=sum+j;
           if(jl <= -ju){              /*if (j<0) printf("j=%d num=%d \n",j,i);*/
             dh[mi][i]=jk;              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
             bh[mi][i]=jl;       /* bias is positive if real duration            }
                                  * is higher than the multiple of stepm and negative otherwise.          }
                                  */          else{
           }            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
           else{  /*        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]); */
             dh[mi][i]=jk+1;  
             bh[mi][i]=ju;            k=k+1;
           }            if (j >= jmax) {
           if(dh[mi][i]==0){              jmax=j;
             dh[mi][i]=1; /* At least one step */              ijmax=i;
             bh[mi][i]=ju; /* At least one step */            }
             /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/            else if (j <= jmin){
           }              jmin=j;
         } /* end if mle */              ijmin=i;
       }            }
     } /* end wave */            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
   }            /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
   jmean=sum/k;            if(j<0){
   printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);              nberr++;
   fprintf(ficlog,"Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, ijmin, jmax, ijmax, jmean);              printf("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]);
             }
 /*********** Tricode ****************************/            sum=sum+j;
 void tricode(int *Tvar, int **nbcode, int imx)          }
 {          jk= j/stepm;
             jl= j -jk*stepm;
   int Ndum[20],ij=1, k, j, i, maxncov=19;          ju= j -(jk+1)*stepm;
   int cptcode=0;          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
   cptcoveff=0;             if(jl==0){
                dh[mi][i]=jk;
   for (k=0; k<maxncov; k++) Ndum[k]=0;              bh[mi][i]=0;
   for (k=1; k<=7; k++) ncodemax[k]=0;            }else{ /* We want a negative bias in order to only have interpolation ie
                     * at the price of an extra matrix product in likelihood */
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {              dh[mi][i]=jk+1;
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum               bh[mi][i]=ju;
                                modality*/             }
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/          }else{
       Ndum[ij]++; /*store the modality */            if(jl <= -ju){
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/              dh[mi][i]=jk;
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable               bh[mi][i]=jl;       /* bias is positive if real duration
                                        Tvar[j]. If V=sex and male is 0 and                                    * is higher than the multiple of stepm and negative otherwise.
                                        female is 1, then  cptcode=1.*/                                   */
     }            }
             else{
     for (i=0; i<=cptcode; i++) {              dh[mi][i]=jk+1;
       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 */              bh[mi][i]=ju;
     }            }
             if(dh[mi][i]==0){
     ij=1;               dh[mi][i]=1; /* At least one step */
     for (i=1; i<=ncodemax[j]; i++) {              bh[mi][i]=ju; /* At least one step */
       for (k=0; k<= maxncov; k++) {              /*  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 (Ndum[k] != 0) {            }
           nbcode[Tvar[j]][ij]=k;           } /* end if mle */
           /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */        }
                 } /* end wave */
           ij++;    }
         }    jmean=sum/k;
         if (ij > ncodemax[j]) break;     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);
     }    }
   }    
   /*********** Tricode ****************************/
  for (k=0; k< maxncov; k++) Ndum[k]=0;  void tricode(int *Tvar, int **nbcode, int imx)
   {
  for (i=1; i<=ncovmodel-2; i++) {    
    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/    int Ndum[20],ij=1, k, j, i, maxncov=19;
    ij=Tvar[i];    int cptcode=0;
    Ndum[ij]++;    cptcoveff=0;
  }   
     for (k=0; k<maxncov; k++) Ndum[k]=0;
  ij=1;    for (k=1; k<=7; k++) ncodemax[k]=0;
  for (i=1; i<= maxncov; i++) {  
    if((Ndum[i]!=0) && (i<=ncovcol)){    for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
      Tvaraff[ij]=i; /*For printing */      for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
      ij++;                                 modality*/
    }        ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
  }        Ndum[ij]++; /*store the modality */
          /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
  cptcoveff=ij-1; /*Number of simple covariates*/        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
 }                                         Tvar[j]. If V=sex and male is 0 and
                                          female is 1, then  cptcode=1.*/
 /*********** Health Expectancies ****************/      }
   
 void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )      for (i=0; i<=cptcode; i++) {
         if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */
 {      }
   /* Health expectancies, no variances */  
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;      ij=1;
   double age, agelim, hf;      for (i=1; i<=ncodemax[j]; i++) {
   double ***p3mat;        for (k=0; k<= maxncov; k++) {
   double eip;          if (Ndum[k] != 0) {
             nbcode[Tvar[j]][ij]=k;
   pstamp(ficreseij);            /* 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; */
   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");           
   fprintf(ficreseij,"# Age");            ij++;
   for(i=1; i<=nlstate;i++){          }
     for(j=1; j<=nlstate;j++){          if (ij > ncodemax[j]) break;
       fprintf(ficreseij," e%1d%1d ",i,j);        }  
     }      }
     fprintf(ficreseij," e%1d. ",i);    }  
   }  
   fprintf(ficreseij,"\n");   for (k=0; k< maxncov; k++) Ndum[k]=0;
   
      for (i=1; i<=ncovmodel-2; i++) {
   if(estepm < stepm){     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
     printf ("Problem %d lower than %d\n",estepm, stepm);     ij=Tvar[i];
   }     Ndum[ij]++;
   else  hstepm=estepm;      }
   /* We compute the life expectancy from trapezoids spaced every estepm months  
    * This is mainly to measure the difference between two models: for example   ij=1;
    * if stepm=24 months pijx are given only every 2 years and by summing them   for (i=1; i<= maxncov; i++) {
    * we are calculating an estimate of the Life Expectancy assuming a linear      if((Ndum[i]!=0) && (i<=ncovcol)){
    * progression in between and thus overestimating or underestimating according       Tvaraff[ij]=i; /*For printing */
    * to the curvature of the survival function. If, for the same date, we        ij++;
    * estimate the model with stepm=1 month, we can keep estepm to 24 months     }
    * to compare the new estimate of Life expectancy with the same linear    }
    * hypothesis. A more precise result, taking into account a more precise   
    * curvature will be obtained if estepm is as small as stepm. */   cptcoveff=ij-1; /*Number of simple covariates*/
   }
   /* 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.   /*********** Health Expectancies ****************/
      nhstepm is the number of hstepm from age to agelim   
      nstepm is the number of stepm from age to agelin.   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[] )
      Look at hpijx to understand the reason of that which relies in memory size  
      and note for a fixed period like estepm months */  {
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    /* Health expectancies, no variances */
      survival function given by stepm (the optimization length). Unfortunately it    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
      means that if the survival funtion is printed only each two years of age and if    double age, agelim, hf;
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     double ***p3mat;
      results. So we changed our mind and took the option of the best precision.    double eip;
   */  
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     pstamp(ficreseij);
     fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
   agelim=AGESUP;    fprintf(ficreseij,"# Age");
   /* nhstepm age range expressed in number of stepm */    for(i=1; i<=nlstate;i++){
   nstepm=(int) rint((agelim-age)*YEARM/stepm);       for(j=1; j<=nlstate;j++){
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */         fprintf(ficreseij," e%1d%1d ",i,j);
   /* if (stepm >= YEARM) hstepm=1;*/      }
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */      fprintf(ficreseij," e%1d. ",i);
   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    }
     fprintf(ficreseij,"\n");
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */  
     /* Computed by stepm unit matrices, product of hstepm matrices, stored   
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */    if(estepm < stepm){
           printf ("Problem %d lower than %d\n",estepm, stepm);
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);      }
         else  hstepm=estepm;  
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    /* We compute the life expectancy from trapezoids spaced every estepm months
          * This is mainly to measure the difference between two models: for example
     printf("%d|",(int)age);fflush(stdout);     * if stepm=24 months pijx are given only every 2 years and by summing them
     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);     * we are calculating an estimate of the Life Expectancy assuming a linear
          * progression in between and thus overestimating or underestimating according
     /* Computing expectancies */     * 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
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){     * hypothesis. A more precise result, taking into account a more precise
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;     * curvature will be obtained if estepm is as small as stepm. */
             
           /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/    /* For example we decided to compute the life expectancy with the smallest unit */
     /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
         }       nhstepm is the number of hstepm from age to agelim
        nstepm is the number of stepm from age to agelin.
     fprintf(ficreseij,"%3.0f",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 */
       eip=0;    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
       for(j=1; j<=nlstate;j++){       survival function given by stepm (the optimization length). Unfortunately it
         eip +=eij[i][j][(int)age];       means that if the survival funtion is printed only each two years of age and if
         fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );       you sum them up and add 1 year (area under the trapezoids) you won't get the same
       }       results. So we changed our mind and took the option of the best precision.
       fprintf(ficreseij,"%9.4f", eip );    */
     }    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
     fprintf(ficreseij,"\n");  
         agelim=AGESUP;
   }    /* If stepm=6 months */
   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      /* Computed by stepm unit matrices, product of hstepm matrices, stored
   printf("\n");         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
   fprintf(ficlog,"\n");     
     /* nhstepm age range expressed in number of stepm */
 }    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
     /* Typically if 20 years nstepm = 20*12/6=40 stepm */
 void cvevsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )    /* if (stepm >= YEARM) hstepm=1;*/
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 {    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   /* Covariances of health expectancies eij and of total life expectancies according  
    to initial status i, ei. .    for (age=bage; age<=fage; age ++){
   */  
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;  
   double age, agelim, hf;      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
   double ***p3matp, ***p3matm, ***varhe;     
   double **dnewm,**doldm;      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
   double *xp, *xm;     
   double **gp, **gm;      printf("%d|",(int)age);fflush(stdout);
   double ***gradg, ***trgradg;      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
   int theta;     
   
   double eip, vip;      /* Computing expectancies */
       for(i=1; i<=nlstate;i++)
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);        for(j=1; j<=nlstate;j++)
   xp=vector(1,npar);          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   xm=vector(1,npar);            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
   dnewm=matrix(1,nlstate*nlstate,1,npar);           
   doldm=matrix(1,nlstate*nlstate,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]);*/
     
   pstamp(ficresstdeij);          }
   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");     
   fprintf(ficresstdeij,"# Age");      fprintf(ficreseij,"%3.0f",age );
   for(i=1; i<=nlstate;i++){      for(i=1; i<=nlstate;i++){
     for(j=1; j<=nlstate;j++)        eip=0;
       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);        for(j=1; j<=nlstate;j++){
     fprintf(ficresstdeij," e%1d. ",i);          eip +=eij[i][j][(int)age];
   }          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
   fprintf(ficresstdeij,"\n");        }
         fprintf(ficreseij,"%9.4f", eip );
   pstamp(ficrescveij);      }
   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");      fprintf(ficreseij,"\n");
   fprintf(ficrescveij,"# Age");     
   for(i=1; i<=nlstate;i++)    }
     for(j=1; j<=nlstate;j++){    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       cptj= (j-1)*nlstate+i;    printf("\n");
       for(i2=1; i2<=nlstate;i2++)    fprintf(ficlog,"\n");
         for(j2=1; j2<=nlstate;j2++){   
           cptj2= (j2-1)*nlstate+i2;  }
           if(cptj2 <= cptj)  
             fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);  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(ficrescveij,"\n");    /* Covariances of health expectancies eij and of total life expectancies according
        to initial status i, ei. .
   if(estepm < stepm){    */
     printf ("Problem %d lower than %d\n",estepm, stepm);    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
   }    double age, agelim, hf;
   else  hstepm=estepm;       double ***p3matp, ***p3matm, ***varhe;
   /* We compute the life expectancy from trapezoids spaced every estepm months    double **dnewm,**doldm;
    * This is mainly to measure the difference between two models: for example    double *xp, *xm;
    * if stepm=24 months pijx are given only every 2 years and by summing them    double **gp, **gm;
    * we are calculating an estimate of the Life Expectancy assuming a linear     double ***gradg, ***trgradg;
    * progression in between and thus overestimating or underestimating according    int theta;
    * to the curvature of the survival function. If, for the same date, we   
    * estimate the model with stepm=1 month, we can keep estepm to 24 months    double eip, vip;
    * to compare the new estimate of Life expectancy with the same linear   
    * hypothesis. A more precise result, taking into account a more precise    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
    * curvature will be obtained if estepm is as small as stepm. */    xp=vector(1,npar);
     xm=vector(1,npar);
   /* For example we decided to compute the life expectancy with the smallest unit */    dnewm=matrix(1,nlstate*nlstate,1,npar);
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.     doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
      nhstepm is the number of hstepm from age to agelim    
      nstepm is the number of stepm from age to agelin.     pstamp(ficresstdeij);
      Look at hpijx to understand the reason of that which relies in memory size    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
      and note for a fixed period like estepm months */    fprintf(ficresstdeij,"# Age");
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    for(i=1; i<=nlstate;i++){
      survival function given by stepm (the optimization length). Unfortunately it      for(j=1; j<=nlstate;j++)
      means that if the survival funtion is printed only each two years of age and if        fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
      you sum them up and add 1 year (area under the trapezoids) you won't get the same       fprintf(ficresstdeij," e%1d. ",i);
      results. So we changed our mind and took the option of the best precision.    }
   */    fprintf(ficresstdeij,"\n");
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */   
     pstamp(ficrescveij);
   /* If stepm=6 months */    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
   /* nhstepm age range expressed in number of stepm */    fprintf(ficrescveij,"# Age");
   agelim=AGESUP;    for(i=1; i<=nlstate;i++)
   nstepm=(int) rint((agelim-age)*YEARM/stepm);       for(j=1; j<=nlstate;j++){
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */         cptj= (j-1)*nlstate+i;
   /* if (stepm >= YEARM) hstepm=1;*/        for(i2=1; i2<=nlstate;i2++)
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */          for(j2=1; j2<=nlstate;j2++){
               cptj2= (j2-1)*nlstate+i2;
   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            if(cptj2 <= cptj)
   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);          }
   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);      }
   gp=matrix(0,nhstepm,1,nlstate*nlstate);    fprintf(ficrescveij,"\n");
   gm=matrix(0,nhstepm,1,nlstate*nlstate);   
     if(estepm < stepm){
   for (age=bage; age<=fage; age ++){       printf ("Problem %d lower than %d\n",estepm, stepm);
     }
     /* Computed by stepm unit matrices, product of hstepm matrices, stored    else  hstepm=estepm;  
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */    /* We compute the life expectancy from trapezoids spaced every estepm months
       * This is mainly to measure the difference between two models: for example
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */     * if stepm=24 months pijx are given only every 2 years and by summing them
      * we are calculating an estimate of the Life Expectancy assuming a linear
     /* Computing  Variances of health expectancies */     * progression in between and thus overestimating or underestimating according
     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to     * to the curvature of the survival function. If, for the same date, we
        decrease memory allocation */     * estimate the model with stepm=1 month, we can keep estepm to 24 months
     for(theta=1; theta <=npar; theta++){     * to compare the new estimate of Life expectancy with the same linear
       for(i=1; i<=npar; i++){      * hypothesis. A more precise result, taking into account a more precise
         xp[i] = x[i] + (i==theta ?delti[theta]:0);     * curvature will be obtained if estepm is as small as stepm. */
         xm[i] = x[i] - (i==theta ?delti[theta]:0);  
       }    /* For example we decided to compute the life expectancy with the smallest unit */
       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);      /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);         nhstepm is the number of hstepm from age to agelim
          nstepm is the number of stepm from age to agelin.
       for(j=1; j<= nlstate; j++){       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(h=0; h<=nhstepm-1; h++){    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
             gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;       survival function given by stepm (the optimization length). Unfortunately it
             gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;       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
         }       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 */
       for(ij=1; ij<= nlstate*nlstate; ij++)  
         for(h=0; h<=nhstepm-1; h++){    /* If stepm=6 months */
           gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];    /* nhstepm age range expressed in number of stepm */
         }    agelim=AGESUP;
     }/* End theta */    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
         /* Typically if 20 years nstepm = 20*12/6=40 stepm */
         /* if (stepm >= YEARM) hstepm=1;*/
     for(h=0; h<=nhstepm-1; h++)    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       for(j=1; j<=nlstate*nlstate;j++)   
         for(theta=1; theta <=npar; theta++)    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           trgradg[h][j][theta]=gradg[h][theta][j];    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
     trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
      for(ij=1;ij<=nlstate*nlstate;ij++)    gp=matrix(0,nhstepm,1,nlstate*nlstate);
       for(ji=1;ji<=nlstate*nlstate;ji++)    gm=matrix(0,nhstepm,1,nlstate*nlstate);
         varhe[ij][ji][(int)age] =0.;  
     for (age=bage; age<=fage; age ++){
      printf("%d|",(int)age);fflush(stdout);  
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);      /* 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(k=0;k<=nhstepm-1;k++){   
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);  
         for(ij=1;ij<=nlstate*nlstate;ij++)      /* Computing  Variances of health expectancies */
           for(ji=1;ji<=nlstate*nlstate;ji++)      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
             varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;         decrease memory allocation */
       }      for(theta=1; theta <=npar; theta++){
     }        for(i=1; i<=npar; i++){
     /* Computing expectancies */          xp[i] = x[i] + (i==theta ?delti[theta]:0);
     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);            xm[i] = x[i] - (i==theta ?delti[theta]:0);
     for(i=1; i<=nlstate;i++)        }
       for(j=1; j<=nlstate;j++)        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
           eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;   
                   for(j=1; j<= nlstate; j++){
           /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/          for(i=1; i<=nlstate; i++){
             for(h=0; h<=nhstepm-1; h++){
         }              gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
               gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
     fprintf(ficresstdeij,"%3.0f",age );            }
     for(i=1; i<=nlstate;i++){          }
       eip=0.;        }
       vip=0.;       
       for(j=1; j<=nlstate;j++){        for(ij=1; ij<= nlstate*nlstate; ij++)
         eip += eij[i][j][(int)age];          for(h=0; h<=nhstepm-1; h++){
         for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
           vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];          }
         fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );      }/* End theta */
       }     
       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));     
     }      for(h=0; h<=nhstepm-1; h++)
     fprintf(ficresstdeij,"\n");        for(j=1; j<=nlstate*nlstate;j++)
           for(theta=1; theta <=npar; theta++)
     fprintf(ficrescveij,"%3.0f",age );            trgradg[h][j][theta]=gradg[h][theta][j];
     for(i=1; i<=nlstate;i++)     
       for(j=1; j<=nlstate;j++){  
         cptj= (j-1)*nlstate+i;       for(ij=1;ij<=nlstate*nlstate;ij++)
         for(i2=1; i2<=nlstate;i2++)        for(ji=1;ji<=nlstate*nlstate;ji++)
           for(j2=1; j2<=nlstate;j2++){          varhe[ij][ji][(int)age] =0.;
             cptj2= (j2-1)*nlstate+i2;  
             if(cptj2 <= cptj)       printf("%d|",(int)age);fflush(stdout);
               fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
           }       for(h=0;h<=nhstepm-1;h++){
       }        for(k=0;k<=nhstepm-1;k++){
     fprintf(ficrescveij,"\n");          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(ij=1;ij<=nlstate*nlstate;ij++)
   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);            for(ji=1;ji<=nlstate*nlstate;ji++)
   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
   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);  
   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      /* Computing expectancies */
   printf("\n");      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
   fprintf(ficlog,"\n");      for(i=1; i<=nlstate;i++)
         for(j=1; j<=nlstate;j++)
   free_vector(xm,1,npar);          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   free_vector(xp,1,npar);            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);           
   free_matrix(doldm,1,nlstate*nlstate,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_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);  
 }          }
   
 /************ Variance ******************/      fprintf(ficresstdeij,"%3.0f",age );
 void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])      for(i=1; i<=nlstate;i++){
 {        eip=0.;
   /* Variance of health expectancies */        vip=0.;
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/        for(j=1; j<=nlstate;j++){
   /* double **newm;*/          eip += eij[i][j][(int)age];
   double **dnewm,**doldm;          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
   double **dnewmp,**doldmp;            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
   int i, j, nhstepm, hstepm, h, nstepm ;          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
   int k, cptcode;        }
   double *xp;        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
   double **gp, **gm;  /* for var eij */      }
   double ***gradg, ***trgradg; /*for var eij */      fprintf(ficresstdeij,"\n");
   double **gradgp, **trgradgp; /* for var p point j */  
   double *gpp, *gmp; /* for var p point j */      fprintf(ficrescveij,"%3.0f",age );
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */      for(i=1; i<=nlstate;i++)
   double ***p3mat;        for(j=1; j<=nlstate;j++){
   double age,agelim, hf;          cptj= (j-1)*nlstate+i;
   double ***mobaverage;          for(i2=1; i2<=nlstate;i2++)
   int theta;            for(j2=1; j2<=nlstate;j2++){
   char digit[4];              cptj2= (j2-1)*nlstate+i2;
   char digitp[25];              if(cptj2 <= cptj)
                 fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
   char fileresprobmorprev[FILENAMELENGTH];            }
         }
   if(popbased==1){      fprintf(ficrescveij,"\n");
     if(mobilav!=0)     
       strcpy(digitp,"-populbased-mobilav-");    }
     else strcpy(digitp,"-populbased-nomobil-");    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
   }    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
   else     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
     strcpy(digitp,"-stablbased-");    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
     free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   if (mobilav!=0) {    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    printf("\n");
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){    fprintf(ficlog,"\n");
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);  
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    free_vector(xm,1,npar);
     }    free_vector(xp,1,npar);
   }    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
     free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
   strcpy(fileresprobmorprev,"prmorprev");     free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
   sprintf(digit,"%-d",ij);  }
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/  
   strcat(fileresprobmorprev,digit); /* Tvar to be done */  /************ Variance ******************/
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */  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[])
   strcat(fileresprobmorprev,fileres);  {
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {    /* Variance of health expectancies */
     printf("Problem with resultfile: %s\n", fileresprobmorprev);    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);    /* double **newm;*/
   }    double **dnewm,**doldm;
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    double **dnewmp,**doldmp;
      int i, j, nhstepm, hstepm, h, nstepm ;
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    int k, cptcode;
   pstamp(ficresprobmorprev);    double *xp;
   fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);    double **gp, **gm;  /* for var eij */
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);    double ***gradg, ***trgradg; /*for var eij */
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){    double **gradgp, **trgradgp; /* for var p point j */
     fprintf(ficresprobmorprev," p.%-d SE",j);    double *gpp, *gmp; /* for var p point j */
     for(i=1; i<=nlstate;i++)    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);    double ***p3mat;
   }      double age,agelim, hf;
   fprintf(ficresprobmorprev,"\n");    double ***mobaverage;
   fprintf(ficgp,"\n# Routine varevsij");    int theta;
   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/    char digit[4];
   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");    char digitp[25];
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);  
 /*   } */    char fileresprobmorprev[FILENAMELENGTH];
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);  
   pstamp(ficresvij);    if(popbased==1){
   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");      if(mobilav!=0)
   if(popbased==1)        strcpy(digitp,"-populbased-mobilav-");
     fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");      else strcpy(digitp,"-populbased-nomobil-");
   else    }
     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");    else
   fprintf(ficresvij,"# Age");      strcpy(digitp,"-stablbased-");
   for(i=1; i<=nlstate;i++)  
     for(j=1; j<=nlstate;j++)    if (mobilav!=0) {
       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficresvij,"\n");      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   xp=vector(1,npar);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   dnewm=matrix(1,nlstate,1,npar);      }
   doldm=matrix(1,nlstate,1,nlstate);    }
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);  
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    strcpy(fileresprobmorprev,"prmorprev");
     sprintf(digit,"%-d",ij);
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
   gpp=vector(nlstate+1,nlstate+ndeath);    strcat(fileresprobmorprev,digit); /* Tvar to be done */
   gmp=vector(nlstate+1,nlstate+ndeath);    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/    strcat(fileresprobmorprev,fileres);
       if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
   if(estepm < stepm){      printf("Problem with resultfile: %s\n", fileresprobmorprev);
     printf ("Problem %d lower than %d\n",estepm, stepm);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
   }    }
   else  hstepm=estepm;       printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   /* 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.     fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
      nhstepm is the number of hstepm from age to agelim     pstamp(ficresprobmorprev);
      nstepm is the number of stepm from age to agelin.     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);
      Look at hpijx to understand the reason of that which relies in memory size    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
      and note for a fixed period like k years */    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the      fprintf(ficresprobmorprev," p.%-d SE",j);
      survival function given by stepm (the optimization length). Unfortunately it      for(i=1; i<=nlstate;i++)
      means that if the survival funtion is printed every two years of age and if        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     }  
      results. So we changed our mind and took the option of the best precision.    fprintf(ficresprobmorprev,"\n");
   */    fprintf(ficgp,"\n# Routine varevsij");
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   agelim = AGESUP;    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");
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */   /*   } */
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    pstamp(ficresvij);
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
     gp=matrix(0,nhstepm,1,nlstate);    if(popbased==1)
     gm=matrix(0,nhstepm,1,nlstate);      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
     else
       fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
     for(theta=1; theta <=npar; theta++){    fprintf(ficresvij,"# Age");
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/    for(i=1; i<=nlstate;i++)
         xp[i] = x[i] + (i==theta ?delti[theta]:0);      for(j=1; j<=nlstate;j++)
       }        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);      fprintf(ficresvij,"\n");
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);  
     xp=vector(1,npar);
       if (popbased==1) {    dnewm=matrix(1,nlstate,1,npar);
         if(mobilav ==0){    doldm=matrix(1,nlstate,1,nlstate);
           for(i=1; i<=nlstate;i++)    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
             prlim[i][i]=probs[(int)age][i][ij];    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
         }else{ /* mobilav */   
           for(i=1; i<=nlstate;i++)    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
             prlim[i][i]=mobaverage[(int)age][i][ij];    gpp=vector(nlstate+1,nlstate+ndeath);
         }    gmp=vector(nlstate+1,nlstate+ndeath);
       }    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
      
       for(j=1; j<= nlstate; j++){    if(estepm < stepm){
         for(h=0; h<=nhstepm; h++){      printf ("Problem %d lower than %d\n",estepm, stepm);
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)    }
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];    else  hstepm=estepm;  
         }    /* 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.
       /* This for computing probability of death (h=1 means       nhstepm is the number of hstepm from age to agelim
          computed over hstepm matrices product = hstepm*stepm months)        nstepm is the number of stepm from age to agelin.
          as a weighted average of prlim.       Look at hpijx to understand the reason of that which relies in memory size
       */       and note for a fixed period like k years */
       for(j=nlstate+1;j<=nlstate+ndeath;j++){    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
         for(i=1,gpp[j]=0.; i<= nlstate; i++)       survival function given by stepm (the optimization length). Unfortunately it
           gpp[j] += prlim[i][i]*p3mat[i][j][1];       means that if the survival funtion is printed every two years of age and if
       }           you sum them up and add 1 year (area under the trapezoids) you won't get the same
       /* end probability of death */       results. So we changed our mind and took the option of the best precision.
     */
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    agelim = AGESUP;
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);      for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
        nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       if (popbased==1) {      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         if(mobilav ==0){      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
           for(i=1; i<=nlstate;i++)      gp=matrix(0,nhstepm,1,nlstate);
             prlim[i][i]=probs[(int)age][i][ij];      gm=matrix(0,nhstepm,1,nlstate);
         }else{ /* mobilav */   
           for(i=1; i<=nlstate;i++)  
             prlim[i][i]=mobaverage[(int)age][i][ij];      for(theta=1; theta <=npar; theta++){
         }        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
       }          xp[i] = x[i] + (i==theta ?delti[theta]:0);
         }
       for(j=1; j<= nlstate; j++){        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
         for(h=0; h<=nhstepm; h++){        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)  
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];        if (popbased==1) {
         }          if(mobilav ==0){
       }            for(i=1; i<=nlstate;i++)
       /* This for computing probability of death (h=1 means              prlim[i][i]=probs[(int)age][i][ij];
          computed over hstepm matrices product = hstepm*stepm months)           }else{ /* mobilav */
          as a weighted average of prlim.            for(i=1; i<=nlstate;i++)
       */              prlim[i][i]=mobaverage[(int)age][i][ij];
       for(j=nlstate+1;j<=nlstate+ndeath;j++){          }
         for(i=1,gmp[j]=0.; i<= nlstate; i++)        }
          gmp[j] += prlim[i][i]*p3mat[i][j][1];   
       }            for(j=1; j<= nlstate; j++){
       /* end probability of death */          for(h=0; h<=nhstepm; h++){
             for(i=1, gp[h][j]=0.;i<=nlstate;i++)
       for(j=1; j<= nlstate; j++) /* vareij */              gp[h][j] += prlim[i][i]*p3mat[i][j][h];
         for(h=0; h<=nhstepm; h++){          }
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];        }
         }        /* This for computing probability of death (h=1 means
            computed over hstepm matrices product = hstepm*stepm months)
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */           as a weighted average of prlim.
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];        */
       }        for(j=nlstate+1;j<=nlstate+ndeath;j++){
           for(i=1,gpp[j]=0.; i<= nlstate; i++)
     } /* End theta */            gpp[j] += prlim[i][i]*p3mat[i][j][1];
         }    
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */        /* end probability of death */
   
     for(h=0; h<=nhstepm; h++) /* veij */        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
       for(j=1; j<=nlstate;j++)          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         for(theta=1; theta <=npar; theta++)        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
           trgradg[h][j][theta]=gradg[h][theta][j];        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
    
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */        if (popbased==1) {
       for(theta=1; theta <=npar; theta++)          if(mobilav ==0){
         trgradgp[j][theta]=gradgp[theta][j];            for(i=1; i<=nlstate;i++)
                 prlim[i][i]=probs[(int)age][i][ij];
           }else{ /* mobilav */
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */            for(i=1; i<=nlstate;i++)
     for(i=1;i<=nlstate;i++)              prlim[i][i]=mobaverage[(int)age][i][ij];
       for(j=1;j<=nlstate;j++)          }
         vareij[i][j][(int)age] =0.;        }
   
     for(h=0;h<=nhstepm;h++){        for(j=1; j<= nlstate; j++){
       for(k=0;k<=nhstepm;k++){          for(h=0; h<=nhstepm; h++){
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
         for(i=1;i<=nlstate;i++)          }
           for(j=1;j<=nlstate;j++)        }
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;        /* This for computing probability of death (h=1 means
       }           computed over hstepm matrices product = hstepm*stepm months)
     }           as a weighted average of prlim.
           */
     /* pptj */        for(j=nlstate+1;j<=nlstate+ndeath;j++){
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);          for(i=1,gmp[j]=0.; i<= nlstate; i++)
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);           gmp[j] += prlim[i][i]*p3mat[i][j][1];
     for(j=nlstate+1;j<=nlstate+ndeath;j++)        }    
       for(i=nlstate+1;i<=nlstate+ndeath;i++)        /* end probability of death */
         varppt[j][i]=doldmp[j][i];  
     /* end ppptj */        for(j=1; j<= nlstate; j++) /* vareij */
     /*  x centered again */          for(h=0; h<=nhstepm; h++){
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);              gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);          }
    
     if (popbased==1) {        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
       if(mobilav ==0){          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
         for(i=1; i<=nlstate;i++)        }
           prlim[i][i]=probs[(int)age][i][ij];  
       }else{ /* mobilav */       } /* End theta */
         for(i=1; i<=nlstate;i++)  
           prlim[i][i]=mobaverage[(int)age][i][ij];      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
       }  
     }      for(h=0; h<=nhstepm; h++) /* veij */
                      for(j=1; j<=nlstate;j++)
     /* This for computing probability of death (h=1 means          for(theta=1; theta <=npar; theta++)
        computed over hstepm (estepm) matrices product = hstepm*stepm months)             trgradg[h][j][theta]=gradg[h][theta][j];
        as a weighted average of prlim.  
     */      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
     for(j=nlstate+1;j<=nlstate+ndeath;j++){        for(theta=1; theta <=npar; theta++)
       for(i=1,gmp[j]=0.;i<= nlstate; i++)           trgradgp[j][theta]=gradgp[theta][j];
         gmp[j] += prlim[i][i]*p3mat[i][j][1];    
     }      
     /* end probability of death */      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       for(i=1;i<=nlstate;i++)
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);        for(j=1;j<=nlstate;j++)
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){          vareij[i][j][(int)age] =0.;
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));  
       for(i=1; i<=nlstate;i++){      for(h=0;h<=nhstepm;h++){
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);        for(k=0;k<=nhstepm;k++){
       }          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
     }           matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
     fprintf(ficresprobmorprev,"\n");          for(i=1;i<=nlstate;i++)
             for(j=1;j<=nlstate;j++)
     fprintf(ficresvij,"%.0f ",age );              vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
     for(i=1; i<=nlstate;i++)        }
       for(j=1; j<=nlstate;j++){      }
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);   
       }      /* pptj */
     fprintf(ficresvij,"\n");      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
     free_matrix(gp,0,nhstepm,1,nlstate);      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
     free_matrix(gm,0,nhstepm,1,nlstate);      for(j=nlstate+1;j<=nlstate+ndeath;j++)
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);        for(i=nlstate+1;i<=nlstate+ndeath;i++)
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);          varppt[j][i]=doldmp[j][i];
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      /* end ppptj */
   } /* End age */      /*  x centered again */
   free_vector(gpp,nlstate+1,nlstate+ndeath);      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
   free_vector(gmp,nlstate+1,nlstate+ndeath);      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);   
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/      if (popbased==1) {
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");        if(mobilav ==0){
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */          for(i=1; i<=nlstate;i++)
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");            prlim[i][i]=probs[(int)age][i][ij];
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */        }else{ /* mobilav */
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */          for(i=1; i<=nlstate;i++)
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */            prlim[i][i]=mobaverage[(int)age][i][ij];
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));        }
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));      }
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));               
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));      /* This for computing probability of death (h=1 means
   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);         computed over hstepm (estepm) matrices product = hstepm*stepm months)
   /*  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);         as a weighted average of prlim.
 */      */
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */      for(j=nlstate+1;j<=nlstate+ndeath;j++){
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);        for(i=1,gmp[j]=0.;i<= nlstate; i++)
           gmp[j] += prlim[i][i]*p3mat[i][j][1];
   free_vector(xp,1,npar);      }    
   free_matrix(doldm,1,nlstate,1,nlstate);      /* end probability of death */
   free_matrix(dnewm,1,nlstate,1,npar);  
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        for(i=1; i<=nlstate;i++){
   fclose(ficresprobmorprev);          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
   fflush(ficgp);        }
   fflush(fichtm);       }
 }  /* end varevsij */      fprintf(ficresprobmorprev,"\n");
   
 /************ Variance of prevlim ******************/      fprintf(ficresvij,"%.0f ",age );
 void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])      for(i=1; i<=nlstate;i++)
 {        for(j=1; j<=nlstate;j++){
   /* Variance of prevalence limit */          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/        }
   double **newm;      fprintf(ficresvij,"\n");
   double **dnewm,**doldm;      free_matrix(gp,0,nhstepm,1,nlstate);
   int i, j, nhstepm, hstepm;      free_matrix(gm,0,nhstepm,1,nlstate);
   int k, cptcode;      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
   double *xp;      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
   double *gp, *gm;      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double **gradg, **trgradg;    } /* End age */
   double age,agelim;    free_vector(gpp,nlstate+1,nlstate+ndeath);
   int theta;    free_vector(gmp,nlstate+1,nlstate+ndeath);
       free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
   pstamp(ficresvpl);    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
   fprintf(ficresvpl,"# Age");    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
   for(i=1; i<=nlstate;i++)    fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
       fprintf(ficresvpl," %1d-%1d",i,i);  /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
   fprintf(ficresvpl,"\n");  /*   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); */
   xp=vector(1,npar);    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
   dnewm=matrix(1,nlstate,1,npar);    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
   doldm=matrix(1,nlstate,1,nlstate);    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
       fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
   hstepm=1*YEARM; /* Every year of age */    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);
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */     /*  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);
   agelim = AGESUP;  */
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
     if (stepm >= YEARM) hstepm=1;  
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */    free_vector(xp,1,npar);
     gradg=matrix(1,npar,1,nlstate);    free_matrix(doldm,1,nlstate,1,nlstate);
     gp=vector(1,nlstate);    free_matrix(dnewm,1,nlstate,1,npar);
     gm=vector(1,nlstate);    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
     free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
     for(theta=1; theta <=npar; theta++){    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
       for(i=1; i<=npar; i++){ /* Computes gradient */    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    fclose(ficresprobmorprev);
       }    fflush(ficgp);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    fflush(fichtm);
       for(i=1;i<=nlstate;i++)  }  /* end varevsij */
         gp[i] = prlim[i][i];  
       /************ Variance of prevlim ******************/
       for(i=1; i<=npar; i++) /* Computes gradient */  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[])
         xp[i] = x[i] - (i==theta ?delti[theta]:0);  {
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    /* Variance of prevalence limit */
       for(i=1;i<=nlstate;i++)    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
         gm[i] = prlim[i][i];    double **newm;
     double **dnewm,**doldm;
       for(i=1;i<=nlstate;i++)    int i, j, nhstepm, hstepm;
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];    int k, cptcode;
     } /* End theta */    double *xp;
     double *gp, *gm;
     trgradg =matrix(1,nlstate,1,npar);    double **gradg, **trgradg;
     double age,agelim;
     for(j=1; j<=nlstate;j++)    int theta;
       for(theta=1; theta <=npar; theta++)   
         trgradg[j][theta]=gradg[theta][j];    pstamp(ficresvpl);
     fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
     for(i=1;i<=nlstate;i++)    fprintf(ficresvpl,"# Age");
       varpl[i][(int)age] =0.;    for(i=1; i<=nlstate;i++)
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);        fprintf(ficresvpl," %1d-%1d",i,i);
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);    fprintf(ficresvpl,"\n");
     for(i=1;i<=nlstate;i++)  
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */    xp=vector(1,npar);
     dnewm=matrix(1,nlstate,1,npar);
     fprintf(ficresvpl,"%.0f ",age );    doldm=matrix(1,nlstate,1,nlstate);
     for(i=1; i<=nlstate;i++)   
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));    hstepm=1*YEARM; /* Every year of age */
     fprintf(ficresvpl,"\n");    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
     free_vector(gp,1,nlstate);    agelim = AGESUP;
     free_vector(gm,1,nlstate);    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
     free_matrix(gradg,1,npar,1,nlstate);      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
     free_matrix(trgradg,1,nlstate,1,npar);      if (stepm >= YEARM) hstepm=1;
   } /* End age */      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
       gradg=matrix(1,npar,1,nlstate);
   free_vector(xp,1,npar);      gp=vector(1,nlstate);
   free_matrix(doldm,1,nlstate,1,npar);      gm=vector(1,nlstate);
   free_matrix(dnewm,1,nlstate,1,nlstate);  
       for(theta=1; theta <=npar; theta++){
 }        for(i=1; i<=npar; i++){ /* Computes gradient */
           xp[i] = x[i] + (i==theta ?delti[theta]:0);
 /************ 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[])        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 {        for(i=1;i<=nlstate;i++)
   int i, j=0,  i1, k1, l1, t, tj;          gp[i] = prlim[i][i];
   int k2, l2, j1,  z1;     
   int k=0,l, cptcode;        for(i=1; i<=npar; i++) /* Computes gradient */
   int first=1, first1;          xp[i] = x[i] - (i==theta ?delti[theta]:0);
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   double **dnewm,**doldm;        for(i=1;i<=nlstate;i++)
   double *xp;          gm[i] = prlim[i][i];
   double *gp, *gm;  
   double **gradg, **trgradg;        for(i=1;i<=nlstate;i++)
   double **mu;          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
   double age,agelim, cov[NCOVMAX];      } /* End theta */
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */  
   int theta;      trgradg =matrix(1,nlstate,1,npar);
   char fileresprob[FILENAMELENGTH];  
   char fileresprobcov[FILENAMELENGTH];      for(j=1; j<=nlstate;j++)
   char fileresprobcor[FILENAMELENGTH];        for(theta=1; theta <=npar; theta++)
           trgradg[j][theta]=gradg[theta][j];
   double ***varpij;  
       for(i=1;i<=nlstate;i++)
   strcpy(fileresprob,"prob");         varpl[i][(int)age] =0.;
   strcat(fileresprob,fileres);      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
     printf("Problem with resultfile: %s\n", fileresprob);      for(i=1;i<=nlstate;i++)
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
   }  
   strcpy(fileresprobcov,"probcov");       fprintf(ficresvpl,"%.0f ",age );
   strcat(fileresprobcov,fileres);      for(i=1; i<=nlstate;i++)
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
     printf("Problem with resultfile: %s\n", fileresprobcov);      fprintf(ficresvpl,"\n");
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);      free_vector(gp,1,nlstate);
   }      free_vector(gm,1,nlstate);
   strcpy(fileresprobcor,"probcor");       free_matrix(gradg,1,npar,1,nlstate);
   strcat(fileresprobcor,fileres);      free_matrix(trgradg,1,nlstate,1,npar);
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {    } /* End age */
     printf("Problem with resultfile: %s\n", fileresprobcor);  
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);    free_vector(xp,1,npar);
   }    free_matrix(doldm,1,nlstate,1,npar);
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    free_matrix(dnewm,1,nlstate,1,nlstate);
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);  
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);  }
   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);  /************ Variance of one-step probabilities  ******************/
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);  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[])
   pstamp(ficresprob);  {
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");    int i, j=0,  i1, k1, l1, t, tj;
   fprintf(ficresprob,"# Age");    int k2, l2, j1,  z1;
   pstamp(ficresprobcov);    int k=0,l, cptcode;
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");    int first=1, first1;
   fprintf(ficresprobcov,"# Age");    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
   pstamp(ficresprobcor);    double **dnewm,**doldm;
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");    double *xp;
   fprintf(ficresprobcor,"# Age");    double *gp, *gm;
     double **gradg, **trgradg;
     double **mu;
   for(i=1; i<=nlstate;i++)    double age,agelim, cov[NCOVMAX];
     for(j=1; j<=(nlstate+ndeath);j++){    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);    int theta;
       fprintf(ficresprobcov," p%1d-%1d ",i,j);    char fileresprob[FILENAMELENGTH];
       fprintf(ficresprobcor," p%1d-%1d ",i,j);    char fileresprobcov[FILENAMELENGTH];
     }      char fileresprobcor[FILENAMELENGTH];
  /* fprintf(ficresprob,"\n");  
   fprintf(ficresprobcov,"\n");    double ***varpij;
   fprintf(ficresprobcor,"\n");  
  */    strcpy(fileresprob,"prob");
  xp=vector(1,npar);    strcat(fileresprob,fileres);
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));      printf("Problem with resultfile: %s\n", fileresprob);
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);    }
   first=1;    strcpy(fileresprobcov,"probcov");
   fprintf(ficgp,"\n# Routine varprob");    strcat(fileresprobcov,fileres);
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
   fprintf(fichtm,"\n");      printf("Problem with resultfile: %s\n", fileresprobcov);
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
   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\    strcpy(fileresprobcor,"probcor");
   file %s<br>\n",optionfilehtmcov);    strcat(fileresprobcor,fileres);
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 and drawn. It helps understanding how is the covariance between two incidences.\      printf("Problem with resultfile: %s\n", fileresprobcor);
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
   fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \    }
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 standard deviations wide on each axis. <br>\    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
     pstamp(ficresprob);
   cov[1]=1;    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
   tj=cptcoveff;    fprintf(ficresprob,"# Age");
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}    pstamp(ficresprobcov);
   j1=0;    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
   for(t=1; t<=tj;t++){    fprintf(ficresprobcov,"# Age");
     for(i1=1; i1<=ncodemax[t];i1++){     pstamp(ficresprobcor);
       j1++;    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
       if  (cptcovn>0) {    fprintf(ficresprobcor,"# Age");
         fprintf(ficresprob, "\n#********** Variable ");   
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);  
         fprintf(ficresprob, "**********\n#\n");    for(i=1; i<=nlstate;i++)
         fprintf(ficresprobcov, "\n#********** Variable ");       for(j=1; j<=(nlstate+ndeath);j++){
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
         fprintf(ficresprobcov, "**********\n#\n");        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                 fprintf(ficresprobcor," p%1d-%1d ",i,j);
         fprintf(ficgp, "\n#********** Variable ");       }  
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);   /* fprintf(ficresprob,"\n");
         fprintf(ficgp, "**********\n#\n");    fprintf(ficresprobcov,"\n");
             fprintf(ficresprobcor,"\n");
            */
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");    xp=vector(1,npar);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
             mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
         fprintf(ficresprobcor, "\n#********** Variable ");        varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    first=1;
         fprintf(ficresprobcor, "**********\n#");        fprintf(ficgp,"\n# Routine varprob");
       }    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
           fprintf(fichtm,"\n");
       for (age=bage; age<=fage; age ++){   
         cov[2]=age;    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
         for (k=1; k<=cptcovn;k++) {    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];    file %s<br>\n",optionfilehtmcov);
         }    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];  and drawn. It helps understanding how is the covariance between two incidences.\
         for (k=1; k<=cptcovprod;k++)   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];    fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
           It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));  would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);  standard deviations wide on each axis. <br>\
         gp=vector(1,(nlstate)*(nlstate+ndeath));   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
         gm=vector(1,(nlstate)*(nlstate+ndeath));   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(theta=1; theta <=npar; theta++){  
           for(i=1; i<=npar; i++)    cov[1]=1;
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);    tj=cptcoveff;
               if (cptcovn<1) {tj=1;ncodemax[1]=1;}
           pmij(pmmij,cov,ncovmodel,xp,nlstate);    j1=0;
               for(t=1; t<=tj;t++){
           k=0;      for(i1=1; i1<=ncodemax[t];i1++){
           for(i=1; i<= (nlstate); i++){        j1++;
             for(j=1; j<=(nlstate+ndeath);j++){        if  (cptcovn>0) {
               k=k+1;          fprintf(ficresprob, "\n#********** Variable ");
               gp[k]=pmmij[i][j];          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             }          fprintf(ficresprob, "**********\n#\n");
           }          fprintf(ficresprobcov, "\n#********** Variable ");
                     for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           for(i=1; i<=npar; i++)          fprintf(ficresprobcov, "**********\n#\n");
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);         
               fprintf(ficgp, "\n#********** Variable ");
           pmij(pmmij,cov,ncovmodel,xp,nlstate);          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 ");
               gm[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<= (nlstate)*(nlstate+ndeath); i++)           for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];            fprintf(ficresprobcor, "**********\n#");    
         }        }
        
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)        for (age=bage; age<=fage; age ++){
           for(theta=1; theta <=npar; theta++)          cov[2]=age;
             trgradg[j][theta]=gradg[theta][j];          for (k=1; k<=cptcovn;k++) {
                     cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);           }
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));          for (k=1; k<=cptcovprod;k++)
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));            cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);         
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
           trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
         pmij(pmmij,cov,ncovmodel,x,nlstate);          gp=vector(1,(nlstate)*(nlstate+ndeath));
                   gm=vector(1,(nlstate)*(nlstate+ndeath));
         k=0;     
         for(i=1; i<=(nlstate); i++){          for(theta=1; theta <=npar; theta++){
           for(j=1; j<=(nlstate+ndeath);j++){            for(i=1; i<=npar; i++)
             k=k+1;              xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
             mu[k][(int) age]=pmmij[i][j];           
           }            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);                gp[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<=npar; i++)
               xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
         fprintf(ficresprob,"\n%d ",(int)age);     
         fprintf(ficresprobcov,"\n%d ",(int)age);            pmij(pmmij,cov,ncovmodel,xp,nlstate);
         fprintf(ficresprobcor,"\n%d ",(int)age);            k=0;
             for(i=1; i<=(nlstate); i++){
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)              for(j=1; j<=(nlstate+ndeath);j++){
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));                k=k+1;
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){                gm[k]=pmmij[i][j];
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);              }
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);            }
         }       
         i=0;            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
         for (k=1; k<=(nlstate);k++){              gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
           for (l=1; l<=(nlstate+ndeath);l++){           }
             i=i++;  
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);          for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);            for(theta=1; theta <=npar; theta++)
             for (j=1; j<=i;j++){              trgradg[j][theta]=gradg[theta][j];
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);         
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
             }          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
           }          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
         }/* end of loop for state */          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
       } /* end of loop for age */          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
           free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
       /* Confidence intervalle of pij  */  
       /*          pmij(pmmij,cov,ncovmodel,x,nlstate);
         fprintf(ficgp,"\nset noparametric;unset label");         
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");          k=0;
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");          for(i=1; i<=(nlstate); 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);            for(j=1; j<=(nlstate+ndeath);j++){
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);              k=k+1;
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);              mu[k][(int) age]=pmmij[i][j];
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);            }
       */          }
           for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/            for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
       first1=1;              varpij[i][j][(int)age] = doldm[i][j];
       for (k2=1; k2<=(nlstate);k2++){  
         for (l2=1; l2<=(nlstate+ndeath);l2++){           /*printf("\n%d ",(int)age);
           if(l2==k2) continue;            for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
           j=(k2-1)*(nlstate+ndeath)+l2;            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
           for (k1=1; k1<=(nlstate);k1++){            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
             for (l1=1; l1<=(nlstate+ndeath);l1++){             }*/
               if(l1==k1) continue;  
               i=(k1-1)*(nlstate+ndeath)+l1;          fprintf(ficresprob,"\n%d ",(int)age);
               if(i<=j) continue;          fprintf(ficresprobcov,"\n%d ",(int)age);
               for (age=bage; age<=fage; age ++){           fprintf(ficresprobcor,"\n%d ",(int)age);
                 if ((int)age %5==0){  
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   mu1=mu[i][(int) age]/stepm*YEARM ;            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   mu2=mu[j][(int) age]/stepm*YEARM;            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   c12=cv12/sqrt(v1*v2);          }
                   /* Computing eigen value of matrix of covariance */          i=0;
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;          for (k=1; k<=(nlstate);k++){
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;            for (l=1; l<=(nlstate+ndeath);l++){
                   /* Eigen vectors */              i=i++;
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   /*v21=sqrt(1.-v11*v11); *//* error */              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   v21=(lc1-v1)/cv12*v11;              for (j=1; j<=i;j++){
                   v12=-v21;                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   v22=v11;                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   tnalp=v21/v11;              }
                   if(first1==1){            }
                     first1=0;          }/* end of loop for state */
                     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);        } /* end of loop for 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);        /* Confidence intervalle of pij  */
                   /*printf(fignu*/        /*
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */          fprintf(ficgp,"\nset noparametric;unset label");
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   if(first==1){          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                     first=0;          fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);
                     fprintf(ficgp,"\nset parametric;unset label");          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                     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 out \"pijgr%s.png\"",optionfilefiname);
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\        */
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\  
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\        first1=1;
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);        for (k2=1; k2<=(nlstate);k2++){
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);          for (l2=1; l2<=(nlstate+ndeath);l2++){
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);            if(l2==k2) continue;
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);            j=(k2-1)*(nlstate+ndeath)+l2;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);            for (k1=1; k1<=(nlstate);k1++){
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);              for (l1=1; l1<=(nlstate+ndeath);l1++){
                     fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\                if(l1==k1) continue;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                i=(k1-1)*(nlstate+ndeath)+l1;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                if(i<=j) continue;
                   }else{                for (age=bage; age<=fage; age ++){
                     first=0;                  if ((int)age %5==0){
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                     fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\                    mu1=mu[i][(int) age]/stepm*YEARM ;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                    mu2=mu[j][(int) age]/stepm*YEARM;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                    c12=cv12/sqrt(v1*v2);
                   }/* if first */                    /* Computing eigen value of matrix of covariance */
                 } /* age mod 5 */                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
               } /* end loop age */                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    /* Eigen vectors */
               first=1;                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
             } /*l12 */                    /*v21=sqrt(1.-v11*v11); *//* error */
           } /* k12 */                    v21=(lc1-v1)/cv12*v11;
         } /*l1 */                    v12=-v21;
       }/* k1 */                    v22=v11;
     } /* loop covariates */                    tnalp=v21/v11;
   }                    if(first1==1){
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);                      first1=0;
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);                      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);
   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));                    }
   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);                    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);
   free_vector(xp,1,npar);                    /*printf(fignu*/
   fclose(ficresprob);                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
   fclose(ficresprobcov);                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
   fclose(ficresprobcor);                    if(first==1){
   fflush(ficgp);                      first=0;
   fflush(fichtmcov);                      fprintf(ficgp,"\nset parametric;unset label");
 }                      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");
                       fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 /******************* Printing html file ***********/   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   int lastpass, int stepm, int weightopt, char model[],\                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   int popforecast, int estepm ,\                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   double jprev1, double mprev1,double anprev1, \                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   double jprev2, double mprev2,double anprev2){                      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   int jj1, k1, i1, cpt;                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                       fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \                      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",\
    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 </ul>");                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \                    }else{
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",                      first=0;
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
    fprintf(fichtm,"\                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));                      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",\
    fprintf(fichtm,"\                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));                    }/* if first */
    fprintf(fichtm,"\                  } /* age mod 5 */
  - (a) Life expectancies by health status at initial age, (b) health expectancies by health status at initial age:  ei., eij (estepm=%2d months): \                } /* end loop age */
    <a href=\"%s\">%s</a> <br>\n</li>",                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));                first=1;
               } /*l12 */
             } /* k12 */
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");          } /*l1 */
         }/* k1 */
  m=cptcoveff;      } /* loop covariates */
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}    }
     free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
  jj1=0;    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
  for(k1=1; k1<=m;k1++){    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
    for(i1=1; i1<=ncodemax[k1];i1++){    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
      jj1++;    free_vector(xp,1,npar);
      if (cptcovn > 0) {    fclose(ficresprob);
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");    fclose(ficresprobcov);
        for (cpt=1; cpt<=cptcoveff;cpt++)     fclose(ficresprobcor);
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    fflush(ficgp);
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");    fflush(fichtmcov);
      }  }
      /* Pij */  
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \  
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);       /******************* Printing html file ***********/
      /* Quasi-incidences */  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\                    int lastpass, int stepm, int weightopt, char model[],\
  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> \                    int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);                     int popforecast, int estepm ,\
        /* Period (stable) prevalence in each health state */                    double jprev1, double mprev1,double anprev1, \
        for(cpt=1; cpt<nlstate;cpt++){                    double jprev2, double mprev2,double anprev2){
          fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \    int jj1, k1, i1, cpt;
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);  
        }     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
      for(cpt=1; cpt<=nlstate;cpt++) {     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
         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> \  </ul>");
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
      }   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
    } /* end i1 */             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
  }/* End k1 */     fprintf(fichtm,"\
  fprintf(fichtm,"</ul>");   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
              stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
      fprintf(fichtm,"\
  fprintf(fichtm,"\   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);     fprintf(fichtm,"\
    - (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," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",     <a href=\"%s\">%s</a> <br>\n",
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",   - Population projections by age and states: \
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
   
  fprintf(fichtm,"\  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",  
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));   m=cptcoveff;
  fprintf(fichtm,"\   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
  - 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): \  
    <a href=\"%s\">%s</a> <br>\n</li>",   jj1=0;
            estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));   for(k1=1; k1<=m;k1++){
  fprintf(fichtm,"\     for(i1=1; i1<=ncodemax[k1];i1++){
  - (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): \       jj1++;
    <a href=\"%s\">%s</a> <br>\n</li>",       if (cptcovn > 0) {
            estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
  fprintf(fichtm,"\         for (cpt=1; cpt<=cptcoveff;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," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
  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",       /* Pij */
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \
  fprintf(fichtm,"\  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\       /* Quasi-incidences */
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) 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> \
 /*  if(popforecast==1) fprintf(fichtm,"\n */  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */         /* Period (stable) prevalence in each health state */
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */         for(cpt=1; cpt<nlstate;cpt++){
 /*      <br>",fileres,fileres,fileres,fileres); */           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
 /*  else  */  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */         }
  fflush(fichtm);       for(cpt=1; cpt<=nlstate;cpt++) {
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");          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> \
   <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
  m=cptcoveff;       }
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}     } /* end i1 */
    }/* End k1 */
  jj1=0;   fprintf(fichtm,"</ul>");
  for(k1=1; k1<=m;k1++){  
    for(i1=1; i1<=ncodemax[k1];i1++){  
      jj1++;   fprintf(fichtm,"\
      if (cptcovn > 0) {  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
        for (cpt=1; cpt<=cptcoveff;cpt++)   
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");           subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
      }   fprintf(fichtm,"\
      for(cpt=1; cpt<=nlstate;cpt++) {   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\  
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);     fprintf(fichtm,"\
      }   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 health expectancies in states (1) and (2): %s%d.png<br>\   fprintf(fichtm,"\
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);   - 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): \
    } /* end i1 */     <a href=\"%s\">%s</a> <br>\n</li>",
  }/* End k1 */             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
  fprintf(fichtm,"</ul>");   fprintf(fichtm,"\
  fflush(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): \
 }     <a href=\"%s\">%s</a> <br>\n</li>",
              estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 /******************* Gnuplot file **************/   fprintf(fichtm,"\
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){   - 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"));
   char dirfileres[132],optfileres[132];   fprintf(fichtm,"\
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;   - 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",
   int ng;           subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */   fprintf(fichtm,"\
 /*     printf("Problem with file %s",optionfilegnuplot); */   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 /*   } */  
   /*  if(popforecast==1) fprintf(fichtm,"\n */
   /*#ifdef windows */  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
   fprintf(ficgp,"cd \"%s\" \n",pathc);  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
     /*#endif */  /*      <br>",fileres,fileres,fileres,fileres); */
   m=pow(2,cptcoveff);  /*  else  */
   /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
   strcpy(dirfileres,optionfilefiname);   fflush(fichtm);
   strcpy(optfileres,"vpl");   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
  /* 1eme*/  
   for (cpt=1; cpt<= nlstate ; cpt ++) {   m=cptcoveff;
    for (k1=1; k1<= m ; k1 ++) {   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);  
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);   jj1=0;
      fprintf(ficgp,"set xlabel \"Age\" \n\   for(k1=1; k1<=m;k1++){
 set ylabel \"Probability\" \n\     for(i1=1; i1<=ncodemax[k1];i1++){
 set ter png small\n\       jj1++;
 set size 0.65,0.65\n\       if (cptcovn > 0) {
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
          for (cpt=1; cpt<=cptcoveff;cpt++)
      for (i=1; i<= nlstate ; i ++) {           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        else fprintf(ficgp," \%%*lf (\%%*lf)");       }
      }       for(cpt=1; cpt<=nlstate;cpt++) {
      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);         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
      for (i=1; i<= nlstate ; i ++) {  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
        else fprintf(ficgp," \%%*lf (\%%*lf)");       }
      }        fprintf(fichtm,"\n<br>- Total life expectancy by age and \
      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);   health expectancies in states (1) and (2): %s%d.png<br>\
      for (i=1; i<= nlstate ; i ++) {  <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");     } /* end i1 */
        else fprintf(ficgp," \%%*lf (\%%*lf)");   }/* End k1 */
      }     fprintf(fichtm,"</ul>");
      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));   fflush(fichtm);
    }  }
   }  
   /*2 eme*/  /******************* Gnuplot file **************/
     void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   for (k1=1; k1<= m ; k1 ++) {   
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);    char dirfileres[132],optfileres[132];
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
         int ng;
     for (i=1; i<= nlstate+1 ; i ++) {  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
       k=2*i;  /*     printf("Problem with file %s",optionfilegnuplot); */
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);  /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
       for (j=1; j<= nlstate+1 ; j ++) {  /*   } */
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");  
         else fprintf(ficgp," \%%*lf (\%%*lf)");    /*#ifdef windows */
       }       fprintf(ficgp,"cd \"%s\" \n",pathc);
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");      /*#endif */
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);    m=pow(2,cptcoveff);
       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 ++) {    strcpy(dirfileres,optionfilefiname);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");    strcpy(optfileres,"vpl");
         else fprintf(ficgp," \%%*lf (\%%*lf)");   /* 1eme*/
       }       for (cpt=1; cpt<= nlstate ; cpt ++) {
       fprintf(ficgp,"\" t\"\" w l 0,");     for (k1=1; k1<= m ; k1 ++) {
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
       for (j=1; j<= nlstate+1 ; j ++) {       fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");       fprintf(ficgp,"set xlabel \"Age\" \n\
         else fprintf(ficgp," \%%*lf (\%%*lf)");  set ylabel \"Probability\" \n\
       }     set ter png small\n\
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");  set size 0.65,0.65\n\
       else fprintf(ficgp,"\" t\"\" w l 0,");  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
     }  
   }       for (i=1; i<= nlstate ; i ++) {
            if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
   /*3eme*/         else fprintf(ficgp," \%%*lf (\%%*lf)");
          }
   for (k1=1; k1<= m ; k1 ++) {        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 (cpt=1; cpt<= nlstate ; cpt ++) {       for (i=1; i<= nlstate ; i ++) {
       /*       k=2+nlstate*(2*cpt-2); */         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       k=2+(nlstate+1)*(cpt-1);         else fprintf(ficgp," \%%*lf (\%%*lf)");
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);       }
       fprintf(ficgp,"set ter png small\n\       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);
 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);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);         else fprintf(ficgp," \%%*lf (\%%*lf)");
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");       }  
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);       fprintf(ficgp,"\" t\"\" w l 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
         fprintf(ficgp,",\"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);    /*2 eme*/
            
       */    for (k1=1; k1<= m ; k1 ++) {
       for (i=1; i< nlstate ; i ++) {      fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
         fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
         /*      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 (i=1; i<= nlstate+1 ; i ++) {
       }         k=2*i;
       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
     }        for (j=1; j<= nlstate+1 ; j ++) {
   }          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
             else fprintf(ficgp," \%%*lf (\%%*lf)");
   /* CV preval stable (period) */        }  
   for (k1=1; k1<= m ; k1 ++) {         if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
     for (cpt=1; cpt<=nlstate ; cpt ++) {        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
       k=3;        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);        for (j=1; j<= nlstate+1 ; j ++) {
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 set ter png small\nset size 0.65,0.65\n\          else fprintf(ficgp," \%%*lf (\%%*lf)");
 unset log y\n\        }  
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);        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 (i=1; i< nlstate ; i ++)        for (j=1; j<= nlstate+1 ; j ++) {
         fprintf(ficgp,"+$%d",k+i+1);          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);          else fprintf(ficgp," \%%*lf (\%%*lf)");
               }  
       l=3+(nlstate+ndeath)*cpt;        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);        else fprintf(ficgp,"\" t\"\" w l 0,");
       for (i=1; i< nlstate ; i ++) {      }
         l=3+(nlstate+ndeath)*cpt;    }
         fprintf(ficgp,"+$%d",l+i+1);   
       }    /*3eme*/
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);      
     }     for (k1=1; k1<= m ; k1 ++) {
   }        for (cpt=1; cpt<= nlstate ; cpt ++) {
           /*       k=2+nlstate*(2*cpt-2); */
   /* proba elementaires */        k=2+(nlstate+1)*(cpt-1);
   for(i=1,jk=1; i <=nlstate; i++){        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
     for(k=1; k <=(nlstate+ndeath); k++){        fprintf(ficgp,"set ter png small\n\
       if (k != i) {  set size 0.65,0.65\n\
         for(j=1; j <=ncovmodel; j++){  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
           jk++;           for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
           fprintf(ficgp,"\n");          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
         }          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
       }          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
     }          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
    }         
         */
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/        for (i=1; i< nlstate ; i ++) {
      for(jk=1; jk <=m; jk++) {          fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);           /*      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 (ng==2)         
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");        }
        else        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,"\nset title \"Probability\"\n");      }
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);    }
        i=1;   
        for(k2=1; k2<=nlstate; k2++) {    /* CV preval stable (period) */
          k3=i;    for (k1=1; k1<= m ; k1 ++) {
          for(k=1; k<=(nlstate+ndeath); k++) {      for (cpt=1; cpt<=nlstate ; cpt ++) {
            if (k != k2){        k=3;
              if(ng==2)        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
              else  set ter png small\nset size 0.65,0.65\n\
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);  unset log y\n\
              ij=1;  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
              for(j=3; j <=ncovmodel; j++) {       
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {        for (i=1; i< nlstate ; i ++)
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);          fprintf(ficgp,"+$%d",k+i+1);
                  ij++;        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
                }       
                else        l=3+(nlstate+ndeath)*cpt;
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
              }        for (i=1; i< nlstate ; i ++) {
              fprintf(ficgp,")/(1");          l=3+(nlstate+ndeath)*cpt;
                        fprintf(ficgp,"+$%d",l+i+1);
              for(k1=1; k1 <=nlstate; k1++){           }
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+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]]]);    /* proba elementaires */
                    ij++;    for(i=1,jk=1; i <=nlstate; i++){
                  }      for(k=1; k <=(nlstate+ndeath); k++){
                  else        if (k != i) {
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);          for(j=1; j <=ncovmodel; j++){
                }            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                fprintf(ficgp,")");            jk++;
              }            fprintf(ficgp,"\n");
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);          }
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");        }
              i=i+ncovmodel;      }
            }     }
          } /* end k */  
        } /* end k2 */     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
      } /* end jk */       for(jk=1; jk <=m; jk++) {
    } /* end ng */         fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
    fflush(ficgp);          if (ng==2)
 }  /* end gnuplot */           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
          else
            fprintf(ficgp,"\nset title \"Probability\"\n");
 /*************** Moving average **************/         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){         i=1;
          for(k2=1; k2<=nlstate; k2++) {
   int i, cpt, cptcod;           k3=i;
   int modcovmax =1;           for(k=1; k<=(nlstate+ndeath); k++) {
   int mobilavrange, mob;             if (k != k2){
   double age;               if(ng==2)
                  fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose                else
                            a covariate has 2 modalities */                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */               ij=1;
                for(j=3; j <=ncovmodel; j++) {
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
     if(mobilav==1) mobilavrange=5; /* default */                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
     else mobilavrange=mobilav;                   ij++;
     for (age=bage; age<=fage; age++)                 }
       for (i=1; i<=nlstate;i++)                 else
         for (cptcod=1;cptcod<=modcovmax;cptcod++)                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];               }
     /* We keep the original values on the extreme ages bage, fage and for                fprintf(ficgp,")/(1");
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2               
        we use a 5 terms etc. until the borders are no more concerned.                for(k1=1; k1 <=nlstate; k1++){  
     */                  fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
     for (mob=3;mob <=mobilavrange;mob=mob+2){                 ij=1;
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){                 for(j=3; j <=ncovmodel; j++){
         for (i=1; i<=nlstate;i++){                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
           for (cptcod=1;cptcod<=modcovmax;cptcod++){                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];                     ij++;
               for (cpt=1;cpt<=(mob-1)/2;cpt++){                   }
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];                   else
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
               }                 }
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;                 fprintf(ficgp,")");
           }               }
         }               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
       }/* end age */               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
     }/* end mob */               i=i+ncovmodel;
   }else return -1;             }
   return 0;           } /* end k */
 }/* End movingaverage */         } /* end k2 */
        } /* end jk */
      } /* end ng */
 /************** Forecasting ******************/     fflush(ficgp);
 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){  }  /* end gnuplot */
   /* proj1, year, month, day of starting projection   
      agemin, agemax range of age  
      dateprev1 dateprev2 range of dates during which prevalence is computed  /*************** Moving average **************/
      anproj2 year of en of projection (same day and month as proj1).  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
   */  
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;    int i, cpt, cptcod;
   int *popage;    int modcovmax =1;
   double agec; /* generic age */    int mobilavrange, mob;
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;    double age;
   double *popeffectif,*popcount;  
   double ***p3mat;    modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
   double ***mobaverage;                             a covariate has 2 modalities */
   char fileresf[FILENAMELENGTH];    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
   
   agelim=AGESUP;    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);      if(mobilav==1) mobilavrange=5; /* default */
        else mobilavrange=mobilav;
   strcpy(fileresf,"f");       for (age=bage; age<=fage; age++)
   strcat(fileresf,fileres);        for (i=1; i<=nlstate;i++)
   if((ficresf=fopen(fileresf,"w"))==NULL) {          for (cptcod=1;cptcod<=modcovmax;cptcod++)
     printf("Problem with forecast resultfile: %s\n", fileresf);            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);      /* 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
   printf("Computing forecasting: result on file '%s' \n", fileresf);         we use a 5 terms etc. until the borders are no more concerned.
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);      */
       for (mob=3;mob <=mobilavrange;mob=mob+2){
   if (cptcoveff==0) ncodemax[cptcoveff]=1;        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
           for (i=1; i<=nlstate;i++){
   if (mobilav!=0) {            for (cptcod=1;cptcod<=modcovmax;cptcod++){
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){                for (cpt=1;cpt<=(mob-1)/2;cpt++){
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
       printf(" Error in movingaverage mobilav=%d\n",mobilav);                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
     }                }
   }              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
             }
   stepsize=(int) (stepm+YEARM-1)/YEARM;          }
   if (stepm<=12) stepsize=1;        }/* end age */
   if(estepm < stepm){      }/* end mob */
     printf ("Problem %d lower than %d\n",estepm, stepm);    }else return -1;
   }    return 0;
   else  hstepm=estepm;     }/* End movingaverage */
   
   hstepm=hstepm/stepm;   
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and  /************** Forecasting ******************/
                                fractional in yp1 */  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){
   anprojmean=yp;    /* proj1, year, month, day of starting projection
   yp2=modf((yp1*12),&yp);       agemin, agemax range of age
   mprojmean=yp;       dateprev1 dateprev2 range of dates during which prevalence is computed
   yp1=modf((yp2*30.5),&yp);       anproj2 year of en of projection (same day and month as proj1).
   jprojmean=yp;    */
   if(jprojmean==0) jprojmean=1;    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
   if(mprojmean==0) jprojmean=1;    int *popage;
     double agec; /* generic age */
   i1=cptcoveff;    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
   if (cptcovn < 1){i1=1;}    double *popeffectif,*popcount;
       double ***p3mat;
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);     double ***mobaverage;
       char fileresf[FILENAMELENGTH];
   fprintf(ficresf,"#****** Routine prevforecast **\n");  
     agelim=AGESUP;
 /*            if (h==(int)(YEARM*yearp)){ */    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){   
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    strcpy(fileresf,"f");
       k=k+1;    strcat(fileresf,fileres);
       fprintf(ficresf,"\n#******");    if((ficresf=fopen(fileresf,"w"))==NULL) {
       for(j=1;j<=cptcoveff;j++) {      printf("Problem with forecast resultfile: %s\n", fileresf);
         fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
       }    }
       fprintf(ficresf,"******\n");    printf("Computing forecasting: result on file '%s' \n", fileresf);
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
       for(j=1; j<=nlstate+ndeath;j++){   
         for(i=1; i<=nlstate;i++)                  if (cptcoveff==0) ncodemax[cptcoveff]=1;
           fprintf(ficresf," p%d%d",i,j);  
         fprintf(ficresf," p.%d",j);    if (mobilav!=0) {
       }      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {       if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
         fprintf(ficresf,"\n");        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);           printf(" Error in movingaverage mobilav=%d\n",mobilav);
       }
         for (agec=fage; agec>=(ageminpar-1); agec--){     }
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);   
           nhstepm = nhstepm/hstepm;     stepsize=(int) (stepm+YEARM-1)/YEARM;
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    if (stepm<=12) stepsize=1;
           oldm=oldms;savm=savms;    if(estepm < stepm){
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);        printf ("Problem %d lower than %d\n",estepm, stepm);
             }
           for (h=0; h<=nhstepm; h++){    else  hstepm=estepm;  
             if (h*hstepm/YEARM*stepm ==yearp) {  
               fprintf(ficresf,"\n");    hstepm=hstepm/stepm;
               for(j=1;j<=cptcoveff;j++)     yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);                                 fractional in yp1 */
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);    anprojmean=yp;
             }     yp2=modf((yp1*12),&yp);
             for(j=1; j<=nlstate+ndeath;j++) {    mprojmean=yp;
               ppij=0.;    yp1=modf((yp2*30.5),&yp);
               for(i=1; i<=nlstate;i++) {    jprojmean=yp;
                 if (mobilav==1)     if(jprojmean==0) jprojmean=1;
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];    if(mprojmean==0) jprojmean=1;
                 else {  
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];    i1=cptcoveff;
                 }    if (cptcovn < 1){i1=1;}
                 if (h*hstepm/YEARM*stepm== yearp) {   
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);    fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
                 }   
               } /* end i */    fprintf(ficresf,"#****** Routine prevforecast **\n");
               if (h*hstepm/YEARM*stepm==yearp) {  
                 fprintf(ficresf," %.3f", ppij);  /*            if (h==(int)(YEARM*yearp)){ */
               }    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
             }/* end j */      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
           } /* end h */        k=k+1;
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        fprintf(ficresf,"\n#******");
         } /* end agec */        for(j=1;j<=cptcoveff;j++) {
       } /* end yearp */          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]]);
     } /* end cptcod */        }
   } /* end  cptcov */        fprintf(ficresf,"******\n");
                fprintf(ficresf,"# Covariate valuofcovar yearproj age");
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        for(j=1; j<=nlstate+ndeath;j++){
           for(i=1; i<=nlstate;i++)              
   fclose(ficresf);            fprintf(ficresf," p%d%d",i,j);
 }          fprintf(ficresf," p.%d",j);
         }
 /************** Forecasting *****not tested NB*************/        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 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");
             fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;  
   int *popage;          for (agec=fage; agec>=(ageminpar-1); agec--){
   double calagedatem, agelim, kk1, kk2;            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
   double *popeffectif,*popcount;            nhstepm = nhstepm/hstepm;
   double ***p3mat,***tabpop,***tabpopprev;            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double ***mobaverage;            oldm=oldms;savm=savms;
   char filerespop[FILENAMELENGTH];            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
          
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            for (h=0; h<=nhstepm; h++){
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);              if (h*hstepm/YEARM*stepm ==yearp) {
   agelim=AGESUP;                fprintf(ficresf,"\n");
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;                for(j=1;j<=cptcoveff;j++)
                     fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                 }
                 for(j=1; j<=nlstate+ndeath;j++) {
   strcpy(filerespop,"pop");                 ppij=0.;
   strcat(filerespop,fileres);                for(i=1; i<=nlstate;i++) {
   if((ficrespop=fopen(filerespop,"w"))==NULL) {                  if (mobilav==1)
     printf("Problem with forecast resultfile: %s\n", filerespop);                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);                  else {
   }                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
   printf("Computing forecasting: result on file '%s' \n", filerespop);                  }
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);                  if (h*hstepm/YEARM*stepm== yearp) {
                     fprintf(ficresf," %.3f", p3mat[i][j][h]);
   if (cptcoveff==0) ncodemax[cptcoveff]=1;                  }
                 } /* end i */
   if (mobilav!=0) {                if (h*hstepm/YEARM*stepm==yearp) {
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                  fprintf(ficresf," %.3f", ppij);
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){                }
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);              }/* end j */
       printf(" Error in movingaverage mobilav=%d\n",mobilav);            } /* end h */
     }            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   }          } /* end agec */
         } /* end yearp */
   stepsize=(int) (stepm+YEARM-1)/YEARM;      } /* end cptcod */
   if (stepm<=12) stepsize=1;    } /* end  cptcov */
            
   agelim=AGESUP;    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     
   hstepm=1;    fclose(ficresf);
   hstepm=hstepm/stepm;   }
     
   if (popforecast==1) {  /************** Forecasting *****not tested NB*************/
     if((ficpop=fopen(popfile,"r"))==NULL) {  populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
       printf("Problem with population file : %s\n",popfile);exit(0);   
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
     }     int *popage;
     popage=ivector(0,AGESUP);    double calagedatem, agelim, kk1, kk2;
     popeffectif=vector(0,AGESUP);    double *popeffectif,*popcount;
     popcount=vector(0,AGESUP);    double ***p3mat,***tabpop,***tabpopprev;
         double ***mobaverage;
     i=1;       char filerespop[FILENAMELENGTH];
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;  
        tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     imx=i;    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];    agelim=AGESUP;
   }    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
    
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){   
       k=k+1;   
       fprintf(ficrespop,"\n#******");    strcpy(filerespop,"pop");
       for(j=1;j<=cptcoveff;j++) {    strcat(filerespop,fileres);
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);    if((ficrespop=fopen(filerespop,"w"))==NULL) {
       }      printf("Problem with forecast resultfile: %s\n", filerespop);
       fprintf(ficrespop,"******\n");      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
       fprintf(ficrespop,"# Age");    }
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);    printf("Computing forecasting: result on file '%s' \n", filerespop);
       if (popforecast==1)  fprintf(ficrespop," [Population]");    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
         
       for (cpt=0; cpt<=0;cpt++) {     if (cptcoveff==0) ncodemax[cptcoveff]=1;
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);     
             if (mobilav!=0) {
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);       if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
           nhstepm = nhstepm/hstepm;         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   printf(" Error in movingaverage mobilav=%d\n",mobilav);
           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);    
             stepsize=(int) (stepm+YEARM-1)/YEARM;
           for (h=0; h<=nhstepm; h++){    if (stepm<=12) stepsize=1;
             if (h==(int) (calagedatem+YEARM*cpt)) {   
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);    agelim=AGESUP;
             }    
             for(j=1; j<=nlstate+ndeath;j++) {    hstepm=1;
               kk1=0.;kk2=0;    hstepm=hstepm/stepm;
               for(i=1; i<=nlstate;i++) {                 
                 if (mobilav==1)     if (popforecast==1) {
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];      if((ficpop=fopen(popfile,"r"))==NULL) {
                 else {        printf("Problem with population file : %s\n",popfile);exit(0);
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];        fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                 }      }
               }      popage=ivector(0,AGESUP);
               if (h==(int)(calagedatem+12*cpt)){      popeffectif=vector(0,AGESUP);
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;      popcount=vector(0,AGESUP);
                   /*fprintf(ficrespop," %.3f", kk1);     
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/      i=1;  
               }      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
             }     
             for(i=1; i<=nlstate;i++){      imx=i;
               kk1=0.;      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                 for(j=1; j<=nlstate;j++){    }
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];   
                 }    for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
             }        k=k+1;
         fprintf(ficrespop,"\n#******");
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)         for(j=1;j<=cptcoveff;j++) {
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           }        }
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        fprintf(ficrespop,"******\n");
         }        fprintf(ficrespop,"# Age");
       }        for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
          if (popforecast==1)  fprintf(ficrespop," [Population]");
   /******/       
         for (cpt=0; cpt<=0;cpt++) {
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {           fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);            
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){           for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
           nhstepm = nhstepm/hstepm;             nhstepm = nhstepm/hstepm;
                      
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           oldm=oldms;savm=savms;            oldm=oldms;savm=savms;
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);              hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
           for (h=0; h<=nhstepm; h++){         
             if (h==(int) (calagedatem+YEARM*cpt)) {            for (h=0; h<=nhstepm; h++){
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);              if (h==(int) (calagedatem+YEARM*cpt)) {
             }                 fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
             for(j=1; j<=nlstate+ndeath;j++) {              }
               kk1=0.;kk2=0;              for(j=1; j<=nlstate+ndeath;j++) {
               for(i=1; i<=nlstate;i++) {                              kk1=0.;kk2=0;
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];                    for(i=1; i<=nlstate;i++) {              
               }                  if (mobilav==1)
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                            kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
             }                  else {
           }                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                  }
         }                }
       }                if (h==(int)(calagedatem+12*cpt)){
    }                   tabpop[(int)(agedeb)][j][cptcod]=kk1;
   }                    /*fprintf(ficrespop," %.3f", kk1);
                        if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                }
               }
   if (popforecast==1) {              for(i=1; i<=nlstate;i++){
     free_ivector(popage,0,AGESUP);                kk1=0.;
     free_vector(popeffectif,0,AGESUP);                  for(j=1; j<=nlstate;j++){
     free_vector(popcount,0,AGESUP);                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
   }                  }
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);              }
   fclose(ficrespop);  
 } /* End of popforecast */              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
                 fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 int fileappend(FILE *fichier, char *optionfich)            }
 {            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   if((fichier=fopen(optionfich,"a"))==NULL) {          }
     printf("Problem with file: %s\n", optionfich);        }
     fprintf(ficlog,"Problem with file: %s\n", optionfich);   
     return (0);    /******/
   }  
   fflush(fichier);        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
   return (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--){
             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
             nhstepm = nhstepm/hstepm;
 /**************** function prwizard **********************/           
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)            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);  
   /* Wizard to print covariance matrix template */            for (h=0; h<=nhstepm; h++){
               if (h==(int) (calagedatem+YEARM*cpt)) {
   char ca[32], cb[32], cc[32];                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;              }
   int numlinepar;              for(j=1; j<=nlstate+ndeath;j++) {
                 kk1=0.;kk2=0;
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");                for(i=1; i<=nlstate;i++) {              
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
   for(i=1; i <=nlstate; i++){                }
     jj=0;                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
     for(j=1; j <=nlstate+ndeath; j++){              }
       if(j==i) continue;            }
       jj++;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       /*ca[0]= k+'a'-1;ca[1]='\0';*/          }
       printf("%1d%1d",i,j);        }
       fprintf(ficparo,"%1d%1d",i,j);     }
       for(k=1; k<=ncovmodel;k++){    }
         /*        printf(" %lf",param[i][j][k]); */   
         /*        fprintf(ficparo," %lf",param[i][j][k]); */    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         printf(" 0.");  
         fprintf(ficparo," 0.");    if (popforecast==1) {
       }      free_ivector(popage,0,AGESUP);
       printf("\n");      free_vector(popeffectif,0,AGESUP);
       fprintf(ficparo,"\n");      free_vector(popcount,0,AGESUP);
     }    }
   }    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   printf("# Scales (for hessian or gradient estimation)\n");    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");    fclose(ficrespop);
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/   } /* End of popforecast */
   for(i=1; i <=nlstate; i++){  
     jj=0;  int fileappend(FILE *fichier, char *optionfich)
     for(j=1; j <=nlstate+ndeath; j++){  {
       if(j==i) continue;    if((fichier=fopen(optionfich,"a"))==NULL) {
       jj++;      printf("Problem with file: %s\n", optionfich);
       fprintf(ficparo,"%1d%1d",i,j);      fprintf(ficlog,"Problem with file: %s\n", optionfich);
       printf("%1d%1d",i,j);      return (0);
       fflush(stdout);    }
       for(k=1; k<=ncovmodel;k++){    fflush(fichier);
         /*      printf(" %le",delti3[i][j][k]); */    return (1);
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */  }
         printf(" 0.");  
         fprintf(ficparo," 0.");  
       }  /**************** function prwizard **********************/
       numlinepar++;  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
       printf("\n");  {
       fprintf(ficparo,"\n");  
     }    /* Wizard to print covariance matrix template */
   }  
   printf("# Covariance matrix\n");    char ca[32], cb[32], cc[32];
 /* # 121 Var(a12)\n\ */    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
 /* # 122 Cov(b12,a12) Var(b12)\n\ */    int numlinepar;
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */  
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */    for(i=1; i <=nlstate; i++){
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */      jj=0;
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */      for(j=1; j <=nlstate+ndeath; j++){
   fflush(stdout);        if(j==i) continue;
   fprintf(ficparo,"# Covariance matrix\n");        jj++;
   /* # 121 Var(a12)\n\ */        /*ca[0]= k+'a'-1;ca[1]='\0';*/
   /* # 122 Cov(b12,a12) Var(b12)\n\ */        printf("%1d%1d",i,j);
   /* #   ...\n\ */        fprintf(ficparo,"%1d%1d",i,j);
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */        for(k=1; k<=ncovmodel;k++){
             /*        printf(" %lf",param[i][j][k]); */
   for(itimes=1;itimes<=2;itimes++){          /*        fprintf(ficparo," %lf",param[i][j][k]); */
     jj=0;          printf(" 0.");
     for(i=1; i <=nlstate; i++){          fprintf(ficparo," 0.");
       for(j=1; j <=nlstate+ndeath; j++){        }
         if(j==i) continue;        printf("\n");
         for(k=1; k<=ncovmodel;k++){        fprintf(ficparo,"\n");
           jj++;      }
           ca[0]= k+'a'-1;ca[1]='\0';    }
           if(itimes==1){    printf("# Scales (for hessian or gradient estimation)\n");
             printf("#%1d%1d%d",i,j,k);    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
             fprintf(ficparo,"#%1d%1d%d",i,j,k);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
           }else{    for(i=1; i <=nlstate; i++){
             printf("%1d%1d%d",i,j,k);      jj=0;
             fprintf(ficparo,"%1d%1d%d",i,j,k);      for(j=1; j <=nlstate+ndeath; j++){
             /*  printf(" %.5le",matcov[i][j]); */        if(j==i) continue;
           }        jj++;
           ll=0;        fprintf(ficparo,"%1d%1d",i,j);
           for(li=1;li <=nlstate; li++){        printf("%1d%1d",i,j);
             for(lj=1;lj <=nlstate+ndeath; lj++){        fflush(stdout);
               if(lj==li) continue;        for(k=1; k<=ncovmodel;k++){
               for(lk=1;lk<=ncovmodel;lk++){          /*      printf(" %le",delti3[i][j][k]); */
                 ll++;          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                 if(ll<=jj){          printf(" 0.");
                   cb[0]= lk +'a'-1;cb[1]='\0';          fprintf(ficparo," 0.");
                   if(ll<jj){        }
                     if(itimes==1){        numlinepar++;
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);        printf("\n");
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);        fprintf(ficparo,"\n");
                     }else{      }
                       printf(" 0.");    }
                       fprintf(ficparo," 0.");    printf("# Covariance matrix\n");
                     }  /* # 121 Var(a12)\n\ */
                   }else{  /* # 122 Cov(b12,a12) Var(b12)\n\ */
                     if(itimes==1){  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                       printf(" Var(%s%1d%1d)",ca,i,j);  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);  /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                     }else{  /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                       printf(" 0.");  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                       fprintf(ficparo," 0.");  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                     }    fflush(stdout);
                   }    fprintf(ficparo,"# Covariance matrix\n");
                 }    /* # 121 Var(a12)\n\ */
               } /* end lk */    /* # 122 Cov(b12,a12) Var(b12)\n\ */
             } /* end lj */    /* #   ...\n\ */
           } /* end li */    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
           printf("\n");   
           fprintf(ficparo,"\n");    for(itimes=1;itimes<=2;itimes++){
           numlinepar++;      jj=0;
         } /* end k*/      for(i=1; i <=nlstate; i++){
       } /*end j */        for(j=1; j <=nlstate+ndeath; j++){
     } /* end i */          if(j==i) continue;
   } /* end itimes */          for(k=1; k<=ncovmodel;k++){
             jj++;
 } /* end of prwizard */            ca[0]= k+'a'-1;ca[1]='\0';
 /******************* Gompertz Likelihood ******************************/            if(itimes==1){
 double gompertz(double x[])              printf("#%1d%1d%d",i,j,k);
 {               fprintf(ficparo,"#%1d%1d%d",i,j,k);
   double A,B,L=0.0,sump=0.,num=0.;            }else{
   int i,n=0; /* n is the size of the sample */              printf("%1d%1d%d",i,j,k);
               fprintf(ficparo,"%1d%1d%d",i,j,k);
   for (i=0;i<=imx-1 ; i++) {              /*  printf(" %.5le",matcov[i][j]); */
     sump=sump+weight[i];            }
     /*    sump=sump+1;*/            ll=0;
     num=num+1;            for(li=1;li <=nlstate; li++){
   }              for(lj=1;lj <=nlstate+ndeath; lj++){
                  if(lj==li) continue;
                  for(lk=1;lk<=ncovmodel;lk++){
   /* for (i=0; i<=imx; i++)                   ll++;
      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]);*/                  if(ll<=jj){
                     cb[0]= lk +'a'-1;cb[1]='\0';
   for (i=1;i<=imx ; i++)                    if(ll<jj){
     {                      if(itimes==1){
       if (cens[i] == 1 && wav[i]>1)                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                             }else{
       if (cens[i] == 0 && wav[i]>1)                        printf(" 0.");
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))                        fprintf(ficparo," 0.");
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);                        }
                           }else{
       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */                      if(itimes==1){
       if (wav[i] > 1 ) { /* ??? */                        printf(" Var(%s%1d%1d)",ca,i,j);
         L=L+A*weight[i];                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
         /*      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]);*/                      }else{
       }                        printf(" 0.");
     }                        fprintf(ficparo," 0.");
                       }
  /*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;                } /* end lk */
 }              } /* end lj */
             } /* end li */
 /******************* Printing html file ***********/            printf("\n");
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \            fprintf(ficparo,"\n");
                   int lastpass, int stepm, int weightopt, char model[],\            numlinepar++;
                   int imx,  double p[],double **matcov,double agemortsup){          } /* end k*/
   int i,k;        } /*end j */
       } /* end i */
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");    } /* end itimes */
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);  
   for (i=1;i<=2;i++)   } /* end of prwizard */
     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]));  /******************* Gompertz Likelihood ******************************/
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");  double gompertz(double x[])
   fprintf(fichtm,"</ul>");  {
     double A,B,L=0.0,sump=0.,num=0.;
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");    int i,n=0; /* n is the size of the sample */
   
  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 (i=0;i<=imx-1 ; i++) {
       sump=sump+weight[i];
  for (k=agegomp;k<(agemortsup-2);k++)       /*    sump=sump+1;*/
    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]);      num=num+1;
     }
     
   fflush(fichtm);   
 }    /* for (i=0; i<=imx; i++)
        if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
 /******************* Gnuplot file **************/  
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){    for (i=1;i<=imx ; i++)
       {
   char dirfileres[132],optfileres[132];        if (cens[i] == 1 && wav[i]>1)
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
   int ng;       
         if (cens[i] == 0 && wav[i]>1)
           A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
   /*#ifdef windows */               +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
   fprintf(ficgp,"cd \"%s\" \n",pathc);       
     /*#endif */        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
         if (wav[i] > 1 ) { /* ??? */
           L=L+A*weight[i];
   strcpy(dirfileres,optionfilefiname);          /*      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]);*/
   strcpy(optfileres,"vpl");        }
   fprintf(ficgp,"set out \"graphmort.png\"\n ");       }
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");   
   fprintf(ficgp, "set ter png small\n set log y\n");    /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
   fprintf(ficgp, "set size 0.65,0.65\n");   
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);    return -2*L*num/sump;
   }
 }   
   /******************* Printing html file ***********/
   void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                     int lastpass, int stepm, int weightopt, char model[],\
                     int imx,  double p[],double **matcov,double agemortsup){
     int i,k;
 /***********************************************/  
 /**************** Main Program *****************/    fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 /***********************************************/    fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
     for (i=1;i<=2;i++)
 int main(int argc, char *argv[])      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\">");
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);    fprintf(fichtm,"</ul>");
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;  
   int linei, month, year,iout;  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
   int jj, ll, li, lj, lk, imk;  
   int numlinepar=0; /* Current linenumber of parameter file */   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>");
   int itimes;  
   int NDIM=2;   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]);
   char ca[32], cb[32], cc[32];  
   char dummy[]="                         ";   
   /*  FILE *fichtm; *//* Html File */    fflush(fichtm);
   /* FILE *ficgp;*/ /*Gnuplot File */  }
   struct stat info;  
   double agedeb, agefin,hf;  /******************* Gnuplot file **************/
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   
   double fret;    char dirfileres[132],optfileres[132];
   double **xi,tmp,delta;    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     int ng;
   double dum; /* Dummy variable */  
   double ***p3mat;  
   double ***mobaverage;    /*#ifdef windows */
   int *indx;    fprintf(ficgp,"cd \"%s\" \n",pathc);
   char line[MAXLINE], linepar[MAXLINE];      /*#endif */
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];  
   char pathr[MAXLINE], pathimach[MAXLINE];   
   char **bp, *tok, *val; /* pathtot */    strcpy(dirfileres,optionfilefiname);
   int firstobs=1, lastobs=10;    strcpy(optfileres,"vpl");
   int sdeb, sfin; /* Status at beginning and end */    fprintf(ficgp,"set out \"graphmort.png\"\n ");
   int c,  h , cpt,l;    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
   int ju,jl, mi;    fprintf(ficgp, "set ter png small\n set log y\n");
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;    fprintf(ficgp, "set size 0.65,0.65\n");
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;     fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */  
   int mobilav=0,popforecast=0;  }
   int hstepm, nhstepm;  
   int agemortsup;  
   float  sumlpop=0.;  
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;  
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;  
   /***********************************************/
   double bage, fage, age, agelim, agebase;  /**************** Main Program *****************/
   double ftolpl=FTOL;  /***********************************************/
   double **prlim;  
   double *severity;  int main(int argc, char *argv[])
   double ***param; /* Matrix of parameters */  {
   double  *p;    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
   double **matcov; /* Matrix of covariance */    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
   double ***delti3; /* Scale */    int linei, month, year,iout;
   double *delti; /* Scale */    int jj, ll, li, lj, lk, imk;
   double ***eij, ***vareij;    int numlinepar=0; /* Current linenumber of parameter file */
   double **varpl; /* Variances of prevalence limits by age */    int itimes;
   double *epj, vepp;    int NDIM=2;
   double kk1, kk2;  
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;    char ca[32], cb[32], cc[32];
   double **ximort;    char dummy[]="                         ";
   char *alph[]={"a","a","b","c","d","e"}, str[4];    /*  FILE *fichtm; *//* Html File */
   int *dcwave;    /* FILE *ficgp;*/ /*Gnuplot File */
     struct stat info;
   char z[1]="c", occ;    double agedeb, agefin,hf;
     double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];  
   char  *strt, strtend[80];    double fret;
   char *stratrunc;    double **xi,tmp,delta;
   int lstra;  
     double dum; /* Dummy variable */
   long total_usecs;    double ***p3mat;
      double ***mobaverage;
 /*   setlocale (LC_ALL, ""); */    int *indx;
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */    char line[MAXLINE], linepar[MAXLINE];
 /*   textdomain (PACKAGE); */    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 /*   setlocale (LC_CTYPE, ""); */    char pathr[MAXLINE], pathimach[MAXLINE];
 /*   setlocale (LC_MESSAGES, ""); */    char **bp, *tok, *val; /* pathtot */
     int firstobs=1, lastobs=10;
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */    int sdeb, sfin; /* Status at beginning and end */
   (void) gettimeofday(&start_time,&tzp);    int c,  h , cpt,l;
   curr_time=start_time;    int ju,jl, mi;
   tm = *localtime(&start_time.tv_sec);    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
   tmg = *gmtime(&start_time.tv_sec);    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
   strcpy(strstart,asctime(&tm));    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
     int mobilav=0,popforecast=0;
 /*  printf("Localtime (at start)=%s",strstart); */    int hstepm, nhstepm;
 /*  tp.tv_sec = tp.tv_sec +86400; */    int agemortsup;
 /*  tm = *localtime(&start_time.tv_sec); */    float  sumlpop=0.;
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */    double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 /*   tmg.tm_hour=tmg.tm_hour + 1; */  
 /*   tp.tv_sec = mktime(&tmg); */    double bage, fage, age, agelim, agebase;
 /*   strt=asctime(&tmg); */    double ftolpl=FTOL;
 /*   printf("Time(after) =%s",strstart);  */    double **prlim;
 /*  (void) time (&time_value);    double *severity;
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);    double ***param; /* Matrix of parameters */
 *  tm = *localtime(&time_value);    double  *p;
 *  strstart=asctime(&tm);    double **matcov; /* Matrix of covariance */
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);     double ***delti3; /* Scale */
 */    double *delti; /* Scale */
     double ***eij, ***vareij;
   nberr=0; /* Number of errors and warnings */    double **varpl; /* Variances of prevalence limits by age */
   nbwarn=0;    double *epj, vepp;
   getcwd(pathcd, size);    double kk1, kk2;
     double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
   printf("\n%s\n%s",version,fullversion);    double **ximort;
   if(argc <=1){    char *alph[]={"a","a","b","c","d","e"}, str[4];
     printf("\nEnter the parameter file name: ");    int *dcwave;
     fgets(pathr,FILENAMELENGTH,stdin);  
     i=strlen(pathr);    char z[1]="c", occ;
     if(pathr[i-1]=='\n')  
       pathr[i-1]='\0';    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
    for (tok = pathr; tok != NULL; ){    char  *strt, strtend[80];
       printf("Pathr |%s|\n",pathr);    char *stratrunc;
       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');    int lstra;
       printf("val= |%s| pathr=%s\n",val,pathr);  
       strcpy (pathtot, val);    long total_usecs;
       if(pathr[0] == '\0') break; /* Dirty */   
     }  /*   setlocale (LC_ALL, ""); */
   }  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
   else{  /*   textdomain (PACKAGE); */
     strcpy(pathtot,argv[1]);  /*   setlocale (LC_CTYPE, ""); */
   }  /*   setlocale (LC_MESSAGES, ""); */
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/  
   /*cygwin_split_path(pathtot,path,optionfile);    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/    (void) gettimeofday(&start_time,&tzp);
   /* cutv(path,optionfile,pathtot,'\\');*/    curr_time=start_time;
     tm = *localtime(&start_time.tv_sec);
   /* Split argv[0], imach program to get pathimach */    tmg = *gmtime(&start_time.tv_sec);
   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);    strcpy(strstart,asctime(&tm));
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);  
   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);  /*  printf("Localtime (at start)=%s",strstart); */
  /*   strcpy(pathimach,argv[0]); */  /*  tp.tv_sec = tp.tv_sec +86400; */
   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */  /*  tm = *localtime(&start_time.tv_sec); */
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
   chdir(path); /* Can be a relative path */  /*   tmg.tm_hour=tmg.tm_hour + 1; */
   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */  /*   tp.tv_sec = mktime(&tmg); */
     printf("Current directory %s!\n",pathcd);  /*   strt=asctime(&tmg); */
   strcpy(command,"mkdir ");  /*   printf("Time(after) =%s",strstart);  */
   strcat(command,optionfilefiname);  /*  (void) time (&time_value);
   if((outcmd=system(command)) != 0){  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);  *  tm = *localtime(&time_value);
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */  *  strstart=asctime(&tm);
     /* fclose(ficlog); */  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
 /*     exit(1); */  */
   }  
 /*   if((imk=mkdir(optionfilefiname))<0){ */    nberr=0; /* Number of errors and warnings */
 /*     perror("mkdir"); */    nbwarn=0;
 /*   } */    getcwd(pathcd, size);
   
   /*-------- arguments in the command line --------*/    printf("\n%s\n%s",version,fullversion);
     if(argc <=1){
   /* Log file */      printf("\nEnter the parameter file name: ");
   strcat(filelog, optionfilefiname);      fgets(pathr,FILENAMELENGTH,stdin);
   strcat(filelog,".log");    /* */      i=strlen(pathr);
   if((ficlog=fopen(filelog,"w"))==NULL)    {      if(pathr[i-1]=='\n')
     printf("Problem with logfile %s\n",filelog);        pathr[i-1]='\0';
     goto end;     for (tok = pathr; tok != NULL; ){
   }        printf("Pathr |%s|\n",pathr);
   fprintf(ficlog,"Log filename:%s\n",filelog);        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
   fprintf(ficlog,"\n%s\n%s",version,fullversion);        printf("val= |%s| pathr=%s\n",val,pathr);
   fprintf(ficlog,"\nEnter the parameter file name: \n");        strcpy (pathtot, val);
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\        if(pathr[0] == '\0') break; /* Dirty */
  path=%s \n\      }
  optionfile=%s\n\    }
  optionfilext=%s\n\    else{
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);      strcpy(pathtot,argv[1]);
     }
   printf("Local time (at start):%s",strstart);    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
   fprintf(ficlog,"Local time (at start): %s",strstart);    /*cygwin_split_path(pathtot,path,optionfile);
   fflush(ficlog);      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 /*   (void) gettimeofday(&curr_time,&tzp); */    /* cutv(path,optionfile,pathtot,'\\');*/
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */  
     /* Split argv[0], imach program to get pathimach */
   /* */    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
   strcpy(fileres,"r");    split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   strcat(fileres, optionfilefiname);    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   strcat(fileres,".txt");    /* Other files have txt extension */   /*   strcpy(pathimach,argv[0]); */
     /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
   /*---------arguments file --------*/    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
     printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
   if((ficpar=fopen(optionfile,"r"))==NULL)    {    chdir(path); /* Can be a relative path */
     printf("Problem with optionfile %s\n",optionfile);    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);      printf("Current directory %s!\n",pathcd);
     fflush(ficlog);    strcpy(command,"mkdir ");
     goto end;    strcat(command,optionfilefiname);
   }    if((outcmd=system(command)) != 0){
       printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
       /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
       /* fclose(ficlog); */
   strcpy(filereso,"o");  /*     exit(1); */
   strcat(filereso,fileres);    }
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */  /*   if((imk=mkdir(optionfilefiname))<0){ */
     printf("Problem with Output resultfile: %s\n", filereso);  /*     perror("mkdir"); */
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);  /*   } */
     fflush(ficlog);  
     goto end;    /*-------- arguments in the command line --------*/
   }  
     /* Log file */
   /* Reads comments: lines beginning with '#' */    strcat(filelog, optionfilefiname);
   numlinepar=0;    strcat(filelog,".log");    /* */
   while((c=getc(ficpar))=='#' && c!= EOF){    if((ficlog=fopen(filelog,"w"))==NULL)    {
     ungetc(c,ficpar);      printf("Problem with logfile %s\n",filelog);
     fgets(line, MAXLINE, ficpar);      goto end;
     numlinepar++;    }
     puts(line);    fprintf(ficlog,"Log filename:%s\n",filelog);
     fputs(line,ficparo);    fprintf(ficlog,"\n%s\n%s",version,fullversion);
     fputs(line,ficlog);    fprintf(ficlog,"\nEnter the parameter file name: \n");
   }    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
   ungetc(c,ficpar);   path=%s \n\
    optionfile=%s\n\
   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);   optionfilext=%s\n\
   numlinepar++;   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);  
   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    printf("Local time (at start):%s",strstart);
   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    fprintf(ficlog,"Local time (at start): %s",strstart);
   fflush(ficlog);    fflush(ficlog);
   while((c=getc(ficpar))=='#' && c!= EOF){  /*   (void) gettimeofday(&curr_time,&tzp); */
     ungetc(c,ficpar);  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
     fgets(line, MAXLINE, ficpar);  
     numlinepar++;    /* */
     puts(line);    strcpy(fileres,"r");
     fputs(line,ficparo);    strcat(fileres, optionfilefiname);
     fputs(line,ficlog);    strcat(fileres,".txt");    /* Other files have txt extension */
   }  
   ungetc(c,ficpar);    /*---------arguments file --------*/
   
        if((ficpar=fopen(optionfile,"r"))==NULL)    {
   covar=matrix(0,NCOVMAX,1,n);       printf("Problem with optionfile %s\n",optionfile);
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;      fflush(ficlog);
       goto end;
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */    }
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */  
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/  
   
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    strcpy(filereso,"o");
   delti=delti3[1][1];    strcat(filereso,fileres);
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */      printf("Problem with Output resultfile: %s\n", filereso);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);      fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);      fflush(ficlog);
     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);      goto end;
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);     }
     fclose (ficparo);  
     fclose (ficlog);    /* Reads comments: lines beginning with '#' */
     exit(0);    numlinepar=0;
   }    while((c=getc(ficpar))=='#' && c!= EOF){
   else if(mle==-3) {      ungetc(c,ficpar);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);      fgets(line, MAXLINE, ficpar);
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);      numlinepar++;
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);      puts(line);
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      fputs(line,ficparo);
     matcov=matrix(1,npar,1,npar);      fputs(line,ficlog);
   }    }
   else{    ungetc(c,ficpar);
     /* Read guess parameters */  
     /* Reads comments: lines beginning with '#' */    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);
     while((c=getc(ficpar))=='#' && c!= EOF){    numlinepar++;
       ungetc(c,ficpar);    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);
       fgets(line, MAXLINE, ficpar);    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);
       numlinepar++;    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);
       puts(line);    fflush(ficlog);
       fputs(line,ficparo);    while((c=getc(ficpar))=='#' && c!= EOF){
       fputs(line,ficlog);      ungetc(c,ficpar);
     }      fgets(line, MAXLINE, ficpar);
     ungetc(c,ficpar);      numlinepar++;
           puts(line);
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      fputs(line,ficparo);
     for(i=1; i <=nlstate; i++){      fputs(line,ficlog);
       j=0;    }
       for(jj=1; jj <=nlstate+ndeath; jj++){    ungetc(c,ficpar);
         if(jj==i) continue;  
         j++;     
         fscanf(ficpar,"%1d%1d",&i1,&j1);    covar=matrix(0,NCOVMAX,1,n);
         if ((i1 != i) && (j1 != j)){    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
           exit(1);  
         }    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
         fprintf(ficparo,"%1d%1d",i1,j1);    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
         if(mle==1)    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
           printf("%1d%1d",i,j);  
         fprintf(ficlog,"%1d%1d",i,j);    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         for(k=1; k<=ncovmodel;k++){    delti=delti3[1][1];
           fscanf(ficpar," %lf",&param[i][j][k]);    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
           if(mle==1){    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
             printf(" %lf",param[i][j][k]);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
             fprintf(ficlog," %lf",param[i][j][k]);      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           }      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
           else      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
             fprintf(ficlog," %lf",param[i][j][k]);      fclose (ficparo);
           fprintf(ficparo," %lf",param[i][j][k]);      fclose (ficlog);
         }      goto end;
         fscanf(ficpar,"\n");      exit(0);
         numlinepar++;    }
         if(mle==1)    else if(mle==-3) {
           printf("\n");      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
         fprintf(ficlog,"\n");      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
         fprintf(ficparo,"\n");      fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
       }      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     }        matcov=matrix(1,npar,1,npar);
     fflush(ficlog);    }
     else{
     p=param[1][1];      /* Read guess parameters */
           /* Reads comments: lines beginning with '#' */
     /* Reads comments: lines beginning with '#' */      while((c=getc(ficpar))=='#' && c!= EOF){
     while((c=getc(ficpar))=='#' && c!= EOF){        ungetc(c,ficpar);
       ungetc(c,ficpar);        fgets(line, MAXLINE, ficpar);
       fgets(line, MAXLINE, ficpar);        numlinepar++;
       numlinepar++;        puts(line);
       puts(line);        fputs(line,ficparo);
       fputs(line,ficparo);        fputs(line,ficlog);
       fputs(line,ficlog);      }
     }      ungetc(c,ficpar);
     ungetc(c,ficpar);     
       param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     for(i=1; i <=nlstate; i++){      for(i=1; i <=nlstate; i++){
       for(j=1; j <=nlstate+ndeath-1; j++){        j=0;
         fscanf(ficpar,"%1d%1d",&i1,&j1);        for(jj=1; jj <=nlstate+ndeath; jj++){
         if ((i1-i)*(j1-j)!=0){          if(jj==i) continue;
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);          j++;
           exit(1);          fscanf(ficpar,"%1d%1d",&i1,&j1);
         }          if ((i1 != i) && (j1 != j)){
         printf("%1d%1d",i,j);            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
         fprintf(ficparo,"%1d%1d",i1,j1);  It might be a problem of design; if ncovcol and the model are correct\n \
         fprintf(ficlog,"%1d%1d",i1,j1);  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
         for(k=1; k<=ncovmodel;k++){            exit(1);
           fscanf(ficpar,"%le",&delti3[i][j][k]);          }
           printf(" %le",delti3[i][j][k]);          fprintf(ficparo,"%1d%1d",i1,j1);
           fprintf(ficparo," %le",delti3[i][j][k]);          if(mle==1)
           fprintf(ficlog," %le",delti3[i][j][k]);            printf("%1d%1d",i,j);
         }          fprintf(ficlog,"%1d%1d",i,j);
         fscanf(ficpar,"\n");          for(k=1; k<=ncovmodel;k++){
         numlinepar++;            fscanf(ficpar," %lf",&param[i][j][k]);
         printf("\n");            if(mle==1){
         fprintf(ficparo,"\n");              printf(" %lf",param[i][j][k]);
         fprintf(ficlog,"\n");              fprintf(ficlog," %lf",param[i][j][k]);
       }            }
     }            else
     fflush(ficlog);              fprintf(ficlog," %lf",param[i][j][k]);
             fprintf(ficparo," %lf",param[i][j][k]);
     delti=delti3[1][1];          }
           fscanf(ficpar,"\n");
           numlinepar++;
     /* 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)
               printf("\n");
     /* Reads comments: lines beginning with '#' */          fprintf(ficlog,"\n");
     while((c=getc(ficpar))=='#' && c!= EOF){          fprintf(ficparo,"\n");
       ungetc(c,ficpar);        }
       fgets(line, MAXLINE, ficpar);      }  
       numlinepar++;      fflush(ficlog);
       puts(line);  
       fputs(line,ficparo);      p=param[1][1];
       fputs(line,ficlog);     
     }      /* Reads comments: lines beginning with '#' */
     ungetc(c,ficpar);      while((c=getc(ficpar))=='#' && c!= EOF){
           ungetc(c,ficpar);
     matcov=matrix(1,npar,1,npar);        fgets(line, MAXLINE, ficpar);
     for(i=1; i <=npar; i++){        numlinepar++;
       fscanf(ficpar,"%s",&str);        puts(line);
       if(mle==1)        fputs(line,ficparo);
         printf("%s",str);        fputs(line,ficlog);
       fprintf(ficlog,"%s",str);      }
       fprintf(ficparo,"%s",str);      ungetc(c,ficpar);
       for(j=1; j <=i; j++){  
         fscanf(ficpar," %le",&matcov[i][j]);      for(i=1; i <=nlstate; i++){
         if(mle==1){        for(j=1; j <=nlstate+ndeath-1; j++){
           printf(" %.5le",matcov[i][j]);          fscanf(ficpar,"%1d%1d",&i1,&j1);
         }          if ((i1-i)*(j1-j)!=0){
         fprintf(ficlog," %.5le",matcov[i][j]);            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
         fprintf(ficparo," %.5le",matcov[i][j]);            exit(1);
       }          }
       fscanf(ficpar,"\n");          printf("%1d%1d",i,j);
       numlinepar++;          fprintf(ficparo,"%1d%1d",i1,j1);
       if(mle==1)          fprintf(ficlog,"%1d%1d",i1,j1);
         printf("\n");          for(k=1; k<=ncovmodel;k++){
       fprintf(ficlog,"\n");            fscanf(ficpar,"%le",&delti3[i][j][k]);
       fprintf(ficparo,"\n");            printf(" %le",delti3[i][j][k]);
     }            fprintf(ficparo," %le",delti3[i][j][k]);
     for(i=1; i <=npar; i++)            fprintf(ficlog," %le",delti3[i][j][k]);
       for(j=i+1;j<=npar;j++)          }
         matcov[i][j]=matcov[j][i];          fscanf(ficpar,"\n");
               numlinepar++;
     if(mle==1)          printf("\n");
       printf("\n");          fprintf(ficparo,"\n");
     fprintf(ficlog,"\n");          fprintf(ficlog,"\n");
             }
     fflush(ficlog);      }
           fflush(ficlog);
     /*-------- Rewriting parameter file ----------*/  
     strcpy(rfileres,"r");    /* "Rparameterfile */      delti=delti3[1][1];
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/  
     strcat(rfileres,".");    /* */  
     strcat(rfileres,optionfilext);    /* Other files have txt extension */      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
     if((ficres =fopen(rfileres,"w"))==NULL) {   
       printf("Problem writing new parameter file: %s\n", fileres);goto end;      /* Reads comments: lines beginning with '#' */
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;      while((c=getc(ficpar))=='#' && c!= EOF){
     }        ungetc(c,ficpar);
     fprintf(ficres,"#%s\n",version);        fgets(line, MAXLINE, ficpar);
   }    /* End of mle != -3 */        numlinepar++;
         puts(line);
   /*-------- data file ----------*/        fputs(line,ficparo);
   if((fic=fopen(datafile,"r"))==NULL)    {        fputs(line,ficlog);
     printf("Problem while opening datafile: %s\n", datafile);goto end;      }
     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;      ungetc(c,ficpar);
   }   
       matcov=matrix(1,npar,1,npar);
   n= lastobs;      for(i=1; i <=npar; i++){
   severity = vector(1,maxwav);        fscanf(ficpar,"%s",&str);
   outcome=imatrix(1,maxwav+1,1,n);        if(mle==1)
   num=lvector(1,n);          printf("%s",str);
   moisnais=vector(1,n);        fprintf(ficlog,"%s",str);
   annais=vector(1,n);        fprintf(ficparo,"%s",str);
   moisdc=vector(1,n);        for(j=1; j <=i; j++){
   andc=vector(1,n);          fscanf(ficpar," %le",&matcov[i][j]);
   agedc=vector(1,n);          if(mle==1){
   cod=ivector(1,n);            printf(" %.5le",matcov[i][j]);
   weight=vector(1,n);          }
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */          fprintf(ficlog," %.5le",matcov[i][j]);
   mint=matrix(1,maxwav,1,n);          fprintf(ficparo," %.5le",matcov[i][j]);
   anint=matrix(1,maxwav,1,n);        }
   s=imatrix(1,maxwav+1,1,n);        fscanf(ficpar,"\n");
   tab=ivector(1,NCOVMAX);        numlinepar++;
   ncodemax=ivector(1,8);        if(mle==1)
           printf("\n");
   i=1;        fprintf(ficlog,"\n");
   linei=0;        fprintf(ficparo,"\n");
   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {      }
     linei=linei+1;      for(i=1; i <=npar; i++)
     for(j=strlen(line); j>=0;j--){  /* Untabifies line */        for(j=i+1;j<=npar;j++)
       if(line[j] == '\t')          matcov[i][j]=matcov[j][i];
         line[j] = ' ';     
     }      if(mle==1)
     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){        printf("\n");
       ;      fprintf(ficlog,"\n");
     };     
     line[j+1]=0;  /* Trims blanks at end of line */      fflush(ficlog);
     if(line[0]=='#'){     
       fprintf(ficlog,"Comment line\n%s\n",line);      /*-------- Rewriting parameter file ----------*/
       printf("Comment line\n%s\n",line);      strcpy(rfileres,"r");    /* "Rparameterfile */
       continue;      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
     }      strcat(rfileres,".");    /* */
       strcat(rfileres,optionfilext);    /* Other files have txt extension */
     for (j=maxwav;j>=1;j--){      if((ficres =fopen(rfileres,"w"))==NULL) {
       cutv(stra, strb,line,' ');         printf("Problem writing new parameter file: %s\n", fileres);goto end;
       errno=0;        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
       lval=strtol(strb,&endptr,10);       }
       /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/      fprintf(ficres,"#%s\n",version);
       if( strb[0]=='\0' || (*endptr != '\0')){    }    /* End of mle != -3 */
         printf("Error reading data around '%d' at line number %d %s for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);  
         exit(1);    /*-------- data file ----------*/
       }    if((fic=fopen(datafile,"r"))==NULL)    {
       s[j][i]=lval;      printf("Problem while opening datafile: %s\n", datafile);goto end;
             fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
       strcpy(line,stra);    }
       cutv(stra, strb,line,' ');  
       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){    n= lastobs;
       }    severity = vector(1,maxwav);
       else  if(iout=sscanf(strb,"%s.") != 0){    outcome=imatrix(1,maxwav+1,1,n);
         month=99;    num=lvector(1,n);
         year=9999;    moisnais=vector(1,n);
       }else{    annais=vector(1,n);
         printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);    moisdc=vector(1,n);
         exit(1);    andc=vector(1,n);
       }    agedc=vector(1,n);
       anint[j][i]= (double) year;     cod=ivector(1,n);
       mint[j][i]= (double)month;     weight=vector(1,n);
       strcpy(line,stra);    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
     } /* ENd Waves */    mint=matrix(1,maxwav,1,n);
         anint=matrix(1,maxwav,1,n);
     cutv(stra, strb,line,' ');     s=imatrix(1,maxwav+1,1,n);
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){    tab=ivector(1,NCOVMAX);
     }    ncodemax=ivector(1,8);
     else  if(iout=sscanf(strb,"%s.",dummy) != 0){  
       month=99;    i=1;
       year=9999;    linei=0;
     }else{    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
       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);      linei=linei+1;
       exit(1);      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
     }        if(line[j] == '\t')
     andc[i]=(double) year;           line[j] = ' ';
     moisdc[i]=(double) month;       }
     strcpy(line,stra);      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
             ;
     cutv(stra, strb,line,' ');       };
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){      line[j+1]=0;  /* Trims blanks at end of line */
     }      if(line[0]=='#'){
     else  if(iout=sscanf(strb,"%s.") != 0){        fprintf(ficlog,"Comment line\n%s\n",line);
       month=99;        printf("Comment line\n%s\n",line);
       year=9999;        continue;
     }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);  
       exit(1);      for (j=maxwav;j>=1;j--){
     }        cutv(stra, strb,line,' ');
     annais[i]=(double)(year);        errno=0;
     moisnais[i]=(double)(month);         lval=strtol(strb,&endptr,10);
     strcpy(line,stra);        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
             if( strb[0]=='\0' || (*endptr != '\0')){
     cutv(stra, strb,line,' ');           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);
     errno=0;          exit(1);
     lval=strtol(strb,&endptr,10);         }
     if( strb[0]=='\0' || (*endptr != '\0')){        s[j][i]=lval;
       printf("Error reading data around '%d' at line number %ld %s for individual %d\nShould be a weight.  Exiting.\n",lval, i,line,linei);       
       exit(1);        strcpy(line,stra);
     }        cutv(stra, strb,line,' ');
     weight[i]=(double)(lval);         if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     strcpy(line,stra);        }
             else  if(iout=sscanf(strb,"%s.") != 0){
     for (j=ncovcol;j>=1;j--){          month=99;
       cutv(stra, strb,line,' ');           year=9999;
       errno=0;        }else{
       lval=strtol(strb,&endptr,10);           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);
       if( strb[0]=='\0' || (*endptr != '\0')){          exit(1);
         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);        anint[j][i]= (double) year;
       }        mint[j][i]= (double)month;
       if(lval <-1 || lval >1){        strcpy(line,stra);
         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);      } /* ENd Waves */
         exit(1);     
       }      cutv(stra, strb,line,' ');
       covar[j][i]=(double)(lval);      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
       strcpy(line,stra);      }
     }       else  if(iout=sscanf(strb,"%s.",dummy) != 0){
     lstra=strlen(stra);        month=99;
             year=9999;
     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */      }else{
       stratrunc = &(stra[lstra-9]);        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);
       num[i]=atol(stratrunc);        exit(1);
     }      }
     else      andc[i]=(double) year;
       num[i]=atol(stra);      moisdc[i]=(double) month;
     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){      strcpy(line,stra);
       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;}*/     
           cutv(stra, strb,line,' ');
     i=i+1;      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
   } /* End loop reading  data */      }
   fclose(fic);      else  if(iout=sscanf(strb,"%s.") != 0){
   /* printf("ii=%d", ij);        month=99;
      scanf("%d",i);*/        year=9999;
   imx=i-1; /* Number of individuals */      }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);
   /* for (i=1; i<=imx; i++){        exit(1);
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;      }
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;      annais[i]=(double)(year);
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;      moisnais[i]=(double)(month);
     }*/      strcpy(line,stra);
    /*  for (i=1; i<=imx; i++){     
      if (s[4][i]==9)  s[4][i]=-1;       cutv(stra, strb,line,' ');
      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]));}*/      errno=0;
         dval=strtod(strb,&endptr);
   /* for (i=1; i<=imx; i++) */      if( strb[0]=='\0' || (*endptr != '\0')){
          printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;        exit(1);
      else weight[i]=1;*/      }
       weight[i]=dval;
   /* Calculation of the number of parameters from char model */      strcpy(line,stra);
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */     
   Tprod=ivector(1,15);       for (j=ncovcol;j>=1;j--){
   Tvaraff=ivector(1,15);         cutv(stra, strb,line,' ');
   Tvard=imatrix(1,15,1,2);        errno=0;
   Tage=ivector(1,15);              lval=strtol(strb,&endptr,10);
            if( strb[0]=='\0' || (*endptr != '\0')){
   if (strlen(model) >1){ /* If there is at least 1 covariate */          printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a covar (meaning 0 for the reference or 1).  Exiting.\n",lval, linei,i, line);
     j=0, j1=0, k1=1, k2=1;          exit(1);
     j=nbocc(model,'+'); /* j=Number of '+' */        }
     j1=nbocc(model,'*'); /* j1=Number of '*' */        if(lval <-1 || lval >1){
     cptcovn=j+1;           printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
     cptcovprod=j1; /*Number of products */   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
        for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
     strcpy(modelsav,model);    For example, for multinomial values like 1, 2 and 3,\n \
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){   build V1=0 V2=0 for the reference value (1),\n \
       printf("Error. Non available option model=%s ",model);          V1=1 V2=0 for (2) \n \
       fprintf(ficlog,"Error. Non available option model=%s ",model);   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
       goto end;   output of IMaCh is often meaningless.\n \
     }   Exiting.\n",lval,linei, i,line,j);
               exit(1);
     /* This loop fills the array Tvar from the string 'model'.*/        }
         covar[j][i]=(double)(lval);
     for(i=(j+1); i>=1;i--){        strcpy(line,stra);
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */       }
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */      lstra=strlen(stra);
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/     
       /*scanf("%d",i);*/      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
       if (strchr(strb,'*')) {  /* Model includes a product */        stratrunc = &(stra[lstra-9]);
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/        num[i]=atol(stratrunc);
         if (strcmp(strc,"age")==0) { /* Vn*age */      }
           cptcovprod--;      else
           cutv(strb,stre,strd,'V');        num[i]=atol(stra);
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
           cptcovage++;        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;}*/
             Tage[cptcovage]=i;     
             /*printf("stre=%s ", stre);*/      i=i+1;
         }    } /* End loop reading  data */
         else if (strcmp(strd,"age")==0) { /* or age*Vn */    fclose(fic);
           cptcovprod--;    /* printf("ii=%d", ij);
           cutv(strb,stre,strc,'V');       scanf("%d",i);*/
           Tvar[i]=atoi(stre);    imx=i-1; /* Number of individuals */
           cptcovage++;  
           Tage[cptcovage]=i;    /* for (i=1; i<=imx; i++){
         }      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
         else {  /* Age is not in the model */      if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
           Tvar[i]=ncovcol+k1;      }*/
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */     /*  for (i=1; i<=imx; i++){
           Tprod[k1]=i;       if (s[4][i]==9)  s[4][i]=-1;
           Tvard[k1][1]=atoi(strc); /* m*/       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]));}*/
           Tvard[k1][2]=atoi(stre); /* n */   
           Tvar[cptcovn+k2]=Tvard[k1][1];    /* for (i=1; i<=imx; i++) */
           Tvar[cptcovn+k2+1]=Tvard[k1][2];    
           for (k=1; k<=lastobs;k++)      /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];       else weight[i]=1;*/
           k1++;  
           k2=k2+2;    /* Calculation of the number of parameters from char model */
         }    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
       }    Tprod=ivector(1,15);
       else { /* no more sum */    Tvaraff=ivector(1,15);
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/    Tvard=imatrix(1,15,1,2);
        /*  scanf("%d",i);*/    Tage=ivector(1,15);      
       cutv(strd,strc,strb,'V');     
       Tvar[i]=atoi(strc);    if (strlen(model) >1){ /* If there is at least 1 covariate */
       }      j=0, j1=0, k1=1, k2=1;
       strcpy(modelsav,stra);        j=nbocc(model,'+'); /* j=Number of '+' */
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);      j1=nbocc(model,'*'); /* j1=Number of '*' */
         scanf("%d",i);*/      cptcovn=j+1;
     } /* end of loop + */      cptcovprod=j1; /*Number of products */
   } /* end model */     
         strcpy(modelsav,model);
   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/        printf("Error. Non available option model=%s ",model);
         fprintf(ficlog,"Error. Non available option model=%s ",model);
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);        goto end;
   printf("cptcovprod=%d ", cptcovprod);      }
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);     
       /* This loop fills the array Tvar from the string 'model'.*/
   scanf("%d ",i);*/  
       for(i=(j+1); i>=1;i--){
     /*  if(mle==1){*/        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
   if (weightopt != 1) { /* Maximisation without weights*/        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
     for(i=1;i<=n;i++) weight[i]=1.0;        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
   }        /*scanf("%d",i);*/
     /*-calculation of age at interview from date of interview and age at death -*/        if (strchr(strb,'*')) {  /* Model includes a product */
   agev=matrix(1,maxwav,1,imx);          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
           if (strcmp(strc,"age")==0) { /* Vn*age */
   for (i=1; i<=imx; i++) {            cptcovprod--;
     for(m=2; (m<= maxwav); m++) {            cutv(strb,stre,strd,'V');
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
         anint[m][i]=9999;            cptcovage++;
         s[m][i]=-1;              Tage[cptcovage]=i;
       }              /*printf("stre=%s ", stre);*/
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){          }
         nberr++;          else if (strcmp(strd,"age")==0) { /* or age*Vn */
         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);            cptcovprod--;
         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);            cutv(strb,stre,strc,'V');
         s[m][i]=-1;            Tvar[i]=atoi(stre);
       }            cptcovage++;
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){            Tage[cptcovage]=i;
         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 {  /* Age is not in the model */
         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]);             cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */            Tvar[i]=ncovcol+k1;
       }            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
     }            Tprod[k1]=i;
   }            Tvard[k1][1]=atoi(strc); /* m*/
             Tvard[k1][2]=atoi(stre); /* n */
   for (i=1; i<=imx; i++)  {            Tvar[cptcovn+k2]=Tvard[k1][1];
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);            Tvar[cptcovn+k2+1]=Tvard[k1][2];
     for(m=firstpass; (m<= lastpass); m++){            for (k=1; k<=lastobs;k++)
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
         if (s[m][i] >= nlstate+1) {            k1++;
           if(agedc[i]>0)            k2=k2+2;
             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 { /* no more sum */
             else {          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
               if ((int)andc[i]!=9999){         /*  scanf("%d",i);*/
                 nbwarn++;        cutv(strd,strc,strb,'V');
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);        Tvar[i]=atoi(strc);
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);        }
                 agev[m][i]=-1;        strcpy(modelsav,stra);  
               }        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
             }          scanf("%d",i);*/
         }      } /* end of loop + */
         else if(s[m][i] !=9){ /* Standard case, age in fractional    } /* end model */
                                  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]);    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
             agev[m][i]=1;  
           else if(agev[m][i] <agemin){     /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
             agemin=agev[m][i];    printf("cptcovprod=%d ", cptcovprod);
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
           }  
           else if(agev[m][i] >agemax){    scanf("%d ",i);*/
             agemax=agev[m][i];  
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/      /*  if(mle==1){*/
           }    if (weightopt != 1) { /* Maximisation without weights*/
           /*agev[m][i]=anint[m][i]-annais[i];*/      for(i=1;i<=n;i++) weight[i]=1.0;
           /*     agev[m][i] = age[i]+2*m;*/    }
         }      /*-calculation of age at interview from date of interview and age at death -*/
         else { /* =9 */    agev=matrix(1,maxwav,1,imx);
           agev[m][i]=1;  
           s[m][i]=-1;    for (i=1; i<=imx; i++) {
         }      for(m=2; (m<= maxwav); m++) {
       }        if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
       else /*= 0 Unknown */          anint[m][i]=9999;
         agev[m][i]=1;          s[m][i]=-1;
     }        }
             if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
   }          nberr++;
   for (i=1; i<=imx; i++)  {          printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
     for(m=firstpass; (m<=lastpass); m++){          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);
       if (s[m][i] > (nlstate+ndeath)) {          s[m][i]=-1;
         nberr++;        }
         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((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
         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);               nberr++;
         goto end;          printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]);
       }          fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]);
     }          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++){  
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);    for (i=1; i<=imx; i++)  {
 }      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
       for(m=firstpass; (m<= lastpass); m++){
 }*/        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
           if (s[m][i] >= nlstate+1) {
             if(agedc[i]>0)
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);                 agev[m][i]=agedc[i];
             /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
   agegomp=(int)agemin;              else {
   free_vector(severity,1,maxwav);                if ((int)andc[i]!=9999){
   free_imatrix(outcome,1,maxwav+1,1,n);                  nbwarn++;
   free_vector(moisnais,1,n);                  printf("Warning negative age at death: %ld line:%d\n",num[i],i);
   free_vector(annais,1,n);                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
   /* free_matrix(mint,1,maxwav,1,n);                  agev[m][i]=-1;
      free_matrix(anint,1,maxwav,1,n);*/                }
   free_vector(moisdc,1,n);              }
   free_vector(andc,1,n);          }
           else if(s[m][i] !=9){ /* Standard case, age in fractional
                                       years but with the precision of a month */
   wav=ivector(1,imx);            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
   dh=imatrix(1,lastpass-firstpass+1,1,imx);            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
   bh=imatrix(1,lastpass-firstpass+1,1,imx);              agev[m][i]=1;
   mw=imatrix(1,lastpass-firstpass+1,1,imx);            else if(agev[m][i] <agemin){
                  agemin=agev[m][i];
   /* Concatenates waves */              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);            }
             else if(agev[m][i] >agemax){
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */              agemax=agev[m][i];
               /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
   Tcode=ivector(1,100);            }
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);             /*agev[m][i]=anint[m][i]-annais[i];*/
   ncodemax[1]=1;            /*     agev[m][i] = age[i]+2*m;*/
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);          }
                 else { /* =9 */
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of             agev[m][i]=1;
                                  the estimations*/            s[m][i]=-1;
   h=0;          }
   m=pow(2,cptcoveff);        }
          else /*= 0 Unknown */
   for(k=1;k<=cptcoveff; k++){          agev[m][i]=1;
     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++){    }
           h++;    for (i=1; i<=imx; i++)  {
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;      for(m=firstpass; (m<=lastpass); m++){
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/        if (s[m][i] > (nlstate+ndeath)) {
         }           nberr++;
       }          printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);    
     }          fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);    
   }           goto end;
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);         }
      codtab[1][2]=1;codtab[2][2]=2; */      }
   /* for(i=1; i <=m ;i++){     }
      for(k=1; k <=cptcovn; k++){  
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);    /*for (i=1; i<=imx; i++){
      }    for (m=firstpass; (m<lastpass); m++){
      printf("\n");       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
      }  }
      scanf("%d",i);*/  
       }*/
   /*------------ gnuplot -------------*/  
   strcpy(optionfilegnuplot,optionfilefiname);  
   if(mle==-3)    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
     strcat(optionfilegnuplot,"-mort");    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
   strcat(optionfilegnuplot,".gp");  
     agegomp=(int)agemin;
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {    free_vector(severity,1,maxwav);
     printf("Problem with file %s",optionfilegnuplot);    free_imatrix(outcome,1,maxwav+1,1,n);
   }    free_vector(moisnais,1,n);
   else{    free_vector(annais,1,n);
     fprintf(ficgp,"\n# %s\n", version);     /* free_matrix(mint,1,maxwav,1,n);
     fprintf(ficgp,"# %s\n", optionfilegnuplot);        free_matrix(anint,1,maxwav,1,n);*/
     fprintf(ficgp,"set missing 'NaNq'\n");    free_vector(moisdc,1,n);
   }    free_vector(andc,1,n);
   /*  fclose(ficgp);*/  
   /*--------- index.htm --------*/     
     wav=ivector(1,imx);
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */    dh=imatrix(1,lastpass-firstpass+1,1,imx);
   if(mle==-3)    bh=imatrix(1,lastpass-firstpass+1,1,imx);
     strcat(optionfilehtm,"-mort");    mw=imatrix(1,lastpass-firstpass+1,1,imx);
   strcat(optionfilehtm,".htm");     
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {    /* Concatenates waves */
     printf("Problem with %s \n",optionfilehtm), exit(0);    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
   }  
     /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */  
   strcat(optionfilehtmcov,"-cov.htm");    Tcode=ivector(1,100);
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
     printf("Problem with %s \n",optionfilehtmcov), exit(0);    ncodemax[1]=1;
   }    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
   else{       
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
 <hr size=\"2\" color=\"#EC5E5E\"> \n\                                   the estimations*/
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\    h=0;
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);    m=pow(2,cptcoveff);
   }   
     for(k=1;k<=cptcoveff; k++){
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \      for(i=1; i <=(m/pow(2,k));i++){
 <hr size=\"2\" color=\"#EC5E5E\"> \n\        for(j=1; j <= ncodemax[k]; j++){
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
 \n\            h++;
 <hr  size=\"2\" color=\"#EC5E5E\">\            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
  <ul><li><h4>Parameter files</h4>\n\            /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\          }
  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\        }
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\      }
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\    }
  - Date and time at start: %s</ul>\n",\    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\       codtab[1][2]=1;codtab[2][2]=2; */
           optionfilefiname,optionfilext,optionfilefiname,optionfilext,\    /* for(i=1; i <=m ;i++){
           fileres,fileres,\       for(k=1; k <=cptcovn; k++){
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
   fflush(fichtm);       }
        printf("\n");
   strcpy(pathr,path);       }
   strcat(pathr,optionfilefiname);       scanf("%d",i);*/
   chdir(optionfilefiname); /* Move to directory named optionfile */     
       /*------------ gnuplot -------------*/
   /* Calculates basic frequencies. Computes observed prevalence at single age    strcpy(optionfilegnuplot,optionfilefiname);
      and prints on file fileres'p'. */    if(mle==-3)
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);      strcat(optionfilegnuplot,"-mort");
     strcat(optionfilegnuplot,".gp");
   fprintf(fichtm,"\n");  
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\      printf("Problem with file %s",optionfilegnuplot);
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\    }
           imx,agemin,agemax,jmin,jmax,jmean);    else{
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      fprintf(ficgp,"\n# %s\n", version);
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      fprintf(ficgp,"# %s\n", optionfilegnuplot);
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */      fprintf(ficgp,"set missing 'NaNq'\n");
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    }
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */    /*  fclose(ficgp);*/
         /*--------- index.htm --------*/
      
   /* For Powell, parameters are in a vector p[] starting at p[1]    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */    if(mle==-3)
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */      strcat(optionfilehtm,"-mort");
     strcat(optionfilehtm,".htm");
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
       printf("Problem with %s \n",optionfilehtm), exit(0);
   if (mle==-3){    }
     ximort=matrix(1,NDIM,1,NDIM);  
     cens=ivector(1,n);    strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
     ageexmed=vector(1,n);    strcat(optionfilehtmcov,"-cov.htm");
     agecens=vector(1,n);    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
     dcwave=ivector(1,n);      printf("Problem with %s \n",optionfilehtmcov), exit(0);
      }
     for (i=1; i<=imx; i++){    else{
       dcwave[i]=-1;    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
       for (m=firstpass; m<=lastpass; m++)  <hr size=\"2\" color=\"#EC5E5E\"> \n\
         if (s[m][i]>nlstate) {  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
           dcwave[i]=m;            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/    }
           break;  
         }    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><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\
     for (i=1; i<=imx; i++) {  \n\
       if (wav[i]>0){  <hr  size=\"2\" color=\"#EC5E5E\">\
         ageexmed[i]=agev[mw[1][i]][i];   <ul><li><h4>Parameter files</h4>\n\
         j=wav[i];   - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
         agecens[i]=1.;    - 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\
         if (ageexmed[i]> 1 && wav[i] > 0){   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
           agecens[i]=agev[mw[j][i]][i];   - Date and time at start: %s</ul>\n",\
           cens[i]= 1;            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
         }else if (ageexmed[i]< 1)             optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
           cens[i]= -1;            fileres,fileres,\
         if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)            filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
           cens[i]=0 ;    fflush(fichtm);
       }  
       else cens[i]=-1;    strcpy(pathr,path);
     }    strcat(pathr,optionfilefiname);
         chdir(optionfilefiname); /* Move to directory named optionfile */
     for (i=1;i<=NDIM;i++) {   
       for (j=1;j<=NDIM;j++)    /* Calculates basic frequencies. Computes observed prevalence at single age
         ximort[i][j]=(i == j ? 1.0 : 0.0);       and prints on file fileres'p'. */
     }    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
       
     p[1]=0.0268; p[NDIM]=0.083;    fprintf(fichtm,"\n");
     /*printf("%lf %lf", p[1], p[2]);*/    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
       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",\
     printf("Powell\n");  fprintf(ficlog,"Powell\n");            imx,agemin,agemax,jmin,jmax,jmean);
     strcpy(filerespow,"pow-mort");     pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     strcat(filerespow,fileres);      oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     if((ficrespow=fopen(filerespow,"w"))==NULL) {      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       printf("Problem with resultfile: %s\n", filerespow);      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
     }     
     fprintf(ficrespow,"# Powell\n# iter -2*LL");     
     /*  for (i=1;i<=nlstate;i++)    /* For Powell, parameters are in a vector p[] starting at p[1]
         for(j=1;j<=nlstate+ndeath;j++)       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);    p=param[1][1]; /* *(*(*(param +1)+1)+0) */
     */  
     fprintf(ficrespow,"\n");    globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
       
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);    if (mle==-3){
     fclose(ficrespow);      ximort=matrix(1,NDIM,1,NDIM);
           cens=ivector(1,n);
     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);       ageexmed=vector(1,n);
       agecens=vector(1,n);
     for(i=1; i <=NDIM; i++)      dcwave=ivector(1,n);
       for(j=i+1;j<=NDIM;j++)   
         matcov[i][j]=matcov[j][i];      for (i=1; i<=imx; i++){
             dcwave[i]=-1;
     printf("\nCovariance matrix\n ");        for (m=firstpass; m<=lastpass; m++)
     for(i=1; i <=NDIM; i++) {          if (s[m][i]>nlstate) {
       for(j=1;j<=NDIM;j++){             dcwave[i]=m;
         printf("%f ",matcov[i][j]);            /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
       }            break;
       printf("\n ");          }
     }      }
       
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);      for (i=1; i<=imx; i++) {
     for (i=1;i<=NDIM;i++)         if (wav[i]>0){
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));          ageexmed[i]=agev[mw[1][i]][i];
           j=wav[i];
     lsurv=vector(1,AGESUP);          agecens[i]=1.;
     lpop=vector(1,AGESUP);  
     tpop=vector(1,AGESUP);          if (ageexmed[i]> 1 && wav[i] > 0){
     lsurv[agegomp]=100000;            agecens[i]=agev[mw[j][i]][i];
                 cens[i]= 1;
     for (k=agegomp;k<=AGESUP;k++) {          }else if (ageexmed[i]< 1)
       agemortsup=k;            cens[i]= -1;
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;          if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
     }            cens[i]=0 ;
             }
     for (k=agegomp;k<agemortsup;k++)        else cens[i]=-1;
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));      }
          
     for (k=agegomp;k<agemortsup;k++){      for (i=1;i<=NDIM;i++) {
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;        for (j=1;j<=NDIM;j++)
       sumlpop=sumlpop+lpop[k];          ximort[i][j]=(i == j ? 1.0 : 0.0);
     }      }
          
     tpop[agegomp]=sumlpop;      p[1]=0.0268; p[NDIM]=0.083;
     for (k=agegomp;k<(agemortsup-3);k++){      /*printf("%lf %lf", p[1], p[2]);*/
       /*  tpop[k+1]=2;*/     
       tpop[k+1]=tpop[k]-lpop[k];     
     }      printf("Powell\n");  fprintf(ficlog,"Powell\n");
           strcpy(filerespow,"pow-mort");
           strcat(filerespow,fileres);
     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");      if((ficrespow=fopen(filerespow,"w"))==NULL) {
     for (k=agegomp;k<(agemortsup-2);k++)         printf("Problem with resultfile: %s\n", filerespow);
       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]);        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
           }
           fprintf(ficrespow,"# Powell\n# iter -2*LL");
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      /*  for (i=1;i<=nlstate;i++)
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);          for(j=1;j<=nlstate+ndeath;j++)
               if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \      */
                      stepm, weightopt,\      fprintf(ficrespow,"\n");
                      model,imx,p,matcov,agemortsup);     
           powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
     free_vector(lsurv,1,AGESUP);      fclose(ficrespow);
     free_vector(lpop,1,AGESUP);     
     free_vector(tpop,1,AGESUP);      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
   } /* Endof if mle==-3 */  
         for(i=1; i <=NDIM; i++)
   else{ /* For mle >=1 */        for(j=i+1;j<=NDIM;j++)
             matcov[i][j]=matcov[j][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);      printf("\nCovariance matrix\n ");
     for (k=1; k<=npar;k++)      for(i=1; i <=NDIM; i++) {
       printf(" %d %8.5f",k,p[k]);        for(j=1;j<=NDIM;j++){
     printf("\n");          printf("%f ",matcov[i][j]);
     globpr=1; /* to print the contributions */        }
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */        printf("\n ");
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);      }
     for (k=1; k<=npar;k++)     
       printf(" %d %8.5f",k,p[k]);      printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
     printf("\n");      for (i=1;i<=NDIM;i++)
     if(mle>=1){ /* Could be 1 or 2 */        printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);  
     }      lsurv=vector(1,AGESUP);
           lpop=vector(1,AGESUP);
     /*--------- results files --------------*/      tpop=vector(1,AGESUP);
     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);      lsurv[agegomp]=100000;
          
           for (k=agegomp;k<=AGESUP;k++) {
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        agemortsup=k;
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      }
     for(i=1,jk=1; i <=nlstate; i++){     
       for(k=1; k <=(nlstate+ndeath); k++){      for (k=agegomp;k<agemortsup;k++)
         if (k != i) {        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
           printf("%d%d ",i,k);     
           fprintf(ficlog,"%d%d ",i,k);      for (k=agegomp;k<agemortsup;k++){
           fprintf(ficres,"%1d%1d ",i,k);        lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
           for(j=1; j <=ncovmodel; j++){        sumlpop=sumlpop+lpop[k];
             printf("%f ",p[jk]);      }
             fprintf(ficlog,"%f ",p[jk]);     
             fprintf(ficres,"%f ",p[jk]);      tpop[agegomp]=sumlpop;
             jk++;       for (k=agegomp;k<(agemortsup-3);k++){
           }        /*  tpop[k+1]=2;*/
           printf("\n");        tpop[k+1]=tpop[k]-lpop[k];
           fprintf(ficlog,"\n");      }
           fprintf(ficres,"\n");     
         }     
       }      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
     }      for (k=agegomp;k<(agemortsup-2);k++)
     if(mle!=0){        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]);
       /* Computing hessian and covariance matrix */     
       ftolhess=ftol; /* Usually correct */     
       hesscov(matcov, p, npar, delti, ftolhess, func);      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     }      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");     
     printf("# Scales (for hessian or gradient estimation)\n");      printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");                       stepm, weightopt,\
     for(i=1,jk=1; i <=nlstate; i++){                       model,imx,p,matcov,agemortsup);
       for(j=1; j <=nlstate+ndeath; j++){     
         if (j!=i) {      free_vector(lsurv,1,AGESUP);
           fprintf(ficres,"%1d%1d",i,j);      free_vector(lpop,1,AGESUP);
           printf("%1d%1d",i,j);      free_vector(tpop,1,AGESUP);
           fprintf(ficlog,"%1d%1d",i,j);    } /* Endof if mle==-3 */
           for(k=1; k<=ncovmodel;k++){   
             printf(" %.5e",delti[jk]);    else{ /* For mle >=1 */
             fprintf(ficlog," %.5e",delti[jk]);   
             fprintf(ficres," %.5e",delti[jk]);      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
             jk++;      printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
           }      for (k=1; k<=npar;k++)
           printf("\n");        printf(" %d %8.5f",k,p[k]);
           fprintf(ficlog,"\n");      printf("\n");
           fprintf(ficres,"\n");      globpr=1; /* to print the contributions */
         }      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
       }      printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
     }      for (k=1; k<=npar;k++)
             printf(" %d %8.5f",k,p[k]);
     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");      printf("\n");
     if(mle>=1)      if(mle>=1){ /* Could be 1 or 2 */
       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");        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
     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");      }
     /* # 121 Var(a12)\n\ */     
     /* # 122 Cov(b12,a12) Var(b12)\n\ */      /*--------- results files --------------*/
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\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);
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */     
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */     
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */      fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
           for(i=1,jk=1; i <=nlstate; i++){
             for(k=1; k <=(nlstate+ndeath); k++){
     /* Just to have a covariance matrix which will be more understandable          if (k != i) {
        even is we still don't want to manage dictionary of variables            printf("%d%d ",i,k);
     */            fprintf(ficlog,"%d%d ",i,k);
     for(itimes=1;itimes<=2;itimes++){            fprintf(ficres,"%1d%1d ",i,k);
       jj=0;            for(j=1; j <=ncovmodel; j++){
       for(i=1; i <=nlstate; i++){              printf("%lf ",p[jk]);
         for(j=1; j <=nlstate+ndeath; j++){              fprintf(ficlog,"%lf ",p[jk]);
           if(j==i) continue;              fprintf(ficres,"%lf ",p[jk]);
           for(k=1; k<=ncovmodel;k++){              jk++;
             jj++;            }
             ca[0]= k+'a'-1;ca[1]='\0';            printf("\n");
             if(itimes==1){            fprintf(ficlog,"\n");
               if(mle>=1)            fprintf(ficres,"\n");
                 printf("#%1d%1d%d",i,j,k);          }
               fprintf(ficlog,"#%1d%1d%d",i,j,k);        }
               fprintf(ficres,"#%1d%1d%d",i,j,k);      }
             }else{      if(mle!=0){
               if(mle>=1)        /* Computing hessian and covariance matrix */
                 printf("%1d%1d%d",i,j,k);        ftolhess=ftol; /* Usually correct */
               fprintf(ficlog,"%1d%1d%d",i,j,k);        hesscov(matcov, p, npar, delti, ftolhess, func);
               fprintf(ficres,"%1d%1d%d",i,j,k);      }
             }      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
             ll=0;      printf("# Scales (for hessian or gradient estimation)\n");
             for(li=1;li <=nlstate; li++){      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
               for(lj=1;lj <=nlstate+ndeath; lj++){      for(i=1,jk=1; i <=nlstate; i++){
                 if(lj==li) continue;        for(j=1; j <=nlstate+ndeath; j++){
                 for(lk=1;lk<=ncovmodel;lk++){          if (j!=i) {
                   ll++;            fprintf(ficres,"%1d%1d",i,j);
                   if(ll<=jj){            printf("%1d%1d",i,j);
                     cb[0]= lk +'a'-1;cb[1]='\0';            fprintf(ficlog,"%1d%1d",i,j);
                     if(ll<jj){            for(k=1; k<=ncovmodel;k++){
                       if(itimes==1){              printf(" %.5e",delti[jk]);
                         if(mle>=1)              fprintf(ficlog," %.5e",delti[jk]);
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);              fprintf(ficres," %.5e",delti[jk]);
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);              jk++;
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);            }
                       }else{            printf("\n");
                         if(mle>=1)            fprintf(ficlog,"\n");
                           printf(" %.5e",matcov[jj][ll]);             fprintf(ficres,"\n");
                         fprintf(ficlog," %.5e",matcov[jj][ll]);           }
                         fprintf(ficres," %.5e",matcov[jj][ll]);         }
                       }      }
                     }else{     
                       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(" Var(%s%1d%1d)",ca,i,j);        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," Var(%s%1d%1d)",ca,i,j);      fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);      /* # 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\ */
                     }      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   }     
                 } /* end lk */     
               } /* end lj */      /* Just to have a covariance matrix which will be more understandable
             } /* end li */         even is we still don't want to manage dictionary of variables
             if(mle>=1)      */
               printf("\n");      for(itimes=1;itimes<=2;itimes++){
             fprintf(ficlog,"\n");        jj=0;
             fprintf(ficres,"\n");        for(i=1; i <=nlstate; i++){
             numlinepar++;          for(j=1; j <=nlstate+ndeath; j++){
           } /* end k*/            if(j==i) continue;
         } /*end j */            for(k=1; k<=ncovmodel;k++){
       } /* end i */              jj++;
     } /* end itimes */              ca[0]= k+'a'-1;ca[1]='\0';
                   if(itimes==1){
     fflush(ficlog);                if(mle>=1)
     fflush(ficres);                  printf("#%1d%1d%d",i,j,k);
                     fprintf(ficlog,"#%1d%1d%d",i,j,k);
     while((c=getc(ficpar))=='#' && c!= EOF){                fprintf(ficres,"#%1d%1d%d",i,j,k);
       ungetc(c,ficpar);              }else{
       fgets(line, MAXLINE, ficpar);                if(mle>=1)
       puts(line);                  printf("%1d%1d%d",i,j,k);
       fputs(line,ficparo);                fprintf(ficlog,"%1d%1d%d",i,j,k);
     }                fprintf(ficres,"%1d%1d%d",i,j,k);
     ungetc(c,ficpar);              }
                   ll=0;
     estepm=0;              for(li=1;li <=nlstate; li++){
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);                for(lj=1;lj <=nlstate+ndeath; lj++){
     if (estepm==0 || estepm < stepm) estepm=stepm;                  if(lj==li) continue;
     if (fage <= 2) {                  for(lk=1;lk<=ncovmodel;lk++){
       bage = ageminpar;                    ll++;
       fage = agemaxpar;                    if(ll<=jj){
     }                      cb[0]= lk +'a'-1;cb[1]='\0';
                           if(ll<jj){
     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(" 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);
     while((c=getc(ficpar))=='#' && c!= EOF){                          fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
       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);                        }
                           }else{
     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);                        if(itimes==1){
     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);                          if(mle>=1)
     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(" Var(%s%1d%1d)",ca,i,j);
     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);                          fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
     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);                          fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                             }else{
     while((c=getc(ficpar))=='#' && c!= EOF){                          if(mle>=1)
       ungetc(c,ficpar);                            printf(" %.5e",matcov[jj][ll]);
       fgets(line, MAXLINE, ficpar);                          fprintf(ficlog," %.5e",matcov[jj][ll]);
       puts(line);                          fprintf(ficres," %.5e",matcov[jj][ll]);
       fputs(line,ficparo);                        }
     }                      }
     ungetc(c,ficpar);                    }
                       } /* end lk */
                     } /* end lj */
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;              } /* end li */
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;              if(mle>=1)
                     printf("\n");
     fscanf(ficpar,"pop_based=%d\n",&popbased);              fprintf(ficlog,"\n");
     fprintf(ficparo,"pop_based=%d\n",popbased);                 fprintf(ficres,"\n");
     fprintf(ficres,"pop_based=%d\n",popbased);                 numlinepar++;
                 } /* end k*/
     while((c=getc(ficpar))=='#' && c!= EOF){          } /*end j */
       ungetc(c,ficpar);        } /* end i */
       fgets(line, MAXLINE, ficpar);      } /* end itimes */
       puts(line);     
       fputs(line,ficparo);      fflush(ficlog);
     }      fflush(ficres);
     ungetc(c,ficpar);     
           while((c=getc(ficpar))=='#' && c!= EOF){
     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);        ungetc(c,ficpar);
     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);        fgets(line, MAXLINE, ficpar);
     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);        puts(line);
     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);        fputs(line,ficparo);
     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      }
     /* day and month of proj2 are not used but only year anproj2.*/      ungetc(c,ficpar);
          
           estepm=0;
           fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/      if (estepm==0 || estepm < stepm) estepm=stepm;
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/      if (fage <= 2) {
             bage = ageminpar;
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */        fage = agemaxpar;
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);      }
          
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\      fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
            
    /*------------ free_vector  -------------*/      while((c=getc(ficpar))=='#' && c!= EOF){
    /*  chdir(path); */        ungetc(c,ficpar);
          fgets(line, MAXLINE, ficpar);
     free_ivector(wav,1,imx);        puts(line);
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);        fputs(line,ficparo);
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);      }
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);         ungetc(c,ficpar);
     free_lvector(num,1,n);     
     free_vector(agedc,1,n);      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);
     /*free_matrix(covar,0,NCOVMAX,1,n);*/      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);
     /*free_matrix(covar,1,NCOVMAX,1,n);*/      fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
     fclose(ficparo);      printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
     fclose(ficres);      fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
      
       while((c=getc(ficpar))=='#' && c!= EOF){
     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/        ungetc(c,ficpar);
           fgets(line, MAXLINE, ficpar);
     strcpy(filerespl,"pl");        puts(line);
     strcat(filerespl,fileres);        fputs(line,ficparo);
     if((ficrespl=fopen(filerespl,"w"))==NULL) {      }
       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;      ungetc(c,ficpar);
       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;     
     }     
     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);      dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);      dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
     pstamp(ficrespl);     
     fprintf(ficrespl,"# Period (stable) prevalence \n");      fscanf(ficpar,"pop_based=%d\n",&popbased);
     fprintf(ficrespl,"#Age ");      fprintf(ficparo,"pop_based=%d\n",popbased);  
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);      fprintf(ficres,"pop_based=%d\n",popbased);  
     fprintf(ficrespl,"\n");     
         while((c=getc(ficpar))=='#' && c!= EOF){
     prlim=matrix(1,nlstate,1,nlstate);        ungetc(c,ficpar);
         fgets(line, MAXLINE, ficpar);
     agebase=ageminpar;        puts(line);
     agelim=agemaxpar;        fputs(line,ficparo);
     ftolpl=1.e-10;      }
     i1=cptcoveff;      ungetc(c,ficpar);
     if (cptcovn < 1){i1=1;}     
       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);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      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(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      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);
         k=k+1;      fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/      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(ficrespl,"\n#******");      /* day and month of proj2 are not used but only year anproj2.*/
         printf("\n#******");     
         fprintf(ficlog,"\n#******");     
         for(j=1;j<=cptcoveff;j++) {     
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);     
         }      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
         fprintf(ficrespl,"******\n");      printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
         printf("******\n");     
         fprintf(ficlog,"******\n");      printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                            model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
         for (age=agebase; age<=agelim; age++){                   jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);       
           fprintf(ficrespl,"%.0f ",age );     /*------------ free_vector  -------------*/
           for(j=1;j<=cptcoveff;j++)     /*  chdir(path); */
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);   
           for(i=1; i<=nlstate;i++)      free_ivector(wav,1,imx);
             fprintf(ficrespl," %.5f", prlim[i][i]);      free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
           fprintf(ficrespl,"\n");      free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
         }      free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
       }      free_lvector(num,1,n);
     }      free_vector(agedc,1,n);
     fclose(ficrespl);      /*free_matrix(covar,0,NCOVMAX,1,n);*/
       /*free_matrix(covar,1,NCOVMAX,1,n);*/
     /*------------- h Pij x at various ages ------------*/      fclose(ficparo);
         fclose(ficres);
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);  
     if((ficrespij=fopen(filerespij,"w"))==NULL) {  
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;   
     }      strcpy(filerespl,"pl");
     printf("Computing pij: result on file '%s' \n", filerespij);      strcat(filerespl,fileres);
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);      if((ficrespl=fopen(filerespl,"w"))==NULL) {
           printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     stepsize=(int) (stepm+YEARM-1)/YEARM;        fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     /*if (stepm<=24) stepsize=2;*/      }
       printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
     agelim=AGESUP;      fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
     hstepm=stepsize*YEARM; /* Every year of age */      pstamp(ficrespl);
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */       fprintf(ficrespl,"# Period (stable) prevalence \n");
       fprintf(ficrespl,"#Age ");
     /* hstepm=1;   aff par mois*/      for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
     pstamp(ficrespij);      fprintf(ficrespl,"\n");
     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");   
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      prlim=matrix(1,nlstate,1,nlstate);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){  
         k=k+1;      agebase=ageminpar;
         fprintf(ficrespij,"\n#****** ");      agelim=agemaxpar;
         for(j=1;j<=cptcoveff;j++)       ftolpl=1.e-10;
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      i1=cptcoveff;
         fprintf(ficrespij,"******\n");      if (cptcovn < 1){i1=1;}
           
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */         for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */          k=k+1;
           /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
           /*      nhstepm=nhstepm*YEARM; aff par mois*/          fprintf(ficrespl,"\n#******");
           printf("\n#******");
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          fprintf(ficlog,"\n#******");
           oldm=oldms;savm=savms;          for(j=1;j<=cptcoveff;j++) {
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);              fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");            printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           for(i=1; i<=nlstate;i++)            fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             for(j=1; j<=nlstate+ndeath;j++)          }
               fprintf(ficrespij," %1d-%1d",i,j);          fprintf(ficrespl,"******\n");
           fprintf(ficrespij,"\n");          printf("******\n");
           for (h=0; h<=nhstepm; h++){          fprintf(ficlog,"******\n");
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );         
             for(i=1; i<=nlstate;i++)          for (age=agebase; age<=agelim; age++){
               for(j=1; j<=nlstate+ndeath;j++)            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);            fprintf(ficrespl,"%.0f ",age );
             fprintf(ficrespij,"\n");            for(j=1;j<=cptcoveff;j++)
           }              fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            for(i=1; i<=nlstate;i++)
           fprintf(ficrespij,"\n");              fprintf(ficrespl," %.5f", prlim[i][i]);
         }            fprintf(ficrespl,"\n");
       }          }
     }        }
       }
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);      fclose(ficrespl);
   
     fclose(ficrespij);      /*------------- h Pij x at various ages ------------*/
    
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);      strcpy(filerespij,"pij");  strcat(filerespij,fileres);
     for(i=1;i<=AGESUP;i++)      if((ficrespij=fopen(filerespij,"w"))==NULL) {
       for(j=1;j<=NCOVMAX;j++)        printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
         for(k=1;k<=NCOVMAX;k++)        fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
           probs[i][j][k]=0.;      }
       printf("Computing pij: result on file '%s' \n", filerespij);
     /*---------- Forecasting ------------------*/      fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/   
     if(prevfcast==1){      stepsize=(int) (stepm+YEARM-1)/YEARM;
       /*    if(stepm ==1){*/      /*if (stepm<=24) stepsize=2;*/
       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);*/      agelim=AGESUP;
       /*      }  */      hstepm=stepsize*YEARM; /* Every year of age */
       /*      else{ */      hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
       /*        erreur=108; */  
       /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */      /* hstepm=1;   aff par mois*/
       /*        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); */      pstamp(ficrespij);
       /*      } */      fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
     }      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
           for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
     /*---------- Health expectancies and variances ------------*/          fprintf(ficrespij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++)
     strcpy(filerest,"t");            fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     strcat(filerest,fileres);          fprintf(ficrespij,"******\n");
     if((ficrest=fopen(filerest,"w"))==NULL) {         
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;          for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
     }            nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);   
     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);             /*      nhstepm=nhstepm*YEARM; aff par mois*/
   
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     strcpy(filerese,"e");            oldm=oldms;savm=savms;
     strcat(filerese,fileres);            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
     if((ficreseij=fopen(filerese,"w"))==NULL) {            fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);            for(i=1; i<=nlstate;i++)
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);              for(j=1; j<=nlstate+ndeath;j++)
     }                fprintf(ficrespij," %1d-%1d",i,j);
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);            fprintf(ficrespij,"\n");
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);            for (h=0; h<=nhstepm; h++){
               fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
     strcpy(fileresstde,"stde");              for(i=1; i<=nlstate;i++)
     strcat(fileresstde,fileres);                for(j=1; j<=nlstate+ndeath;j++)
     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {                  fprintf(ficrespij," %.5f", p3mat[i][j][h]);
       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);              fprintf(ficrespij,"\n");
       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);            }
     }            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);            fprintf(ficrespij,"\n");
     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);          }
         }
     strcpy(filerescve,"cve");      }
     strcat(filerescve,fileres);  
     if((ficrescveij=fopen(filerescve,"w"))==NULL) {      varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);  
       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);      fclose(ficrespij);
     }  
     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      for(i=1;i<=AGESUP;i++)
         for(j=1;j<=NCOVMAX;j++)
     strcpy(fileresv,"v");          for(k=1;k<=NCOVMAX;k++)
     strcat(fileresv,fileres);            probs[i][j][k]=0.;
     if((ficresvij=fopen(fileresv,"w"))==NULL) {  
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);      /*---------- Forecasting ------------------*/
       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);      /*if((stepm == 1) && (strcmp(model,".")==0)){*/
     }      if(prevfcast==1){
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);        /*    if(stepm ==1){*/
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);        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);*/
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */        /*      }  */
     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);        /*      else{ */
     /*  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",\        /*        erreur=108; */
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);        /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
     */        /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
         /*      } */
     if (mobilav!=0) {      }
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);   
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){  
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);      /*---------- Health expectancies and variances ------------*/
         printf(" Error in movingaverage mobilav=%d\n",mobilav);  
       }      strcpy(filerest,"t");
     }      strcat(filerest,fileres);
       if((ficrest=fopen(filerest,"w"))==NULL) {
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){        printf("Problem with total LE resultfile: %s\n", filerest);goto end;
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){        fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
         k=k+1;       }
         fprintf(ficrest,"\n#****** ");      printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
         for(j=1;j<=cptcoveff;j++)       fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
         fprintf(ficrest,"******\n");  
       strcpy(filerese,"e");
         fprintf(ficreseij,"\n#****** ");      strcat(filerese,fileres);
         fprintf(ficresstdeij,"\n#****** ");      if((ficreseij=fopen(filerese,"w"))==NULL) {
         fprintf(ficrescveij,"\n#****** ");        printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
         for(j=1;j<=cptcoveff;j++) {        fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
           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]]);      printf("Computing Health Expectancies: result on file '%s' \n", filerese);
           fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
         }  
         fprintf(ficreseij,"******\n");      strcpy(fileresstde,"stde");
         fprintf(ficresstdeij,"******\n");      strcat(fileresstde,fileres);
         fprintf(ficrescveij,"******\n");      if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
         printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
         fprintf(ficresvij,"\n#****** ");        fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
         for(j=1;j<=cptcoveff;j++)       }
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
         fprintf(ficresvij,"******\n");      fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
   
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      strcpy(filerescve,"cve");
         oldm=oldms;savm=savms;      strcat(filerescve,fileres);
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);        if((ficrescveij=fopen(filerescve,"w"))==NULL) {
         cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);          printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
          fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      }
         oldm=oldms;savm=savms;      printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
         varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);      fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
         if(popbased==1){  
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);      strcpy(fileresv,"v");
         }      strcat(fileresv,fileres);
       if((ficresvij=fopen(fileresv,"w"))==NULL) {
         pstamp(ficrest);        printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
         fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");        fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);      }
         fprintf(ficrest,"\n");      printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
       fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
         epj=vector(1,nlstate+1);  
         for(age=bage; age <=fage ;age++){      /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      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",\
             if(mobilav ==0){          ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
               for(i=1; i<=nlstate;i++)      */
                 prlim[i][i]=probs[(int)age][i][k];  
             }else{ /* mobilav */       if (mobilav!=0) {
               for(i=1; i<=nlstate;i++)        mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                 prlim[i][i]=mobaverage[(int)age][i][k];        if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
             }          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
           }          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                 }
           fprintf(ficrest," %4.0f",age);      }
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){  
             for(i=1, epj[j]=0.;i <=nlstate;i++) {      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
               epj[j] += prlim[i][i]*eij[i][j][(int)age];        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/          k=k+1;
             }          fprintf(ficrest,"\n#****** ");
             epj[nlstate+1] +=epj[j];          for(j=1;j<=cptcoveff;j++)
           }            fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrest,"******\n");
           for(i=1, vepp=0.;i <=nlstate;i++)  
             for(j=1;j <=nlstate;j++)          fprintf(ficreseij,"\n#****** ");
               vepp += vareij[i][j][(int)age];          fprintf(ficresstdeij,"\n#****** ");
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));          fprintf(ficrescveij,"\n#****** ");
           for(j=1;j <=nlstate;j++){          for(j=1;j<=cptcoveff;j++) {
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));            fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           }            fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrest,"\n");            fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         }          }
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);          fprintf(ficreseij,"******\n");
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);          fprintf(ficresstdeij,"******\n");
         free_vector(epj,1,nlstate+1);          fprintf(ficrescveij,"******\n");
       }  
     }          fprintf(ficresvij,"\n#****** ");
     free_vector(weight,1,n);          for(j=1;j<=cptcoveff;j++)
     free_imatrix(Tvard,1,15,1,2);            fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_imatrix(s,1,maxwav+1,1,n);          fprintf(ficresvij,"******\n");
     free_matrix(anint,1,maxwav,1,n);   
     free_matrix(mint,1,maxwav,1,n);          eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
     free_ivector(cod,1,n);          oldm=oldms;savm=savms;
     free_ivector(tab,1,NCOVMAX);          evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
     fclose(ficreseij);          cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
     fclose(ficresstdeij);   
     fclose(ficrescveij);          vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
     fclose(ficresvij);          oldm=oldms;savm=savms;
     fclose(ficrest);          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);
     fclose(ficpar);          if(popbased==1){
               varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);
     /*------- Variance of period (stable) prevalence------*/             }
   
     strcpy(fileresvpl,"vpl");          pstamp(ficrest);
     strcat(fileresvpl,fileres);          fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);          fprintf(ficrest,"\n");
       exit(0);  
     }          epj=vector(1,nlstate+1);
     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);          for(age=bage; age <=fage ;age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){            if (popbased==1) {
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){              if(mobilav ==0){
         k=k+1;                for(i=1; i<=nlstate;i++)
         fprintf(ficresvpl,"\n#****** ");                  prlim[i][i]=probs[(int)age][i][k];
         for(j=1;j<=cptcoveff;j++)               }else{ /* mobilav */
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);                for(i=1; i<=nlstate;i++)
         fprintf(ficresvpl,"******\n");                  prlim[i][i]=mobaverage[(int)age][i][k];
                     }
         varpl=matrix(1,nlstate,(int) bage, (int) fage);            }
         oldm=oldms;savm=savms;         
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);            fprintf(ficrest," %4.0f",age);
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
       }              for(i=1, epj[j]=0.;i <=nlstate;i++) {
     }                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                 /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
     fclose(ficresvpl);              }
               epj[nlstate+1] +=epj[j];
     /*---------- End : free ----------------*/            }
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);            for(i=1, vepp=0.;i <=nlstate;i++)
               for(j=1;j <=nlstate;j++)
   }  /* mle==-3 arrives here for freeing */                vepp += vareij[i][j][(int)age];
   free_matrix(prlim,1,nlstate,1,nlstate);            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);            for(j=1;j <=nlstate;j++){
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);            }
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);            fprintf(ficrest,"\n");
     free_matrix(covar,0,NCOVMAX,1,n);          }
     free_matrix(matcov,1,npar,1,npar);          free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     /*free_vector(delti,1,npar);*/          free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);           free_vector(epj,1,nlstate+1);
     free_matrix(agev,1,maxwav,1,imx);        }
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);      }
       free_vector(weight,1,n);
     free_ivector(ncodemax,1,8);      free_imatrix(Tvard,1,15,1,2);
     free_ivector(Tvar,1,15);      free_imatrix(s,1,maxwav+1,1,n);
     free_ivector(Tprod,1,15);      free_matrix(anint,1,maxwav,1,n);
     free_ivector(Tvaraff,1,15);      free_matrix(mint,1,maxwav,1,n);
     free_ivector(Tage,1,15);      free_ivector(cod,1,n);
     free_ivector(Tcode,1,100);      free_ivector(tab,1,NCOVMAX);
       fclose(ficreseij);
     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);      fclose(ficresstdeij);
     free_imatrix(codtab,1,100,1,10);      fclose(ficrescveij);
   fflush(fichtm);      fclose(ficresvij);
   fflush(ficgp);      fclose(ficrest);
         fclose(ficpar);
    
   if((nberr >0) || (nbwarn>0)){      /*------- Variance of period (stable) prevalence------*/  
     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);  
     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);      strcpy(fileresvpl,"vpl");
   }else{      strcat(fileresvpl,fileres);
     printf("End of Imach\n");      if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
     fprintf(ficlog,"End of Imach\n");        printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
   }        exit(0);
   printf("See log file on %s\n",filelog);      }
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */      printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
   (void) gettimeofday(&end_time,&tzp);  
   tm = *localtime(&end_time.tv_sec);      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
   tmg = *gmtime(&end_time.tv_sec);        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
   strcpy(strtend,asctime(&tm));          k=k+1;
   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);           fprintf(ficresvpl,"\n#****** ");
   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);           for(j=1;j<=cptcoveff;j++)
   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));            fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficresvpl,"******\n");
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);       
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));          varpl=matrix(1,nlstate,(int) bage, (int) fage);
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);          oldm=oldms;savm=savms;
   /*  printf("Total time was %d uSec.\n", total_usecs);*/          varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 /*   if(fileappend(fichtm,optionfilehtm)){ */          free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);        }
   fclose(fichtm);      }
   fclose(fichtmcov);  
   fclose(ficgp);      fclose(ficresvpl);
   fclose(ficlog);  
   /*------ End -----------*/      /*---------- End : free ----------------*/
       if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
    printf("Before Current directory %s!\n",pathcd);  
    if(chdir(pathcd) != 0)    }  /* mle==-3 arrives here for freeing */
     printf("Can't move to directory %s!\n",path);    free_matrix(prlim,1,nlstate,1,nlstate);
   if(getcwd(pathcd,MAXLINE) > 0)      free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
     printf("Current directory %s!\n",pathcd);      free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
   /*strcat(plotcmd,CHARSEPARATOR);*/      free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
   sprintf(plotcmd,"gnuplot");      free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 #ifndef UNIX      free_matrix(covar,0,NCOVMAX,1,n);
   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);      free_matrix(matcov,1,npar,1,npar);
 #endif      /*free_vector(delti,1,npar);*/
   if(!stat(plotcmd,&info)){      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);      free_matrix(agev,1,maxwav,1,imx);
     if(!stat(getenv("GNUPLOTBIN"),&info)){      free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);  
     }else      free_ivector(ncodemax,1,8);
       strcpy(pplotcmd,plotcmd);      free_ivector(Tvar,1,15);
 #ifdef UNIX      free_ivector(Tprod,1,15);
     strcpy(plotcmd,GNUPLOTPROGRAM);      free_ivector(Tvaraff,1,15);
     if(!stat(plotcmd,&info)){      free_ivector(Tage,1,15);
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);      free_ivector(Tcode,1,100);
     }else  
       strcpy(pplotcmd,plotcmd);      free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 #endif      free_imatrix(codtab,1,100,1,10);
   }else    fflush(fichtm);
     strcpy(pplotcmd,plotcmd);    fflush(ficgp);
      
   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);  
   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);    if((nberr >0) || (nbwarn>0)){
       printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
   if((outcmd=system(plotcmd)) != 0){      fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
     printf("\n Problem with gnuplot\n");    }else{
   }      printf("End of Imach\n");
   printf(" Wait...");      fprintf(ficlog,"End of Imach\n");
   while (z[0] != 'q') {    }
     /* chdir(path); */    printf("See log file on %s\n",filelog);
     printf("\nType e to edit output files, g to graph again and q for exiting: ");    /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
     scanf("%s",z);    (void) gettimeofday(&end_time,&tzp);
 /*     if (z[0] == 'c') system("./imach"); */    tm = *localtime(&end_time.tv_sec);
     if (z[0] == 'e') {    tmg = *gmtime(&end_time.tv_sec);
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);    strcpy(strtend,asctime(&tm));
       system(optionfilehtm);    printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);
     }    fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);
     else if (z[0] == 'g') system(plotcmd);    printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     else if (z[0] == 'q') exit(0);  
   }    printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
   end:    fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
   while (z[0] != 'q') {    fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     printf("\nType  q for exiting: ");    /*  printf("Total time was %d uSec.\n", total_usecs);*/
     scanf("%s",z);  /*   if(fileappend(fichtm,optionfilehtm)){ */
   }    fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 }    fclose(fichtm);
     fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     fclose(fichtmcov);
     fclose(ficgp);
     fclose(ficlog);
     /*------ End -----------*/
   
   
      printf("Before Current directory %s!\n",pathcd);
      if(chdir(pathcd) != 0)
       printf("Can't move to directory %s!\n",path);
     if(getcwd(pathcd,MAXLINE) > 0)
       printf("Current directory %s!\n",pathcd);
     /*strcat(plotcmd,CHARSEPARATOR);*/
     sprintf(plotcmd,"gnuplot");
   #ifndef UNIX
     sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
   #endif
     if(!stat(plotcmd,&info)){
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       if(!stat(getenv("GNUPLOTBIN"),&info)){
         printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #ifdef UNIX
       strcpy(plotcmd,GNUPLOTPROGRAM);
       if(!stat(plotcmd,&info)){
         printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #endif
     }else
       strcpy(pplotcmd,plotcmd);
    
     sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
     printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
   
     if((outcmd=system(plotcmd)) != 0){
       printf("\n Problem with gnuplot\n");
     }
     printf(" Wait...");
     while (z[0] != 'q') {
       /* chdir(path); */
       printf("\nType e to edit output files, g to graph again and q for exiting: ");
       scanf("%s",z);
   /*     if (z[0] == 'c') system("./imach"); */
       if (z[0] == 'e') {
         printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
         system(optionfilehtm);
       }
       else if (z[0] == 'g') system(plotcmd);
       else if (z[0] == 'q') exit(0);
     }
     end:
     while (z[0] != 'q') {
       printf("\nType  q for exiting: ");
       scanf("%s",z);
     }
   }
   
   
   

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


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