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

version 1.122, 2006/03/20 09:45:41 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.122  2006/03/20 09:45:41  brouard    Revision 1.125  2006/04/04 15:20:31  lievre
   (Module): Weights can have a decimal point as for    Errors in calculation of health expectancies. Age was not initialized.
   English (a comma might work with a correct LC_NUMERIC environment,    Forecasting file added.
   otherwise the weight is truncated).  
   Modification of warning when the covariates values are not 0 or    Revision 1.124  2006/03/22 17:13:53  lievre
   1.    Parameters are printed with %lf instead of %f (more numbers after the comma).
   Version 0.98g    The log-likelihood is printed in the log file
   
   Revision 1.121  2006/03/16 17:45:01  lievre    Revision 1.123  2006/03/20 10:52:43  brouard
   * imach.c (Module): Comments concerning covariates added    * imach.c (Module): <title> changed, corresponds to .htm file
     name. <head> headers where missing.
   * imach.c (Module): refinements in the computation of lli if  
   status=-2 in order to have more reliable computation if stepm is    * imach.c (Module): Weights can have a decimal point as for
   not 1 month. Version 0.98f    English (a comma might work with a correct LC_NUMERIC environment,
     otherwise the weight is truncated).
   Revision 1.120  2006/03/16 15:10:38  lievre    Modification of warning when the covariates values are not 0 or
   (Module): refinements in the computation of lli if    1.
   status=-2 in order to have more reliable computation if stepm is    Version 0.98g
   not 1 month. Version 0.98f  
     Revision 1.122  2006/03/20 09:45:41  brouard
   Revision 1.119  2006/03/15 17:42:26  brouard    (Module): Weights can have a decimal point as for
   (Module): Bug if status = -2, the loglikelihood was    English (a comma might work with a correct LC_NUMERIC environment,
   computed as likelihood omitting the logarithm. Version O.98e    otherwise the weight is truncated).
     Modification of warning when the covariates values are not 0 or
   Revision 1.118  2006/03/14 18:20:07  brouard    1.
   (Module): varevsij Comments added explaining the second    Version 0.98g
   table of variances if popbased=1 .  
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.    Revision 1.121  2006/03/16 17:45:01  lievre
   (Module): Function pstamp added    * imach.c (Module): Comments concerning covariates added
   (Module): Version 0.98d  
     * imach.c (Module): refinements in the computation of lli if
   Revision 1.117  2006/03/14 17:16:22  brouard    status=-2 in order to have more reliable computation if stepm is
   (Module): varevsij Comments added explaining the second    not 1 month. Version 0.98f
   table of variances if popbased=1 .  
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.    Revision 1.120  2006/03/16 15:10:38  lievre
   (Module): Function pstamp added    (Module): refinements in the computation of lli if
   (Module): Version 0.98d    status=-2 in order to have more reliable computation if stepm is
     not 1 month. Version 0.98f
   Revision 1.116  2006/03/06 10:29:27  brouard  
   (Module): Variance-covariance wrong links and    Revision 1.119  2006/03/15 17:42:26  brouard
   varian-covariance of ej. is needed (Saito).    (Module): Bug if status = -2, the loglikelihood was
     computed as likelihood omitting the logarithm. Version O.98e
   Revision 1.115  2006/02/27 12:17:45  brouard  
   (Module): One freematrix added in mlikeli! 0.98c    Revision 1.118  2006/03/14 18:20:07  brouard
     (Module): varevsij Comments added explaining the second
   Revision 1.114  2006/02/26 12:57:58  brouard    table of variances if popbased=1 .
   (Module): Some improvements in processing parameter    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   filename with strsep.    (Module): Function pstamp added
     (Module): Version 0.98d
   Revision 1.113  2006/02/24 14:20:24  brouard  
   (Module): Memory leaks checks with valgrind and:    Revision 1.117  2006/03/14 17:16:22  brouard
   datafile was not closed, some imatrix were not freed and on matrix    (Module): varevsij Comments added explaining the second
   allocation too.    table of variances if popbased=1 .
     (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   Revision 1.112  2006/01/30 09:55:26  brouard    (Module): Function pstamp added
   (Module): Back to gnuplot.exe instead of wgnuplot.exe    (Module): Version 0.98d
   
   Revision 1.111  2006/01/25 20:38:18  brouard    Revision 1.116  2006/03/06 10:29:27  brouard
   (Module): Lots of cleaning and bugs added (Gompertz)    (Module): Variance-covariance wrong links and
   (Module): Comments can be added in data file. Missing date values    varian-covariance of ej. is needed (Saito).
   can be a simple dot '.'.  
     Revision 1.115  2006/02/27 12:17:45  brouard
   Revision 1.110  2006/01/25 00:51:50  brouard    (Module): One freematrix added in mlikeli! 0.98c
   (Module): Lots of cleaning and bugs added (Gompertz)  
     Revision 1.114  2006/02/26 12:57:58  brouard
   Revision 1.109  2006/01/24 19:37:15  brouard    (Module): Some improvements in processing parameter
   (Module): Comments (lines starting with a #) are allowed in data.    filename with strsep.
   
   Revision 1.108  2006/01/19 18:05:42  lievre    Revision 1.113  2006/02/24 14:20:24  brouard
   Gnuplot problem appeared...    (Module): Memory leaks checks with valgrind and:
   To be fixed    datafile was not closed, some imatrix were not freed and on matrix
     allocation too.
   Revision 1.107  2006/01/19 16:20:37  brouard  
   Test existence of gnuplot in imach path    Revision 1.112  2006/01/30 09:55:26  brouard
     (Module): Back to gnuplot.exe instead of wgnuplot.exe
   Revision 1.106  2006/01/19 13:24:36  brouard  
   Some cleaning and links added in html output    Revision 1.111  2006/01/25 20:38:18  brouard
     (Module): Lots of cleaning and bugs added (Gompertz)
   Revision 1.105  2006/01/05 20:23:19  lievre    (Module): Comments can be added in data file. Missing date values
   *** empty log message ***    can be a simple dot '.'.
   
   Revision 1.104  2005/09/30 16:11:43  lievre    Revision 1.110  2006/01/25 00:51:50  brouard
   (Module): sump fixed, loop imx fixed, and simplifications.    (Module): Lots of cleaning and bugs added (Gompertz)
   (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.109  2006/01/24 19:37:15  brouard
   (instead of missing=-1 in earlier versions) and his/her    (Module): Comments (lines starting with a #) are allowed in data.
   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.108  2006/01/19 18:05:42  lievre
   the healthy state at last known wave). Version is 0.98    Gnuplot problem appeared...
     To be fixed
   Revision 1.103  2005/09/30 15:54:49  lievre  
   (Module): sump fixed, loop imx fixed, and simplifications.    Revision 1.107  2006/01/19 16:20:37  brouard
     Test existence of gnuplot in imach path
   Revision 1.102  2004/09/15 17:31:30  brouard  
   Add the possibility to read data file including tab characters.    Revision 1.106  2006/01/19 13:24:36  brouard
     Some cleaning and links added in html output
   Revision 1.101  2004/09/15 10:38:38  brouard  
   Fix on curr_time    Revision 1.105  2006/01/05 20:23:19  lievre
     *** empty log message ***
   Revision 1.100  2004/07/12 18:29:06  brouard  
   Add version for Mac OS X. Just define UNIX in Makefile    Revision 1.104  2005/09/30 16:11:43  lievre
     (Module): sump fixed, loop imx fixed, and simplifications.
   Revision 1.99  2004/06/05 08:57:40  brouard    (Module): If the status is missing at the last wave but we know
   *** empty log message ***    that the person is alive, then we can code his/her status as -2
     (instead of missing=-1 in earlier versions) and his/her
   Revision 1.98  2004/05/16 15:05:56  brouard    contributions to the likelihood is 1 - Prob of dying from last
   New version 0.97 . First attempt to estimate force of mortality    health status (= 1-p13= p11+p12 in the easiest case of somebody in
   directly from the data i.e. without the need of knowing the health    the healthy state at last known wave). Version is 0.98
   state at each age, but using a Gompertz model: log u =a + b*age .  
   This is the basic analysis of mortality and should be done before any    Revision 1.103  2005/09/30 15:54:49  lievre
   other analysis, in order to test if the mortality estimated from the    (Module): sump fixed, loop imx fixed, and simplifications.
   cross-longitudinal survey is different from the mortality estimated  
   from other sources like vital statistic data.    Revision 1.102  2004/09/15 17:31:30  brouard
     Add the possibility to read data file including tab characters.
   The same imach parameter file can be used but the option for mle should be -3.  
     Revision 1.101  2004/09/15 10:38:38  brouard
   Agnès, who wrote this part of the code, tried to keep most of the    Fix on curr_time
   former routines in order to include the new code within the former code.  
     Revision 1.100  2004/07/12 18:29:06  brouard
   The output is very simple: only an estimate of the intercept and of    Add version for Mac OS X. Just define UNIX in Makefile
   the slope with 95% confident intervals.  
     Revision 1.99  2004/06/05 08:57:40  brouard
   Current limitations:    *** empty log message ***
   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.98  2004/05/16 15:05:56  brouard
   B) There is no computation of Life Expectancy nor Life Table.    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.97  2004/02/20 13:25:42  lievre    state at each age, but using a Gompertz model: log u =a + b*age .
   Version 0.96d. Population forecasting command line is (temporarily)    This is the basic analysis of mortality and should be done before any
   suppressed.    other analysis, in order to test if the mortality estimated from the
     cross-longitudinal survey is different from the mortality estimated
   Revision 1.96  2003/07/15 15:38:55  brouard    from other sources like vital statistic data.
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is  
   rewritten within the same printf. Workaround: many printfs.    The same imach parameter file can be used but the option for mle should be -3.
   
   Revision 1.95  2003/07/08 07:54:34  brouard    Agnès, who wrote this part of the code, tried to keep most of the
   * imach.c (Repository):    former routines in order to include the new code within the former code.
   (Repository): Using imachwizard code to output a more meaningful covariance  
   matrix (cov(a12,c31) instead of numbers.    The output is very simple: only an estimate of the intercept and of
     the slope with 95% confident intervals.
   Revision 1.94  2003/06/27 13:00:02  brouard  
   Just cleaning    Current limitations:
     A) Even if you enter covariates, i.e. with the
   Revision 1.93  2003/06/25 16:33:55  brouard    model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   (Module): On windows (cygwin) function asctime_r doesn't    B) There is no computation of Life Expectancy nor Life Table.
   exist so I changed back to asctime which exists.  
   (Module): Version 0.96b    Revision 1.97  2004/02/20 13:25:42  lievre
     Version 0.96d. Population forecasting command line is (temporarily)
   Revision 1.92  2003/06/25 16:30:45  brouard    suppressed.
   (Module): On windows (cygwin) function asctime_r doesn't  
   exist so I changed back to asctime which exists.    Revision 1.96  2003/07/15 15:38:55  brouard
     * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   Revision 1.91  2003/06/25 15:30:29  brouard    rewritten within the same printf. Workaround: many printfs.
   * imach.c (Repository): Duplicated warning errors corrected.  
   (Repository): Elapsed time after each iteration is now output. It    Revision 1.95  2003/07/08 07:54:34  brouard
   helps to forecast when convergence will be reached. Elapsed time    * imach.c (Repository):
   is stamped in powell.  We created a new html file for the graphs    (Repository): Using imachwizard code to output a more meaningful covariance
   concerning matrix of covariance. It has extension -cov.htm.    matrix (cov(a12,c31) instead of numbers.
   
   Revision 1.90  2003/06/24 12:34:15  brouard    Revision 1.94  2003/06/27 13:00:02  brouard
   (Module): Some bugs corrected for windows. Also, when    Just cleaning
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.93  2003/06/25 16:33:55  brouard
     (Module): On windows (cygwin) function asctime_r doesn't
   Revision 1.89  2003/06/24 12:30:52  brouard    exist so I changed back to asctime which exists.
   (Module): Some bugs corrected for windows. Also, when    (Module): Version 0.96b
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.92  2003/06/25 16:30:45  brouard
     (Module): On windows (cygwin) function asctime_r doesn't
   Revision 1.88  2003/06/23 17:54:56  brouard    exist so I changed back to asctime which exists.
   * 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.91  2003/06/25 15:30:29  brouard
   Revision 1.87  2003/06/18 12:26:01  brouard    * imach.c (Repository): Duplicated warning errors corrected.
   Version 0.96    (Repository): Elapsed time after each iteration is now output. It
     helps to forecast when convergence will be reached. Elapsed time
   Revision 1.86  2003/06/17 20:04:08  brouard    is stamped in powell.  We created a new html file for the graphs
   (Module): Change position of html and gnuplot routines and added    concerning matrix of covariance. It has extension -cov.htm.
   routine fileappend.  
     Revision 1.90  2003/06/24 12:34:15  brouard
   Revision 1.85  2003/06/17 13:12:43  brouard    (Module): Some bugs corrected for windows. Also, when
   * imach.c (Repository): Check when date of death was earlier that    mle=-1 a template is output in file "or"mypar.txt with the design
   current date of interview. It may happen when the death was just    of the covariance matrix to be input.
   prior to the death. In this case, dh was negative and likelihood  
   was wrong (infinity). We still send an "Error" but patch by    Revision 1.89  2003/06/24 12:30:52  brouard
   assuming that the date of death was just one stepm after the    (Module): Some bugs corrected for windows. Also, when
   interview.    mle=-1 a template is output in file "or"mypar.txt with the design
   (Repository): Because some people have very long ID (first column)    of the covariance matrix to be input.
   we changed int to long in num[] and we added a new lvector for  
   memory allocation. But we also truncated to 8 characters (left    Revision 1.88  2003/06/23 17:54:56  brouard
   truncation)    * 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.
   (Repository): No more line truncation errors.  
     Revision 1.87  2003/06/18 12:26:01  brouard
   Revision 1.84  2003/06/13 21:44:43  brouard    Version 0.96
   * imach.c (Repository): Replace "freqsummary" at a correct  
   place. It differs from routine "prevalence" which may be called    Revision 1.86  2003/06/17 20:04:08  brouard
   many times. Probs is memory consuming and must be used with    (Module): Change position of html and gnuplot routines and added
   parcimony.    routine fileappend.
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)  
     Revision 1.85  2003/06/17 13:12:43  brouard
   Revision 1.83  2003/06/10 13:39:11  lievre    * imach.c (Repository): Check when date of death was earlier that
   *** empty log message ***    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.82  2003/06/05 15:57:20  brouard    was wrong (infinity). We still send an "Error" but patch by
   Add log in  imach.c and  fullversion number is now printed.    assuming that the date of death was just one stepm after the
     interview.
 */    (Repository): Because some people have very long ID (first column)
 /*    we changed int to long in num[] and we added a new lvector for
    Interpolated Markov Chain    memory allocation. But we also truncated to 8 characters (left
     truncation)
   Short summary of the programme:    (Repository): No more line truncation errors.
     
   This program computes Healthy Life Expectancies from    Revision 1.84  2003/06/13 21:44:43  brouard
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    * imach.c (Repository): Replace "freqsummary" at a correct
   first survey ("cross") where individuals from different ages are    place. It differs from routine "prevalence" which may be called
   interviewed on their health status or degree of disability (in the    many times. Probs is memory consuming and must be used with
   case of a health survey which is our main interest) -2- at least a    parcimony.
   second wave of interviews ("longitudinal") which measure each change    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
   (if any) in individual health status.  Health expectancies are  
   computed from the time spent in each health state according to a    Revision 1.83  2003/06/10 13:39:11  lievre
   model. More health states you consider, more time is necessary to reach the    *** empty log message ***
   Maximum Likelihood of the parameters involved in the model.  The  
   simplest model is the multinomial logistic model where pij is the    Revision 1.82  2003/06/05 15:57:20  brouard
   probability to be observed in state j at the second wave    Add log in  imach.c and  fullversion number is now printed.
   conditional to be observed in state i at the first wave. Therefore  
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where  */
   'age' is age and 'sex' is a covariate. If you want to have a more  /*
   complex model than "constant and age", you should modify the program     Interpolated Markov Chain
   where the markup *Covariates have to be included here again* invites  
   you to do it.  More covariates you add, slower the    Short summary of the programme:
   convergence.   
     This program computes Healthy Life Expectancies from
   The advantage of this computer programme, compared to a simple    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
   multinomial logistic model, is clear when the delay between waves is not    first survey ("cross") where individuals from different ages are
   identical for each individual. Also, if a individual missed an    interviewed on their health status or degree of disability (in the
   intermediate interview, the information is lost, but taken into    case of a health survey which is our main interest) -2- at least a
   account using an interpolation or extrapolation.      second wave of interviews ("longitudinal") which measure each change
     (if any) in individual health status.  Health expectancies are
   hPijx is the probability to be observed in state i at age x+h    computed from the time spent in each health state according to a
   conditional to the observed state i at age x. The delay 'h' can be    model. More health states you consider, more time is necessary to reach the
   split into an exact number (nh*stepm) of unobserved intermediate    Maximum Likelihood of the parameters involved in the model.  The
   states. This elementary transition (by month, quarter,    simplest model is the multinomial logistic model where pij is the
   semester or year) is modelled as a multinomial logistic.  The hPx    probability to be observed in state j at the second wave
   matrix is simply the matrix product of nh*stepm elementary matrices    conditional to be observed in state i at the first wave. Therefore
   and the contribution of each individual to the likelihood is simply    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
   hPijx.    'age' is age and 'sex' is a covariate. If you want to have a more
     complex model than "constant and age", you should modify the program
   Also this programme outputs the covariance matrix of the parameters but also    where the markup *Covariates have to be included here again* invites
   of the life expectancies. It also computes the period (stable) prevalence.     you to do it.  More covariates you add, slower the
       convergence.
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).  
            Institut national d'études démographiques, Paris.    The advantage of this computer programme, compared to a simple
   This software have been partly granted by Euro-REVES, a concerted action    multinomial logistic model, is clear when the delay between waves is not
   from the European Union.    identical for each individual. Also, if a individual missed an
   It is copyrighted identically to a GNU software product, ie programme and    intermediate interview, the information is lost, but taken into
   software can be distributed freely for non commercial use. Latest version    account using an interpolation or extrapolation.  
   can be accessed at http://euroreves.ined.fr/imach .  
     hPijx is the probability to be observed in state i at age x+h
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    conditional to the observed state i at age x. The delay 'h' can be
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    split into an exact number (nh*stepm) of unobserved intermediate
       states. This elementary transition (by month, quarter,
   **********************************************************************/    semester or year) is modelled as a multinomial logistic.  The hPx
 /*    matrix is simply the matrix product of nh*stepm elementary matrices
   main    and the contribution of each individual to the likelihood is simply
   read parameterfile    hPijx.
   read datafile  
   concatwav    Also this programme outputs the covariance matrix of the parameters but also
   freqsummary    of the life expectancies. It also computes the period (stable) prevalence.
   if (mle >= 1)   
     mlikeli    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
   print results files             Institut national d'études démographiques, Paris.
   if mle==1     This software have been partly granted by Euro-REVES, a concerted action
      computes hessian    from the European Union.
   read end of parameter file: agemin, agemax, bage, fage, estepm    It is copyrighted identically to a GNU software product, ie programme and
       begin-prev-date,...    software can be distributed freely for non commercial use. Latest version
   open gnuplot file    can be accessed at http://euroreves.ined.fr/imach .
   open html file  
   period (stable) prevalence    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
    for age prevalim()    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
   h Pij x   
   variance of p varprob    **********************************************************************/
   forecasting if prevfcast==1 prevforecast call prevalence()  /*
   health expectancies    main
   Variance-covariance of DFLE    read parameterfile
   prevalence()    read datafile
    movingaverage()    concatwav
   varevsij()     freqsummary
   if popbased==1 varevsij(,popbased)    if (mle >= 1)
   total life expectancies      mlikeli
   Variance of period (stable) prevalence    print results files
  end    if mle==1
 */       computes hessian
     read end of parameter file: agemin, agemax, bage, fage, estepm
         begin-prev-date,...
     open gnuplot file
      open html file
 #include <math.h>    period (stable) prevalence
 #include <stdio.h>     for age prevalim()
 #include <stdlib.h>    h Pij x
 #include <string.h>    variance of p varprob
 #include <unistd.h>    forecasting if prevfcast==1 prevforecast call prevalence()
     health expectancies
 #include <limits.h>    Variance-covariance of DFLE
 #include <sys/types.h>    prevalence()
 #include <sys/stat.h>     movingaverage()
 #include <errno.h>    varevsij()
 extern int errno;    if popbased==1 varevsij(,popbased)
     total life expectancies
 /* #include <sys/time.h> */    Variance of period (stable) prevalence
 #include <time.h>   end
 #include "timeval.h"  */
   
 /* #include <libintl.h> */  
 /* #define _(String) gettext (String) */  
    
 #define MAXLINE 256  #include <math.h>
   #include <stdio.h>
 #define GNUPLOTPROGRAM "gnuplot"  #include <stdlib.h>
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/  #include <string.h>
 #define FILENAMELENGTH 132  #include <unistd.h>
   
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */  #include <limits.h>
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */  #include <sys/types.h>
   #include <sys/stat.h>
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */  #include <errno.h>
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  extern int errno;
   
 #define NINTERVMAX 8  /* #include <sys/time.h> */
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */  #include <time.h>
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */  #include "timeval.h"
 #define NCOVMAX 8 /* Maximum number of covariates */  
 #define MAXN 20000  /* #include <libintl.h> */
 #define YEARM 12. /* Number of months per year */  /* #define _(String) gettext (String) */
 #define AGESUP 130  
 #define AGEBASE 40  #define MAXLINE 256
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */  
 #ifdef UNIX  #define GNUPLOTPROGRAM "gnuplot"
 #define DIRSEPARATOR '/'  /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 #define CHARSEPARATOR "/"  #define FILENAMELENGTH 132
 #define ODIRSEPARATOR '\\'  
 #else  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 #define DIRSEPARATOR '\\'  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 #define CHARSEPARATOR "\\"  
 #define ODIRSEPARATOR '/'  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 #endif  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
   
 /* $Id$ */  #define NINTERVMAX 8
 /* $State$ */  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
   #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";  #define NCOVMAX 8 /* Maximum number of covariates */
 char fullversion[]="$Revision$ $Date$";   #define MAXN 20000
 char strstart[80];  #define YEARM 12. /* Number of months per year */
 char optionfilext[10], optionfilefiname[FILENAMELENGTH];  #define AGESUP 130
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */  #define AGEBASE 40
 int nvar;  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;  #ifdef UNIX
 int npar=NPARMAX;  #define DIRSEPARATOR '/'
 int nlstate=2; /* Number of live states */  #define CHARSEPARATOR "/"
 int ndeath=1; /* Number of dead states */  #define ODIRSEPARATOR '\\'
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */  #else
 int popbased=0;  #define DIRSEPARATOR '\\'
   #define CHARSEPARATOR "\\"
 int *wav; /* Number of waves for this individuual 0 is possible */  #define ODIRSEPARATOR '/'
 int maxwav; /* Maxim number of waves */  #endif
 int jmin, jmax; /* min, max spacing between 2 waves */  
 int ijmin, ijmax; /* Individuals having jmin and jmax */   /* $Id$ */
 int gipmx, gsw; /* Global variables on the number of contributions   /* $State$ */
                    to the likelihood and the sum of weights (done by funcone)*/  
 int mle, weightopt;  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */  char fullversion[]="$Revision$ $Date$";
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */  char strstart[80];
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
            * wave mi and wave mi+1 is not an exact multiple of stepm. */  int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 double jmean; /* Mean space between 2 waves */  int nvar;
 double **oldm, **newm, **savm; /* Working pointers to matrices */  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */  int npar=NPARMAX;
 FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;  int nlstate=2; /* Number of live states */
 FILE *ficlog, *ficrespow;  int ndeath=1; /* Number of dead states */
 int globpr; /* Global variable for printing or not */  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 double fretone; /* Only one call to likelihood */  int popbased=0;
 long ipmx; /* Number of contributions */  
 double sw; /* Sum of weights */  int *wav; /* Number of waves for this individuual 0 is possible */
 char filerespow[FILENAMELENGTH];  int maxwav; /* Maxim number of waves */
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */  int jmin, jmax; /* min, max spacing between 2 waves */
 FILE *ficresilk;  int ijmin, ijmax; /* Individuals having jmin and jmax */
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;  int gipmx, gsw; /* Global variables on the number of contributions
 FILE *ficresprobmorprev;                     to the likelihood and the sum of weights (done by funcone)*/
 FILE *fichtm, *fichtmcov; /* Html File */  int mle, weightopt;
 FILE *ficreseij;  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 char filerese[FILENAMELENGTH];  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 FILE *ficresstdeij;  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
 char fileresstde[FILENAMELENGTH];             * wave mi and wave mi+1 is not an exact multiple of stepm. */
 FILE *ficrescveij;  double jmean; /* Mean space between 2 waves */
 char filerescve[FILENAMELENGTH];  double **oldm, **newm, **savm; /* Working pointers to matrices */
 FILE  *ficresvij;  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 char fileresv[FILENAMELENGTH];  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
 FILE  *ficresvpl;  FILE *ficlog, *ficrespow;
 char fileresvpl[FILENAMELENGTH];  int globpr; /* Global variable for printing or not */
 char title[MAXLINE];  double fretone; /* Only one call to likelihood */
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];  long ipmx; /* Number of contributions */
 char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];  double sw; /* Sum of weights */
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];   char filerespow[FILENAMELENGTH];
 char command[FILENAMELENGTH];  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 int  outcmd=0;  FILE *ficresilk;
   FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  FILE *ficresprobmorprev;
   FILE *fichtm, *fichtmcov; /* Html File */
 char filelog[FILENAMELENGTH]; /* Log file */  FILE *ficreseij;
 char filerest[FILENAMELENGTH];  char filerese[FILENAMELENGTH];
 char fileregp[FILENAMELENGTH];  FILE *ficresstdeij;
 char popfile[FILENAMELENGTH];  char fileresstde[FILENAMELENGTH];
   FILE *ficrescveij;
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  char filerescve[FILENAMELENGTH];
   FILE  *ficresvij;
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  char fileresv[FILENAMELENGTH];
 struct timezone tzp;  FILE  *ficresvpl;
 extern int gettimeofday();  char fileresvpl[FILENAMELENGTH];
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  char title[MAXLINE];
 long time_value;  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 extern long time();  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 char strcurr[80], strfor[80];  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
   char command[FILENAMELENGTH];
 char *endptr;  int  outcmd=0;
 long lval;  
 double dval;  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
   
 #define NR_END 1  char filelog[FILENAMELENGTH]; /* Log file */
 #define FREE_ARG char*  char filerest[FILENAMELENGTH];
 #define FTOL 1.0e-10  char fileregp[FILENAMELENGTH];
   char popfile[FILENAMELENGTH];
 #define NRANSI   
 #define ITMAX 200   char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
   
 #define TOL 2.0e-4   struct timeval start_time, end_time, curr_time, last_time, forecast_time;
   struct timezone tzp;
 #define CGOLD 0.3819660   extern int gettimeofday();
 #define ZEPS 1.0e-10   struct tm tmg, tm, tmf, *gmtime(), *localtime();
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   long time_value;
   extern long time();
 #define GOLD 1.618034   char strcurr[80], strfor[80];
 #define GLIMIT 100.0   
 #define TINY 1.0e-20   char *endptr;
   long lval;
 static double maxarg1,maxarg2;  double dval;
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  #define NR_END 1
     #define FREE_ARG char*
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  #define FTOL 1.0e-10
 #define rint(a) floor(a+0.5)  
   #define NRANSI
 static double sqrarg;  #define ITMAX 200
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   #define TOL 2.0e-4
 int agegomp= AGEGOMP;  
   #define CGOLD 0.3819660
 int imx;   #define ZEPS 1.0e-10
 int stepm=1;  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
 /* Stepm, step in month: minimum step interpolation*/  
   #define GOLD 1.618034
 int estepm;  #define GLIMIT 100.0
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  #define TINY 1.0e-20
   
 int m,nb;  static double maxarg1,maxarg2;
 long *num;  #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;   
 double **pmmij, ***probs;  #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 double *ageexmed,*agecens;  #define rint(a) floor(a+0.5)
 double dateintmean=0;  
   static double sqrarg;
 double *weight;  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 int **s; /* Status */  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
 double *agedc, **covar, idx;  int agegomp= AGEGOMP;
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  
 double *lsurv, *lpop, *tpop;  int imx;
   int stepm=1;
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  /* Stepm, step in month: minimum step interpolation*/
 double ftolhess; /* Tolerance for computing hessian */  
   int estepm;
 /**************** split *************************/  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  
 {  int m,nb;
   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)  long *num;
      the name of the file (name), its extension only (ext) and its first part of the name (finame)  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
   */   double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
   char  *ss;                            /* pointer */  double **pmmij, ***probs;
   int   l1, l2;                         /* length counters */  double *ageexmed,*agecens;
   double dateintmean=0;
   l1 = strlen(path );                   /* length of path */  
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  double *weight;
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */  int **s; /* Status */
   if ( ss == NULL ) {                   /* no directory, so determine current directory */  double *agedc, **covar, idx;
     strcpy( name, path );               /* we got the fullname name because no directory */  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)  double *lsurv, *lpop, *tpop;
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/  
     /* get current working directory */  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
     /*    extern  char* getcwd ( char *buf , int len);*/  double ftolhess; /* Tolerance for computing hessian */
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {  
       return( GLOCK_ERROR_GETCWD );  /**************** split *************************/
     }  static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
     /* got dirc from getcwd*/  {
     printf(" DIRC = %s \n",dirc);    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
   } else {                              /* strip direcotry from path */       the name of the file (name), its extension only (ext) and its first part of the name (finame)
     ss++;                               /* after this, the filename */    */
     l2 = strlen( ss );                  /* length of filename */    char  *ss;                            /* pointer */
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );    int   l1, l2;                         /* length counters */
     strcpy( name, ss );         /* save file name */  
     strncpy( dirc, path, l1 - l2 );     /* now the directory */    l1 = strlen(path );                   /* length of path */
     dirc[l1-l2] = 0;                    /* add zero */    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
     printf(" DIRC2 = %s \n",dirc);    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
   }    if ( ss == NULL ) {                   /* no directory, so determine current directory */
   /* We add a separator at the end of dirc if not exists */      strcpy( name, path );               /* we got the fullname name because no directory */
   l1 = strlen( dirc );                  /* length of directory */      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
   if( dirc[l1-1] != DIRSEPARATOR ){        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
     dirc[l1] =  DIRSEPARATOR;      /* get current working directory */
     dirc[l1+1] = 0;       /*    extern  char* getcwd ( char *buf , int len);*/
     printf(" DIRC3 = %s \n",dirc);      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
   }        return( GLOCK_ERROR_GETCWD );
   ss = strrchr( name, '.' );            /* find last / */      }
   if (ss >0){      /* got dirc from getcwd*/
     ss++;      printf(" DIRC = %s \n",dirc);
     strcpy(ext,ss);                     /* save extension */    } else {                              /* strip direcotry from path */
     l1= strlen( name);      ss++;                               /* after this, the filename */
     l2= strlen(ss)+1;      l2 = strlen( ss );                  /* length of filename */
     strncpy( finame, name, l1-l2);      if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
     finame[l1-l2]= 0;      strcpy( name, ss );         /* save file name */
   }      strncpy( dirc, path, l1 - l2 );     /* now the directory */
       dirc[l1-l2] = 0;                    /* add zero */
   return( 0 );                          /* we're done */      printf(" DIRC2 = %s \n",dirc);
 }    }
     /* We add a separator at the end of dirc if not exists */
     l1 = strlen( dirc );                  /* length of directory */
 /******************************************/    if( dirc[l1-1] != DIRSEPARATOR ){
       dirc[l1] =  DIRSEPARATOR;
 void replace_back_to_slash(char *s, char*t)      dirc[l1+1] = 0;
 {      printf(" DIRC3 = %s \n",dirc);
   int i;    }
   int lg=0;    ss = strrchr( name, '.' );            /* find last / */
   i=0;    if (ss >0){
   lg=strlen(t);      ss++;
   for(i=0; i<= lg; i++) {      strcpy(ext,ss);                     /* save extension */
     (s[i] = t[i]);      l1= strlen( name);
     if (t[i]== '\\') s[i]='/';      l2= strlen(ss)+1;
   }      strncpy( finame, name, l1-l2);
 }      finame[l1-l2]= 0;
     }
 int nbocc(char *s, char occ)  
 {    return( 0 );                          /* we're done */
   int i,j=0;  }
   int lg=20;  
   i=0;  
   lg=strlen(s);  /******************************************/
   for(i=0; i<= lg; i++) {  
   if  (s[i] == occ ) j++;  void replace_back_to_slash(char *s, char*t)
   }  {
   return j;    int i;
 }    int lg=0;
     i=0;
 void cutv(char *u,char *v, char*t, char occ)    lg=strlen(t);
 {    for(i=0; i<= lg; i++) {
   /* cuts string t into u and v where u ends before first occurence of char 'occ'       (s[i] = t[i]);
      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')      if (t[i]== '\\') s[i]='/';
      gives u="abcedf" and v="ghi2j" */    }
   int i,lg,j,p=0;  }
   i=0;  
   for(j=0; j<=strlen(t)-1; j++) {  int nbocc(char *s, char occ)
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;  {
   }    int i,j=0;
     int lg=20;
   lg=strlen(t);    i=0;
   for(j=0; j<p; j++) {    lg=strlen(s);
     (u[j] = t[j]);    for(i=0; i<= lg; i++) {
   }    if  (s[i] == occ ) j++;
      u[p]='\0';    }
     return j;
    for(j=0; j<= lg; j++) {  }
     if (j>=(p+1))(v[j-p-1] = t[j]);  
   }  void cutv(char *u,char *v, char*t, char occ)
 }  {
     /* cuts string t into u and v where u ends before first occurence of char 'occ'
 /********************** nrerror ********************/       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
        gives u="abcedf" and v="ghi2j" */
 void nrerror(char error_text[])    int i,lg,j,p=0;
 {    i=0;
   fprintf(stderr,"ERREUR ...\n");    for(j=0; j<=strlen(t)-1; j++) {
   fprintf(stderr,"%s\n",error_text);      if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
   exit(EXIT_FAILURE);    }
 }  
 /*********************** vector *******************/    lg=strlen(t);
 double *vector(int nl, int nh)    for(j=0; j<p; j++) {
 {      (u[j] = t[j]);
   double *v;    }
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));       u[p]='\0';
   if (!v) nrerror("allocation failure in vector");  
   return v-nl+NR_END;     for(j=0; j<= lg; j++) {
 }      if (j>=(p+1))(v[j-p-1] = t[j]);
     }
 /************************ free vector ******************/  }
 void free_vector(double*v, int nl, int nh)  
 {  /********************** nrerror ********************/
   free((FREE_ARG)(v+nl-NR_END));  
 }  void nrerror(char error_text[])
   {
 /************************ivector *******************************/    fprintf(stderr,"ERREUR ...\n");
 int *ivector(long nl,long nh)    fprintf(stderr,"%s\n",error_text);
 {    exit(EXIT_FAILURE);
   int *v;  }
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));  /*********************** vector *******************/
   if (!v) nrerror("allocation failure in ivector");  double *vector(int nl, int nh)
   return v-nl+NR_END;  {
 }    double *v;
     v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 /******************free ivector **************************/    if (!v) nrerror("allocation failure in vector");
 void free_ivector(int *v, long nl, long nh)    return v-nl+NR_END;
 {  }
   free((FREE_ARG)(v+nl-NR_END));  
 }  /************************ free vector ******************/
   void free_vector(double*v, int nl, int nh)
 /************************lvector *******************************/  {
 long *lvector(long nl,long nh)    free((FREE_ARG)(v+nl-NR_END));
 {  }
   long *v;  
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));  /************************ivector *******************************/
   if (!v) nrerror("allocation failure in ivector");  int *ivector(long nl,long nh)
   return v-nl+NR_END;  {
 }    int *v;
     v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 /******************free lvector **************************/    if (!v) nrerror("allocation failure in ivector");
 void free_lvector(long *v, long nl, long nh)    return v-nl+NR_END;
 {  }
   free((FREE_ARG)(v+nl-NR_END));  
 }  /******************free ivector **************************/
   void free_ivector(int *v, long nl, long nh)
 /******************* imatrix *******************************/  {
 int **imatrix(long nrl, long nrh, long ncl, long nch)     free((FREE_ARG)(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;   /************************lvector *******************************/
   int **m;   long *lvector(long nl,long nh)
     {
   /* allocate pointers to rows */     long *v;
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));     v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
   if (!m) nrerror("allocation failure 1 in matrix()");     if (!v) nrerror("allocation failure in ivector");
   m += NR_END;     return v-nl+NR_END;
   m -= nrl;   }
     
     /******************free lvector **************************/
   /* allocate rows and set pointers to them */   void free_lvector(long *v, long nl, long nh)
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));   {
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");     free((FREE_ARG)(v+nl-NR_END));
   m[nrl] += NR_END;   }
   m[nrl] -= ncl;   
     /******************* imatrix *******************************/
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;   int **imatrix(long nrl, long nrh, long ncl, long nch)
          /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
   /* return pointer to array of pointers to rows */   {
   return m;     long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
 }     int **m;
    
 /****************** free_imatrix *************************/    /* allocate pointers to rows */
 void free_imatrix(m,nrl,nrh,ncl,nch)    m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
       int **m;    if (!m) nrerror("allocation failure 1 in matrix()");
       long nch,ncl,nrh,nrl;     m += NR_END;
      /* free an int matrix allocated by imatrix() */     m -= nrl;
 {    
   free((FREE_ARG) (m[nrl]+ncl-NR_END));    
   free((FREE_ARG) (m+nrl-NR_END));     /* 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()");
 /******************* matrix *******************************/    m[nrl] += NR_END;
 double **matrix(long nrl, long nrh, long ncl, long nch)    m[nrl] -= ncl;
 {   
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
   double **m;   
     /* return pointer to array of pointers to rows */
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));    return m;
   if (!m) nrerror("allocation failure 1 in matrix()");  }
   m += NR_END;  
   m -= nrl;  /****************** free_imatrix *************************/
   void free_imatrix(m,nrl,nrh,ncl,nch)
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));        int **m;
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");        long nch,ncl,nrh,nrl;
   m[nrl] += NR_END;       /* free an int matrix allocated by imatrix() */
   m[nrl] -= ncl;  {
     free((FREE_ARG) (m[nrl]+ncl-NR_END));
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    free((FREE_ARG) (m+nrl-NR_END));
   return m;  }
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])   
    */  /******************* matrix *******************************/
 }  double **matrix(long nrl, long nrh, long ncl, long nch)
   {
 /*************************free matrix ************************/    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)    double **m;
 {  
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   free((FREE_ARG)(m+nrl-NR_END));    if (!m) nrerror("allocation failure 1 in matrix()");
 }    m += NR_END;
     m -= nrl;
 /******************* ma3x *******************************/  
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)    m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 {    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;    m[nrl] += NR_END;
   double ***m;    m[nrl] -= ncl;
   
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   if (!m) nrerror("allocation failure 1 in matrix()");    return m;
   m += NR_END;    /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
   m -= nrl;     */
   }
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));  
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  /*************************free matrix ************************/
   m[nrl] += NR_END;  void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   m[nrl] -= ncl;  {
     free((FREE_ARG)(m[nrl]+ncl-NR_END));
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    free((FREE_ARG)(m+nrl-NR_END));
   }
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));  
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");  /******************* ma3x *******************************/
   m[nrl][ncl] += NR_END;  double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
   m[nrl][ncl] -= nll;  {
   for (j=ncl+1; j<=nch; j++)     long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
     m[nrl][j]=m[nrl][j-1]+nlay;    double ***m;
     
   for (i=nrl+1; i<=nrh; i++) {    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;    if (!m) nrerror("allocation failure 1 in matrix()");
     for (j=ncl+1; j<=nch; j++)     m += NR_END;
       m[i][j]=m[i][j-1]+nlay;    m -= nrl;
   }  
   return m;     m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)    m[nrl] += NR_END;
   */    m[nrl] -= ncl;
 }  
     for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 /*************************free ma3x ************************/  
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 {    if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    m[nrl][ncl] += NR_END;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    m[nrl][ncl] -= nll;
   free((FREE_ARG)(m+nrl-NR_END));    for (j=ncl+1; j<=nch; j++)
 }      m[nrl][j]=m[nrl][j-1]+nlay;
    
 /*************** function subdirf ***********/    for (i=nrl+1; i<=nrh; i++) {
 char *subdirf(char fileres[])      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 {      for (j=ncl+1; j<=nch; j++)
   /* Caution optionfilefiname is hidden */        m[i][j]=m[i][j-1]+nlay;
   strcpy(tmpout,optionfilefiname);    }
   strcat(tmpout,"/"); /* Add to the right */    return m;
   strcat(tmpout,fileres);    /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
   return tmpout;             &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 }    */
   }
 /*************** function subdirf2 ***********/  
 char *subdirf2(char fileres[], char *preop)  /*************************free ma3x ************************/
 {  void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
     {
   /* Caution optionfilefiname is hidden */    free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
   strcpy(tmpout,optionfilefiname);    free((FREE_ARG)(m[nrl]+ncl-NR_END));
   strcat(tmpout,"/");    free((FREE_ARG)(m+nrl-NR_END));
   strcat(tmpout,preop);  }
   strcat(tmpout,fileres);  
   return tmpout;  /*************** function subdirf ***********/
 }  char *subdirf(char fileres[])
   {
 /*************** function subdirf3 ***********/    /* Caution optionfilefiname is hidden */
 char *subdirf3(char fileres[], char *preop, char *preop2)    strcpy(tmpout,optionfilefiname);
 {    strcat(tmpout,"/"); /* Add to the right */
       strcat(tmpout,fileres);
   /* Caution optionfilefiname is hidden */    return tmpout;
   strcpy(tmpout,optionfilefiname);  }
   strcat(tmpout,"/");  
   strcat(tmpout,preop);  /*************** function subdirf2 ***********/
   strcat(tmpout,preop2);  char *subdirf2(char fileres[], char *preop)
   strcat(tmpout,fileres);  {
   return tmpout;   
 }    /* Caution optionfilefiname is hidden */
     strcpy(tmpout,optionfilefiname);
 /***************** f1dim *************************/    strcat(tmpout,"/");
 extern int ncom;     strcat(tmpout,preop);
 extern double *pcom,*xicom;    strcat(tmpout,fileres);
 extern double (*nrfunc)(double []);     return tmpout;
    }
 double f1dim(double x)   
 {   /*************** function subdirf3 ***********/
   int j;   char *subdirf3(char fileres[], char *preop, char *preop2)
   double f;  {
   double *xt;    
      /* Caution optionfilefiname is hidden */
   xt=vector(1,ncom);     strcpy(tmpout,optionfilefiname);
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];     strcat(tmpout,"/");
   f=(*nrfunc)(xt);     strcat(tmpout,preop);
   free_vector(xt,1,ncom);     strcat(tmpout,preop2);
   return f;     strcat(tmpout,fileres);
 }     return tmpout;
   }
 /*****************brent *************************/  
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)   /***************** f1dim *************************/
 {   extern int ncom;
   int iter;   extern double *pcom,*xicom;
   double a,b,d,etemp;  extern double (*nrfunc)(double []);
   double fu,fv,fw,fx;   
   double ftemp;  double f1dim(double x)
   double p,q,r,tol1,tol2,u,v,w,x,xm;   {
   double e=0.0;     int j;
      double f;
   a=(ax < cx ? ax : cx);     double *xt;
   b=(ax > cx ? ax : cx);    
   x=w=v=bx;     xt=vector(1,ncom);
   fw=fv=fx=(*f)(x);     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
   for (iter=1;iter<=ITMAX;iter++) {     f=(*nrfunc)(xt);
     xm=0.5*(a+b);     free_vector(xt,1,ncom);
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     return f;
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/  }
     printf(".");fflush(stdout);  
     fprintf(ficlog,".");fflush(ficlog);  /*****************brent *************************/
 #ifdef DEBUG  double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
     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);    int iter;
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */    double a,b,d,etemp;
 #endif    double fu,fv,fw,fx;
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){     double ftemp;
       *xmin=x;     double p,q,r,tol1,tol2,u,v,w,x,xm;
       return fx;     double e=0.0;
     }    
     ftemp=fu;    a=(ax < cx ? ax : cx);
     if (fabs(e) > tol1) {     b=(ax > cx ? ax : cx);
       r=(x-w)*(fx-fv);     x=w=v=bx;
       q=(x-v)*(fx-fw);     fw=fv=fx=(*f)(x);
       p=(x-v)*q-(x-w)*r;     for (iter=1;iter<=ITMAX;iter++) {
       q=2.0*(q-r);       xm=0.5*(a+b);
       if (q > 0.0) p = -p;       tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
       q=fabs(q);       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
       etemp=e;       printf(".");fflush(stdout);
       e=d;       fprintf(ficlog,".");fflush(ficlog);
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))   #ifdef DEBUG
         d=CGOLD*(e=(x >= xm ? a-x : b-x));       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);
       else {       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);
         d=p/q;       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
         u=x+d;   #endif
         if (u-a < tol2 || b-u < tol2)       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
           d=SIGN(tol1,xm-x);         *xmin=x;
       }         return fx;
     } else {       }
       d=CGOLD*(e=(x >= xm ? a-x : b-x));       ftemp=fu;
     }       if (fabs(e) > tol1) {
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));         r=(x-w)*(fx-fv);
     fu=(*f)(u);         q=(x-v)*(fx-fw);
     if (fu <= fx) {         p=(x-v)*q-(x-w)*r;
       if (u >= x) a=x; else b=x;         q=2.0*(q-r);
       SHFT(v,w,x,u)         if (q > 0.0) p = -p;
         SHFT(fv,fw,fx,fu)         q=fabs(q);
         } else {         etemp=e;
           if (u < x) a=u; else b=u;         e=d;
           if (fu <= fw || w == x) {         if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
             v=w;           d=CGOLD*(e=(x >= xm ? a-x : b-x));
             w=u;         else {
             fv=fw;           d=p/q;
             fw=fu;           u=x+d;
           } else if (fu <= fv || v == x || v == w) {           if (u-a < tol2 || b-u < tol2)
             v=u;             d=SIGN(tol1,xm-x);
             fv=fu;         }
           }       } else {
         }         d=CGOLD*(e=(x >= xm ? a-x : b-x));
   }       }
   nrerror("Too many iterations in brent");       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
   *xmin=x;       fu=(*f)(u);
   return fx;       if (fu <= fx) {
 }         if (u >= x) a=x; else b=x;
         SHFT(v,w,x,u)
 /****************** mnbrak ***********************/          SHFT(fv,fw,fx,fu)
           } else {
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,             if (u < x) a=u; else b=u;
             double (*func)(double))             if (fu <= fw || w == x) {
 {               v=w;
   double ulim,u,r,q, dum;              w=u;
   double fu;               fv=fw;
                fw=fu;
   *fa=(*func)(*ax);             } else if (fu <= fv || v == x || v == w) {
   *fb=(*func)(*bx);               v=u;
   if (*fb > *fa) {               fv=fu;
     SHFT(dum,*ax,*bx,dum)             }
       SHFT(dum,*fb,*fa,dum)           }
       }     }
   *cx=(*bx)+GOLD*(*bx-*ax);     nrerror("Too many iterations in brent");
   *fc=(*func)(*cx);     *xmin=x;
   while (*fb > *fc) {     return fx;
     r=(*bx-*ax)*(*fb-*fc);   }
     q=(*bx-*cx)*(*fb-*fa);   
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/   /****************** mnbrak ***********************/
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));   
     ulim=(*bx)+GLIMIT*(*cx-*bx);   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
     if ((*bx-u)*(u-*cx) > 0.0) {               double (*func)(double))
       fu=(*func)(u);   {
     } else if ((*cx-u)*(u-ulim) > 0.0) {     double ulim,u,r,q, dum;
       fu=(*func)(u);     double fu;
       if (fu < *fc) {    
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))     *fa=(*func)(*ax);
           SHFT(*fb,*fc,fu,(*func)(u))     *fb=(*func)(*bx);
           }     if (*fb > *fa) {
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {       SHFT(dum,*ax,*bx,dum)
       u=ulim;         SHFT(dum,*fb,*fa,dum)
       fu=(*func)(u);         }
     } else {     *cx=(*bx)+GOLD*(*bx-*ax);
       u=(*cx)+GOLD*(*cx-*bx);     *fc=(*func)(*cx);
       fu=(*func)(u);     while (*fb > *fc) {
     }       r=(*bx-*ax)*(*fb-*fc);
     SHFT(*ax,*bx,*cx,u)       q=(*bx-*cx)*(*fb-*fa);
       SHFT(*fa,*fb,*fc,fu)       u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
       }         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
 }       ulim=(*bx)+GLIMIT*(*cx-*bx);
       if ((*bx-u)*(u-*cx) > 0.0) {
 /*************** linmin ************************/        fu=(*func)(u);
       } else if ((*cx-u)*(u-ulim) > 0.0) {
 int ncom;         fu=(*func)(u);
 double *pcom,*xicom;        if (fu < *fc) {
 double (*nrfunc)(double []);           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
              SHFT(*fb,*fc,fu,(*func)(u))
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))             }
 {       } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
   double brent(double ax, double bx, double cx,         u=ulim;
                double (*f)(double), double tol, double *xmin);         fu=(*func)(u);
   double f1dim(double x);       } else {
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,         u=(*cx)+GOLD*(*cx-*bx);
               double *fc, double (*func)(double));         fu=(*func)(u);
   int j;       }
   double xx,xmin,bx,ax;       SHFT(*ax,*bx,*cx,u)
   double fx,fb,fa;        SHFT(*fa,*fb,*fc,fu)
          }
   ncom=n;   }
   pcom=vector(1,n);   
   xicom=vector(1,n);   /*************** linmin ************************/
   nrfunc=func;   
   for (j=1;j<=n;j++) {   int ncom;
     pcom[j]=p[j];   double *pcom,*xicom;
     xicom[j]=xi[j];   double (*nrfunc)(double []);
   }    
   ax=0.0;   void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
   xx=1.0;   {
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);     double brent(double ax, double bx, double cx,
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);                  double (*f)(double), double tol, double *xmin);
 #ifdef DEBUG    double f1dim(double x);
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);                double *fc, double (*func)(double));
 #endif    int j;
   for (j=1;j<=n;j++) {     double xx,xmin,bx,ax;
     xi[j] *= xmin;     double fx,fb,fa;
     p[j] += xi[j];    
   }     ncom=n;
   free_vector(xicom,1,n);     pcom=vector(1,n);
   free_vector(pcom,1,n);     xicom=vector(1,n);
 }     nrfunc=func;
     for (j=1;j<=n;j++) {
 char *asc_diff_time(long time_sec, char ascdiff[])      pcom[j]=p[j];
 {      xicom[j]=xi[j];
   long sec_left, days, hours, minutes;    }
   days = (time_sec) / (60*60*24);    ax=0.0;
   sec_left = (time_sec) % (60*60*24);    xx=1.0;
   hours = (sec_left) / (60*60) ;    mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
   sec_left = (sec_left) %(60*60);    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
   minutes = (sec_left) /60;  #ifdef DEBUG
   sec_left = (sec_left) % (60);    printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);      fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   return ascdiff;  #endif
 }    for (j=1;j<=n;j++) {
       xi[j] *= xmin;
 /*************** powell ************************/      p[j] += xi[j];
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,     }
             double (*func)(double []))     free_vector(xicom,1,n);
 {     free_vector(pcom,1,n);
   void linmin(double p[], double xi[], int n, double *fret,   }
               double (*func)(double []));   
   int i,ibig,j;   char *asc_diff_time(long time_sec, char ascdiff[])
   double del,t,*pt,*ptt,*xit;  {
   double fp,fptt;    long sec_left, days, hours, minutes;
   double *xits;    days = (time_sec) / (60*60*24);
   int niterf, itmp;    sec_left = (time_sec) % (60*60*24);
     hours = (sec_left) / (60*60) ;
   pt=vector(1,n);     sec_left = (sec_left) %(60*60);
   ptt=vector(1,n);     minutes = (sec_left) /60;
   xit=vector(1,n);     sec_left = (sec_left) % (60);
   xits=vector(1,n);     sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
   *fret=(*func)(p);     return ascdiff;
   for (j=1;j<=n;j++) pt[j]=p[j];   }
   for (*iter=1;;++(*iter)) {   
     fp=(*fret);   /*************** powell ************************/
     ibig=0;   void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
     del=0.0;               double (*func)(double []))
     last_time=curr_time;  {
     (void) gettimeofday(&curr_time,&tzp);    void linmin(double p[], double xi[], int n, double *fret,
     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);                double (*func)(double []));
     /*    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);    int i,ibig,j;
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);    double del,t,*pt,*ptt,*xit;
     */    double fp,fptt;
    for (i=1;i<=n;i++) {    double *xits;
       printf(" %d %.12f",i, p[i]);    int niterf, itmp;
       fprintf(ficlog," %d %.12lf",i, p[i]);  
       fprintf(ficrespow," %.12lf", p[i]);    pt=vector(1,n);
     }    ptt=vector(1,n);
     printf("\n");    xit=vector(1,n);
     fprintf(ficlog,"\n");    xits=vector(1,n);
     fprintf(ficrespow,"\n");fflush(ficrespow);    *fret=(*func)(p);
     if(*iter <=3){    for (j=1;j<=n;j++) pt[j]=p[j];
       tm = *localtime(&curr_time.tv_sec);    for (*iter=1;;++(*iter)) {
       strcpy(strcurr,asctime(&tm));      fp=(*fret);
 /*       asctime_r(&tm,strcurr); */      ibig=0;
       forecast_time=curr_time;       del=0.0;
       itmp = strlen(strcurr);      last_time=curr_time;
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */      (void) gettimeofday(&curr_time,&tzp);
         strcurr[itmp-1]='\0';      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("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);      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,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
       for(niterf=10;niterf<=30;niterf+=10){     for (i=1;i<=n;i++) {
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);        printf(" %d %.12f",i, p[i]);
         tmf = *localtime(&forecast_time.tv_sec);        fprintf(ficlog," %d %.12lf",i, p[i]);
 /*      asctime_r(&tmf,strfor); */        fprintf(ficrespow," %.12lf", p[i]);
         strcpy(strfor,asctime(&tmf));      }
         itmp = strlen(strfor);      printf("\n");
         if(strfor[itmp-1]=='\n')      fprintf(ficlog,"\n");
         strfor[itmp-1]='\0';      fprintf(ficrespow,"\n");fflush(ficrespow);
         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);      if(*iter <=3){
         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);        tm = *localtime(&curr_time.tv_sec);
       }        strcpy(strcurr,asctime(&tm));
     }  /*       asctime_r(&tm,strcurr); */
     for (i=1;i<=n;i++) {         forecast_time=curr_time;
       for (j=1;j<=n;j++) xit[j]=xi[j][i];         itmp = strlen(strcurr);
       fptt=(*fret);         if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 #ifdef DEBUG          strcurr[itmp-1]='\0';
       printf("fret=%lf \n",*fret);        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       fprintf(ficlog,"fret=%lf \n",*fret);        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
 #endif        for(niterf=10;niterf<=30;niterf+=10){
       printf("%d",i);fflush(stdout);          forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
       fprintf(ficlog,"%d",i);fflush(ficlog);          tmf = *localtime(&forecast_time.tv_sec);
       linmin(p,xit,n,fret,func);   /*      asctime_r(&tmf,strfor); */
       if (fabs(fptt-(*fret)) > del) {           strcpy(strfor,asctime(&tmf));
         del=fabs(fptt-(*fret));           itmp = strlen(strfor);
         ibig=i;           if(strfor[itmp-1]=='\n')
       }           strfor[itmp-1]='\0';
 #ifdef DEBUG          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);
       printf("%d %.12e",i,(*fret));          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);
       fprintf(ficlog,"%d %.12e",i,(*fret));        }
       for (j=1;j<=n;j++) {      }
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);      for (i=1;i<=n;i++) {
         printf(" x(%d)=%.12e",j,xit[j]);        for (j=1;j<=n;j++) xit[j]=xi[j][i];
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);        fptt=(*fret);
       }  #ifdef DEBUG
       for(j=1;j<=n;j++) {        printf("fret=%lf \n",*fret);
         printf(" p=%.12e",p[j]);        fprintf(ficlog,"fret=%lf \n",*fret);
         fprintf(ficlog," p=%.12e",p[j]);  #endif
       }        printf("%d",i);fflush(stdout);
       printf("\n");        fprintf(ficlog,"%d",i);fflush(ficlog);
       fprintf(ficlog,"\n");        linmin(p,xit,n,fret,func);
 #endif        if (fabs(fptt-(*fret)) > del) {
     }           del=fabs(fptt-(*fret));
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {          ibig=i;
 #ifdef DEBUG        }
       int k[2],l;  #ifdef DEBUG
       k[0]=1;        printf("%d %.12e",i,(*fret));
       k[1]=-1;        fprintf(ficlog,"%d %.12e",i,(*fret));
       printf("Max: %.12e",(*func)(p));        for (j=1;j<=n;j++) {
       fprintf(ficlog,"Max: %.12e",(*func)(p));          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
       for (j=1;j<=n;j++) {          printf(" x(%d)=%.12e",j,xit[j]);
         printf(" %.12e",p[j]);          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
         fprintf(ficlog," %.12e",p[j]);        }
       }        for(j=1;j<=n;j++) {
       printf("\n");          printf(" p=%.12e",p[j]);
       fprintf(ficlog,"\n");          fprintf(ficlog," p=%.12e",p[j]);
       for(l=0;l<=1;l++) {        }
         for (j=1;j<=n;j++) {        printf("\n");
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];        fprintf(ficlog,"\n");
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);  #endif
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);      }
         }      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));  #ifdef DEBUG
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        int k[2],l;
       }        k[0]=1;
 #endif        k[1]=-1;
         printf("Max: %.12e",(*func)(p));
         fprintf(ficlog,"Max: %.12e",(*func)(p));
       free_vector(xit,1,n);         for (j=1;j<=n;j++) {
       free_vector(xits,1,n);           printf(" %.12e",p[j]);
       free_vector(ptt,1,n);           fprintf(ficlog," %.12e",p[j]);
       free_vector(pt,1,n);         }
       return;         printf("\n");
     }         fprintf(ficlog,"\n");
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");         for(l=0;l<=1;l++) {
     for (j=1;j<=n;j++) {           for (j=1;j<=n;j++) {
       ptt[j]=2.0*p[j]-pt[j];             ptt[j]=p[j]+(p[j]-pt[j])*k[l];
       xit[j]=p[j]-pt[j];             printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
       pt[j]=p[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]);
     }           }
     fptt=(*func)(ptt);           printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
     if (fptt < fp) {           fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);         }
       if (t < 0.0) {   #endif
         linmin(p,xit,n,fret,func);   
         for (j=1;j<=n;j++) {   
           xi[j][ibig]=xi[j][n];         free_vector(xit,1,n);
           xi[j][n]=xit[j];         free_vector(xits,1,n);
         }        free_vector(ptt,1,n);
 #ifdef DEBUG        free_vector(pt,1,n);
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        return;
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);      }
         for(j=1;j<=n;j++){      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
           printf(" %.12e",xit[j]);      for (j=1;j<=n;j++) {
           fprintf(ficlog," %.12e",xit[j]);        ptt[j]=2.0*p[j]-pt[j];
         }        xit[j]=p[j]-pt[j];
         printf("\n");        pt[j]=p[j];
         fprintf(ficlog,"\n");      }
 #endif      fptt=(*func)(ptt);
       }      if (fptt < fp) {
     }         t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
   }         if (t < 0.0) {
 }           linmin(p,xit,n,fret,func);
           for (j=1;j<=n;j++) {
 /**** Prevalence limit (stable or period prevalence)  ****************/            xi[j][ibig]=xi[j][n];
             xi[j][n]=xit[j];
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)          }
 {  #ifdef DEBUG
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
      matrix by transitions matrix until convergence is reached */          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
           for(j=1;j<=n;j++){
   int i, ii,j,k;            printf(" %.12e",xit[j]);
   double min, max, maxmin, maxmax,sumnew=0.;            fprintf(ficlog," %.12e",xit[j]);
   double **matprod2();          }
   double **out, cov[NCOVMAX], **pmij();          printf("\n");
   double **newm;          fprintf(ficlog,"\n");
   double agefin, delaymax=50 ; /* Max number of years to converge */  #endif
         }
   for (ii=1;ii<=nlstate+ndeath;ii++)      }
     for (j=1;j<=nlstate+ndeath;j++){    }
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);  }
     }  
   /**** Prevalence limit (stable or period prevalence)  ****************/
    cov[1]=1.;  
    double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */  {
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
     newm=savm;       matrix by transitions matrix until convergence is reached */
     /* Covariates have to be included here again */  
      cov[2]=agefin;    int i, ii,j,k;
       double min, max, maxmin, maxmax,sumnew=0.;
       for (k=1; k<=cptcovn;k++) {    double **matprod2();
         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];    double **out, cov[NCOVMAX], **pmij();
         /*      printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/    double **newm;
       }    double agefin, delaymax=50 ; /* Max number of years to converge */
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];  
       for (k=1; k<=cptcovprod;k++)    for (ii=1;ii<=nlstate+ndeath;ii++)
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];      for (j=1;j<=nlstate+ndeath;j++){
         oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       /*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]);*/     cov[1]=1.;
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);   
    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
     savm=oldm;    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
     oldm=newm;      newm=savm;
     maxmax=0.;      /* Covariates have to be included here again */
     for(j=1;j<=nlstate;j++){       cov[2]=agefin;
       min=1.;   
       max=0.;        for (k=1; k<=cptcovn;k++) {
       for(i=1; i<=nlstate; i++) {          cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
         sumnew=0;          /*      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(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];        }
         prlim[i][j]= newm[i][j]/(1-sumnew);        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         max=FMAX(max,prlim[i][j]);        for (k=1; k<=cptcovprod;k++)
         min=FMIN(min,prlim[i][j]);          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
       }  
       maxmin=max-min;        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
       maxmax=FMAX(maxmax,maxmin);        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
     }        /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
     if(maxmax < ftolpl){      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
       return prlim;  
     }      savm=oldm;
   }      oldm=newm;
 }      maxmax=0.;
       for(j=1;j<=nlstate;j++){
 /*************** transition probabilities ***************/         min=1.;
         max=0.;
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )        for(i=1; i<=nlstate; i++) {
 {          sumnew=0;
   double s1, s2;          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
   /*double t34;*/          prlim[i][j]= newm[i][j]/(1-sumnew);
   int i,j,j1, nc, ii, jj;          max=FMAX(max,prlim[i][j]);
           min=FMIN(min,prlim[i][j]);
     for(i=1; i<= nlstate; i++){        }
       for(j=1; j<i;j++){        maxmin=max-min;
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){        maxmax=FMAX(maxmax,maxmin);
           /*s2 += param[i][j][nc]*cov[nc];*/      }
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];      if(maxmax < ftolpl){
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */        return prlim;
         }      }
         ps[i][j]=s2;    }
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */  }
       }  
       for(j=i+1; j<=nlstate+ndeath;j++){  /*************** transition probabilities ***************/
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){  
           s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */  {
         }    double s1, s2;
         ps[i][j]=s2;    /*double t34;*/
       }    int i,j,j1, nc, ii, jj;
     }  
     /*ps[3][2]=1;*/      for(i=1; i<= nlstate; i++){
             for(j=1; j<i;j++){
     for(i=1; i<= nlstate; i++){          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
       s1=0;            /*s2 += param[i][j][nc]*cov[nc];*/
       for(j=1; j<i; j++)            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
         s1+=exp(ps[i][j]);  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
       for(j=i+1; j<=nlstate+ndeath; j++)          }
         s1+=exp(ps[i][j]);          ps[i][j]=s2;
       ps[i][i]=1./(s1+1.);  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
       for(j=1; j<i; j++)        }
         ps[i][j]= exp(ps[i][j])*ps[i][i];        for(j=i+1; j<=nlstate+ndeath;j++){
       for(j=i+1; j<=nlstate+ndeath; j++)          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
         ps[i][j]= exp(ps[i][j])*ps[i][i];            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
     } /* end i */          }
               ps[i][j]=s2;
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){        }
       for(jj=1; jj<= nlstate+ndeath; jj++){      }
         ps[ii][jj]=0;      /*ps[3][2]=1;*/
         ps[ii][ii]=1;     
       }      for(i=1; i<= nlstate; i++){
     }        s1=0;
             for(j=1; j<i; j++)
           s1+=exp(ps[i][j]);
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */        for(j=i+1; j<=nlstate+ndeath; j++)
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */          s1+=exp(ps[i][j]);
 /*         printf("ddd %lf ",ps[ii][jj]); */        ps[i][i]=1./(s1+1.);
 /*       } */        for(j=1; j<i; j++)
 /*       printf("\n "); */          ps[i][j]= exp(ps[i][j])*ps[i][i];
 /*        } */        for(j=i+1; j<=nlstate+ndeath; j++)
 /*        printf("\n ");printf("%lf ",cov[2]); */          ps[i][j]= exp(ps[i][j])*ps[i][i];
        /*        /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
       for(i=1; i<= npar; i++) printf("%f ",x[i]);      } /* end i */
       goto end;*/     
     return ps;      for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 }        for(jj=1; jj<= nlstate+ndeath; jj++){
           ps[ii][jj]=0;
 /**************** Product of 2 matrices ******************/          ps[ii][ii]=1;
         }
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)      }
 {     
   /* 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(...) */  /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
   /* in, b, out are matrice of pointers which should have been initialized   /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
      before: only the contents of out is modified. The function returns  /*         printf("ddd %lf ",ps[ii][jj]); */
      a pointer to pointers identical to out */  /*       } */
   long i, j, k;  /*       printf("\n "); */
   for(i=nrl; i<= nrh; i++)  /*        } */
     for(k=ncolol; k<=ncoloh; k++)  /*        printf("\n ");printf("%lf ",cov[2]); */
       for(j=ncl,out[i][k]=0.; j<=nch; j++)         /*
         out[i][k] +=in[i][j]*b[j][k];        for(i=1; i<= npar; i++) printf("%f ",x[i]);
         goto end;*/
   return out;      return ps;
 }  }
   
   /**************** Product of 2 matrices ******************/
 /************* Higher Matrix Product ***************/  
   double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )  {
 {    /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
   /* Computes the transition matrix starting at age 'age' over        b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
      'nhstepm*hstepm*stepm' months (i.e. until    /* in, b, out are matrice of pointers which should have been initialized
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying        before: only the contents of out is modified. The function returns
      nhstepm*hstepm matrices.        a pointer to pointers identical to out */
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step     long i, j, k;
      (typically every 2 years instead of every month which is too big     for(i=nrl; i<= nrh; i++)
      for the memory).      for(k=ncolol; k<=ncoloh; k++)
      Model is determined by parameters x and covariates have to be         for(j=ncl,out[i][k]=0.; j<=nch; j++)
      included manually here.           out[i][k] +=in[i][j]*b[j][k];
   
      */    return out;
   }
   int i, j, d, h, k;  
   double **out, cov[NCOVMAX];  
   double **newm;  /************* Higher Matrix Product ***************/
   
   /* Hstepm could be zero and should return the unit matrix */  double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
   for (i=1;i<=nlstate+ndeath;i++)  {
     for (j=1;j<=nlstate+ndeath;j++){    /* Computes the transition matrix starting at age 'age' over
       oldm[i][j]=(i==j ? 1.0 : 0.0);       'nhstepm*hstepm*stepm' months (i.e. until
       po[i][j][0]=(i==j ? 1.0 : 0.0);       age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
     }       nhstepm*hstepm matrices.
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */       Output is stored in matrix po[i][j][h] for h every 'hstepm' step
   for(h=1; h <=nhstepm; h++){       (typically every 2 years instead of every month which is too big
     for(d=1; d <=hstepm; d++){       for the memory).
       newm=savm;       Model is determined by parameters x and covariates have to be
       /* Covariates have to be included here again */       included manually here.
       cov[1]=1.;  
       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;       */
       for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];  
       for (k=1; k<=cptcovage;k++)    int i, j, d, h, k;
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];    double **out, cov[NCOVMAX];
       for (k=1; k<=cptcovprod;k++)    double **newm;
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];  
     /* Hstepm could be zero and should return the unit matrix */
     for (i=1;i<=nlstate+ndeath;i++)
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/      for (j=1;j<=nlstate+ndeath;j++){
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/        oldm[i][j]=(i==j ? 1.0 : 0.0);
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,         po[i][j][0]=(i==j ? 1.0 : 0.0);
                    pmij(pmmij,cov,ncovmodel,x,nlstate));      }
       savm=oldm;    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
       oldm=newm;    for(h=1; h <=nhstepm; h++){
     }      for(d=1; d <=hstepm; d++){
     for(i=1; i<=nlstate+ndeath; i++)        newm=savm;
       for(j=1;j<=nlstate+ndeath;j++) {        /* Covariates have to be included here again */
         po[i][j][h]=newm[i][j];        cov[1]=1.;
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);        cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
          */        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
       }        for (k=1; k<=cptcovage;k++)
   } /* end h */          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
   return po;        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]]];
   
   
 /*************** log-likelihood *************/        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 double func( double *x)        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 {        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
   int i, ii, j, k, mi, d, kk;                     pmij(pmmij,cov,ncovmodel,x,nlstate));
   double l, ll[NLSTATEMAX], cov[NCOVMAX];        savm=oldm;
   double **out;        oldm=newm;
   double sw; /* Sum of weights */      }
   double lli; /* Individual log likelihood */      for(i=1; i<=nlstate+ndeath; i++)
   int s1, s2;        for(j=1;j<=nlstate+ndeath;j++) {
   double bbh, survp;          po[i][j][h]=newm[i][j];
   long ipmx;          /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
   /*extern weight */           */
   /* We are differentiating ll according to initial status */        }
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/    } /* end h */
   /*for(i=1;i<imx;i++)     return po;
     printf(" %d\n",s[4][i]);  }
   */  
   cov[1]=1.;  
   /*************** log-likelihood *************/
   for(k=1; k<=nlstate; k++) ll[k]=0.;  double func( double *x)
   {
   if(mle==1){    int i, ii, j, k, mi, d, kk;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){    double l, ll[NLSTATEMAX], cov[NCOVMAX];
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];    double **out;
       for(mi=1; mi<= wav[i]-1; mi++){    double sw; /* Sum of weights */
         for (ii=1;ii<=nlstate+ndeath;ii++)    double lli; /* Individual log likelihood */
           for (j=1;j<=nlstate+ndeath;j++){    int s1, s2;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    double bbh, survp;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    long ipmx;
           }    /*extern weight */
         for(d=0; d<dh[mi][i]; d++){    /* We are differentiating ll according to initial status */
           newm=savm;    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    /*for(i=1;i<imx;i++)
           for (kk=1; kk<=cptcovage;kk++) {      printf(" %d\n",s[4][i]);
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    */
           }    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;    if(mle==1){
         } /* end mult */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
               for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */        for(mi=1; mi<= wav[i]-1; mi++){
         /* But now since version 0.9 we anticipate for bias at large stepm.          for (ii=1;ii<=nlstate+ndeath;ii++)
          * If stepm is larger than one month (smallest stepm) and if the exact delay             for (j=1;j<=nlstate+ndeath;j++){
          * (in months) between two waves is not a multiple of stepm, we rounded to               oldm[ii][j]=(ii==j ? 1.0 : 0.0);
          * the nearest (and in case of equal distance, to the lowest) interval but now              savm[ii][j]=(ii==j ? 1.0 : 0.0);
          * we keep into memory the bias bh[mi][i] and also the previous matrix product            }
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the          for(d=0; d<dh[mi][i]; d++){
          * probability in order to take into account the bias as a fraction of the way            newm=savm;
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
          * -stepm/2 to stepm/2 .            for (kk=1; kk<=cptcovage;kk++) {
          * For stepm=1 the results are the same as for previous versions of Imach.              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
          * For stepm > 1 the results are less biased than in previous versions.             }
          */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         s1=s[mw[mi][i]][i];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         s2=s[mw[mi+1][i]][i];            savm=oldm;
         bbh=(double)bh[mi][i]/(double)stepm;             oldm=newm;
         /* bias bh is positive if real duration          } /* end mult */
          * is higher than the multiple of stepm and negative otherwise.       
          */          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/          /* But now since version 0.9 we anticipate for bias at large stepm.
         if( s2 > nlstate){            * If stepm is larger than one month (smallest stepm) and if the exact delay
           /* i.e. if s2 is a death state and if the date of death is known            * (in months) between two waves is not a multiple of stepm, we rounded to
              then the contribution to the likelihood is the probability to            * the nearest (and in case of equal distance, to the lowest) interval but now
              die between last step unit time and current  step unit time,            * we keep into memory the bias bh[mi][i] and also the previous matrix product
              which is also equal to probability to die before dh            * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
              minus probability to die before dh-stepm .            * probability in order to take into account the bias as a fraction of the way
              In version up to 0.92 likelihood was computed           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
         as if date of death was unknown. Death was treated as any other           * -stepm/2 to stepm/2 .
         health state: the date of the interview describes the actual state           * For stepm=1 the results are the same as for previous versions of Imach.
         and not the date of a change in health state. The former idea was           * For stepm > 1 the results are less biased than in previous versions.
         to consider that at each interview the state was recorded           */
         (healthy, disable or death) and IMaCh was corrected; but when we          s1=s[mw[mi][i]][i];
         introduced the exact date of death then we should have modified          s2=s[mw[mi+1][i]][i];
         the contribution of an exact death to the likelihood. This new          bbh=(double)bh[mi][i]/(double)stepm;
         contribution is smaller and very dependent of the step unit          /* bias bh is positive if real duration
         stepm. It is no more the probability to die between last interview           * is higher than the multiple of stepm and negative otherwise.
         and month of death but the probability to survive from last           */
         interview up to one month before death multiplied by the          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
         probability to die within a month. Thanks to Chris          if( s2 > nlstate){
         Jackson for correcting this bug.  Former versions increased            /* i.e. if s2 is a death state and if the date of death is known
         mortality artificially. The bad side is that we add another loop               then the contribution to the likelihood is the probability to
         which slows down the processing. The difference can be up to 10%               die between last step unit time and current  step unit time,
         lower mortality.               which is also equal to probability to die before dh
           */               minus probability to die before dh-stepm .
           lli=log(out[s1][s2] - savm[s1][s2]);               In version up to 0.92 likelihood was computed
           as if date of death was unknown. Death was treated as any other
           health state: the date of the interview describes the actual state
         } else if  (s2==-2) {          and not the date of a change in health state. The former idea was
           for (j=1,survp=0. ; j<=nlstate; j++)           to consider that at each interview the state was recorded
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          (healthy, disable or death) and IMaCh was corrected; but when we
           /*survp += out[s1][j]; */          introduced the exact date of death then we should have modified
           lli= log(survp);          the contribution of an exact death to the likelihood. This new
         }          contribution is smaller and very dependent of the step unit
                   stepm. It is no more the probability to die between last interview
         else if  (s2==-4) {           and month of death but the probability to survive from last
           for (j=3,survp=0. ; j<=nlstate; j++)            interview up to one month before death multiplied by the
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          probability to die within a month. Thanks to Chris
           lli= log(survp);           Jackson for correcting this bug.  Former versions increased
         }           mortality artificially. The bad side is that we add another loop
           which slows down the processing. The difference can be up to 10%
         else if  (s2==-5) {           lower mortality.
           for (j=1,survp=0. ; j<=2; j++)              */
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];            lli=log(out[s1][s2] - savm[s1][s2]);
           lli= log(survp);   
         }   
                   } else if  (s2==-2) {
         else{            for (j=1,survp=0. ; j<=nlstate; j++)
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */              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 */            /*survp += out[s1][j]; */
         }             lli= log(survp);
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/          }
         /*if(lli ==000.0)*/         
         /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */          else if  (s2==-4) {
         ipmx +=1;            for (j=3,survp=0. ; j<=nlstate; j++)  
         sw += weight[i];              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            lli= log(survp);
       } /* end of wave */          }
     } /* end of individual */  
   }  else if(mle==2){          else if  (s2==-5) {
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){            for (j=1,survp=0. ; j<=2; j++)  
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
       for(mi=1; mi<= wav[i]-1; mi++){            lli= log(survp);
         for (ii=1;ii<=nlstate+ndeath;ii++)          }
           for (j=1;j<=nlstate+ndeath;j++){         
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          else{
             savm[ii][j]=(ii==j ? 1.0 : 0.0);            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
           }            /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
         for(d=0; d<=dh[mi][i]; d++){          }
           newm=savm;          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          /*if(lli ==000.0)*/
           for (kk=1; kk<=cptcovage;kk++) {          /*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); */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          ipmx +=1;
           }          sw += weight[i];
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));        } /* end of wave */
           savm=oldm;      } /* end of individual */
           oldm=newm;    }  else if(mle==2){
         } /* end mult */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
               for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         s1=s[mw[mi][i]][i];        for(mi=1; mi<= wav[i]-1; mi++){
         s2=s[mw[mi+1][i]][i];          for (ii=1;ii<=nlstate+ndeath;ii++)
         bbh=(double)bh[mi][i]/(double)stepm;             for (j=1;j<=nlstate+ndeath;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 */              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++){
       } /* end of wave */            newm=savm;
     } /* end of individual */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   }  else if(mle==3){  /* exponential inter-extrapolation */            for (kk=1; kk<=cptcovage;kk++) {
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            }
       for(mi=1; mi<= wav[i]-1; mi++){            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         for (ii=1;ii<=nlstate+ndeath;ii++)                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           for (j=1;j<=nlstate+ndeath;j++){            savm=oldm;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);            oldm=newm;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          } /* end mult */
           }       
         for(d=0; d<dh[mi][i]; d++){          s1=s[mw[mi][i]][i];
           newm=savm;          s2=s[mw[mi+1][i]][i];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          bbh=(double)bh[mi][i]/(double)stepm;
           for (kk=1; kk<=cptcovage;kk++) {          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[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          ipmx +=1;
           }          sw += weight[i];
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));        } /* end of wave */
           savm=oldm;      } /* end of individual */
           oldm=newm;    }  else if(mle==3){  /* exponential inter-extrapolation */
         } /* end mult */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
               for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         s1=s[mw[mi][i]][i];        for(mi=1; mi<= wav[i]-1; mi++){
         s2=s[mw[mi+1][i]][i];          for (ii=1;ii<=nlstate+ndeath;ii++)
         bbh=(double)bh[mi][i]/(double)stepm;             for (j=1;j<=nlstate+ndeath;j++){
         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 */              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++){
       } /* end of wave */            newm=savm;
     } /* end of individual */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   }else if (mle==4){  /* ml=4 no inter-extrapolation */            for (kk=1; kk<=cptcovage;kk++) {
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            }
       for(mi=1; mi<= wav[i]-1; mi++){            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         for (ii=1;ii<=nlstate+ndeath;ii++)                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           for (j=1;j<=nlstate+ndeath;j++){            savm=oldm;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);            oldm=newm;
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          } /* end mult */
           }       
         for(d=0; d<dh[mi][i]; d++){          s1=s[mw[mi][i]][i];
           newm=savm;          s2=s[mw[mi+1][i]][i];
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          bbh=(double)bh[mi][i]/(double)stepm;
           for (kk=1; kk<=cptcovage;kk++) {          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 */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          ipmx +=1;
           }          sw += weight[i];
                   ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,        } /* end of wave */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));      } /* end of individual */
           savm=oldm;    }else if (mle==4){  /* ml=4 no inter-extrapolation */
           oldm=newm;      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         } /* end mult */        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
               for(mi=1; mi<= wav[i]-1; mi++){
         s1=s[mw[mi][i]][i];          for (ii=1;ii<=nlstate+ndeath;ii++)
         s2=s[mw[mi+1][i]][i];            for (j=1;j<=nlstate+ndeath;j++){
         if( s2 > nlstate){               oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           lli=log(out[s1][s2] - savm[s1][s2]);              savm[ii][j]=(ii==j ? 1.0 : 0.0);
         }else{            }
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */          for(d=0; d<dh[mi][i]; d++){
         }            newm=savm;
         ipmx +=1;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         sw += weight[i];            for (kk=1; kk<=cptcovage;kk++) {
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */            }
       } /* end of wave */         
     } /* end of individual */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){            savm=oldm;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            oldm=newm;
       for(mi=1; mi<= wav[i]-1; mi++){          } /* end mult */
         for (ii=1;ii<=nlstate+ndeath;ii++)       
           for (j=1;j<=nlstate+ndeath;j++){          s1=s[mw[mi][i]][i];
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          s2=s[mw[mi+1][i]][i];
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          if( s2 > nlstate){
           }            lli=log(out[s1][s2] - savm[s1][s2]);
         for(d=0; d<dh[mi][i]; d++){          }else{
           newm=savm;            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          }
           for (kk=1; kk<=cptcovage;kk++) {          ipmx +=1;
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          sw += weight[i];
           }          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,        } /* end of wave */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));      } /* end of individual */
           savm=oldm;    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
           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]); */         
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
   return -l;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 }            savm=oldm;
             oldm=newm;
 /*************** log-likelihood *************/          } /* end mult */
 double funcone( double *x)       
 {          s1=s[mw[mi][i]][i];
   /* Same as likeli but slower because of a lot of printf and if */          s2=s[mw[mi+1][i]][i];
   int i, ii, j, k, mi, d, kk;          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   double l, ll[NLSTATEMAX], cov[NCOVMAX];          ipmx +=1;
   double **out;          sw += weight[i];
   double lli; /* Individual log likelihood */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   double llt;          /*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]);*/
   int s1, s2;        } /* end of wave */
   double bbh, survp;      } /* end of individual */
   /*extern weight */    } /* End of if */
   /* We are differentiating ll according to initial status */    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   /*for(i=1;i<imx;i++)     l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
     printf(" %d\n",s[4][i]);    return -l;
   */  }
   cov[1]=1.;  
   /*************** log-likelihood *************/
   for(k=1; k<=nlstate; k++) ll[k]=0.;  double funcone( double *x)
   {
   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]);
         }    */
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    cov[1]=1.;
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));  
         savm=oldm;    for(k=1; k<=nlstate; k++) ll[k]=0.;
         oldm=newm;  
       } /* end mult */    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
             for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       s1=s[mw[mi][i]][i];      for(mi=1; mi<= wav[i]-1; mi++){
       s2=s[mw[mi+1][i]][i];        for (ii=1;ii<=nlstate+ndeath;ii++)
       bbh=(double)bh[mi][i]/(double)stepm;           for (j=1;j<=nlstate+ndeath;j++){
       /* bias is positive if real duration            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        * is higher than the multiple of stepm and negative otherwise.            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        */          }
       if( s2 > nlstate && (mle <5) ){  /* Jackson */        for(d=0; d<dh[mi][i]; d++){
         lli=log(out[s1][s2] - savm[s1][s2]);          newm=savm;
       } else if  (s2==-2) {          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         for (j=1,survp=0. ; j<=nlstate; j++)           for (kk=1; kk<=cptcovage;kk++) {
           survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         lli= log(survp);          }
       }else if (mle==1){          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
       } else if(mle==2){          savm=oldm;
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */          oldm=newm;
       } else if(mle==3){  /* exponential inter-extrapolation */        } /* end mult */
         lli= (savm[s1][s2]>(double)1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */       
       } else if (mle==4){  /* mle=4 no inter-extrapolation */        s1=s[mw[mi][i]][i];
         lli=log(out[s1][s2]); /* Original formula */        s2=s[mw[mi+1][i]][i];
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */        bbh=(double)bh[mi][i]/(double)stepm;
         lli=log(out[s1][s2]); /* Original formula */        /* bias is positive if real duration
       } /* End of if */         * is higher than the multiple of stepm and negative otherwise.
       ipmx +=1;         */
       sw += weight[i];        if( s2 > nlstate && (mle <5) ){  /* Jackson */
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          lli=log(out[s1][s2] - savm[s1][s2]);
 /*       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]); */        } else if  (s2==-2) {
       if(globpr){          for (j=1,survp=0. ; j<=nlstate; j++)
         fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
  %11.6f %11.6f %11.6f ", \          lli= log(survp);
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],        }else if (mle==1){
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){        } else if(mle==2){
           llt +=ll[k]*gipmx/gsw;          lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);        } 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 */
         fprintf(ficresilk," %10.6f\n", -llt);        } else if (mle==4){  /* mle=4 no inter-extrapolation */
       }          lli=log(out[s1][s2]); /* Original formula */
     } /* end of wave */        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
   } /* end of individual */          lli=log(out[s1][s2]); /* Original formula */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];        } /* End of if */
   /* 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];
   if(globpr==0){ /* First time we count the contributions and weights */        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
     gipmx=ipmx;  /*       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]); */
     gsw=sw;        if(globpr){
   }          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
   return -l;   %11.6f %11.6f %11.6f ", \
 }                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
           for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 /*************** function likelione ***********/            llt +=ll[k]*gipmx/gsw;
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 {          }
   /* This routine should help understanding what is done with           fprintf(ficresilk," %10.6f\n", -llt);
      the selection of individuals/waves and        }
      to check the exact contribution to the likelihood.      } /* end of wave */
      Plotting could be done.    } /* end of individual */
    */    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
   int k;    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
   if(*globpri !=0){ /* Just counts and sums, no printings */    if(globpr==0){ /* First time we count the contributions and weights */
     strcpy(fileresilk,"ilk");       gipmx=ipmx;
     strcat(fileresilk,fileres);      gsw=sw;
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {    }
       printf("Problem with resultfile: %s\n", fileresilk);    return -l;
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);  }
     }  
     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");  
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");  /*************** function likelione ***********/
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
     for(k=1; k<=nlstate; k++)   {
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);    /* This routine should help understanding what is done with
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");       the selection of individuals/waves and
   }       to check the exact contribution to the likelihood.
        Plotting could be done.
   *fretone=(*funcone)(p);     */
   if(*globpri !=0){    int k;
     fclose(ficresilk);  
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));    if(*globpri !=0){ /* Just counts and sums, no printings */
     fflush(fichtm);       strcpy(fileresilk,"ilk");
   }       strcat(fileresilk,fileres);
   return;      if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 }        printf("Problem with resultfile: %s\n", fileresilk);
         fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
       }
 /*********** Maximum Likelihood Estimation ***************/      fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
       fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 {      for(k=1; k<=nlstate; k++)
   int i,j, iter;        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
   double **xi;      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
   double fret;    }
   double fretone; /* Only one call to likelihood */  
   /*  char filerespow[FILENAMELENGTH];*/    *fretone=(*funcone)(p);
   xi=matrix(1,npar,1,npar);    if(*globpri !=0){
   for (i=1;i<=npar;i++)      fclose(ficresilk);
     for (j=1;j<=npar;j++)      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
       xi[i][j]=(i==j ? 1.0 : 0.0);      fflush(fichtm);
   printf("Powell\n");  fprintf(ficlog,"Powell\n");    }
   strcpy(filerespow,"pow");     return;
   strcat(filerespow,fileres);  }
   if((ficrespow=fopen(filerespow,"w"))==NULL) {  
     printf("Problem with resultfile: %s\n", filerespow);  
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);  /*********** Maximum Likelihood Estimation ***************/
   }  
   fprintf(ficrespow,"# Powell\n# iter -2*LL");  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   for (i=1;i<=nlstate;i++)  {
     for(j=1;j<=nlstate+ndeath;j++)    int i,j, iter;
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);    double **xi;
   fprintf(ficrespow,"\n");    double fret;
     double fretone; /* Only one call to likelihood */
   powell(p,xi,npar,ftol,&iter,&fret,func);    /*  char filerespow[FILENAMELENGTH];*/
     xi=matrix(1,npar,1,npar);
   free_matrix(xi,1,npar,1,npar);    for (i=1;i<=npar;i++)
   fclose(ficrespow);      for (j=1;j<=npar;j++)
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));        xi[i][j]=(i==j ? 1.0 : 0.0);
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));    printf("Powell\n");  fprintf(ficlog,"Powell\n");
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));    strcpy(filerespow,"pow");
     strcat(filerespow,fileres);
 }    if((ficrespow=fopen(filerespow,"w"))==NULL) {
       printf("Problem with resultfile: %s\n", filerespow);
 /**** Computes Hessian and covariance matrix ***/      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))    }
 {    fprintf(ficrespow,"# Powell\n# iter -2*LL");
   double  **a,**y,*x,pd;    for (i=1;i<=nlstate;i++)
   double **hess;      for(j=1;j<=nlstate+ndeath;j++)
   int i, j,jk;        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   int *indx;    fprintf(ficrespow,"\n");
   
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);    powell(p,xi,npar,ftol,&iter,&fret,func);
   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);  
   void lubksb(double **a, int npar, int *indx, double b[]) ;    free_matrix(xi,1,npar,1,npar);
   void ludcmp(double **a, int npar, int *indx, double *d) ;    fclose(ficrespow);
   double gompertz(double p[]);    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
   hess=matrix(1,npar,1,npar);    fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
     fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
   printf("\nCalculation of the hessian matrix. Wait...\n");  
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");  }
   for (i=1;i<=npar;i++){  
     printf("%d",i);fflush(stdout);  /**** Computes Hessian and covariance matrix ***/
     fprintf(ficlog,"%d",i);fflush(ficlog);  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
      {
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);    double  **a,**y,*x,pd;
         double **hess;
     /*  printf(" %f ",p[i]);    int i, j,jk;
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/    int *indx;
   }  
       double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
   for (i=1;i<=npar;i++) {    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
     for (j=1;j<=npar;j++)  {    void lubksb(double **a, int npar, int *indx, double b[]) ;
       if (j>i) {     void ludcmp(double **a, int npar, int *indx, double *d) ;
         printf(".%d%d",i,j);fflush(stdout);    double gompertz(double p[]);
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);    hess=matrix(1,npar,1,npar);
         hess[i][j]=hessij(p,delti,i,j,func,npar);  
             printf("\nCalculation of the hessian matrix. Wait...\n");
         hess[j][i]=hess[i][j];        fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
         /*printf(" %lf ",hess[i][j]);*/    for (i=1;i<=npar;i++){
       }      printf("%d",i);fflush(stdout);
     }      fprintf(ficlog,"%d",i);fflush(ficlog);
   }     
   printf("\n");       hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
   fprintf(ficlog,"\n");     
       /*  printf(" %f ",p[i]);
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");          printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");    }
      
   a=matrix(1,npar,1,npar);    for (i=1;i<=npar;i++) {
   y=matrix(1,npar,1,npar);      for (j=1;j<=npar;j++)  {
   x=vector(1,npar);        if (j>i) {
   indx=ivector(1,npar);          printf(".%d%d",i,j);fflush(stdout);
   for (i=1;i<=npar;i++)          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];          hess[i][j]=hessij(p,delti,i,j,func,npar);
   ludcmp(a,npar,indx,&pd);         
           hess[j][i]=hess[i][j];    
   for (j=1;j<=npar;j++) {          /*printf(" %lf ",hess[i][j]);*/
     for (i=1;i<=npar;i++) x[i]=0;        }
     x[j]=1;      }
     lubksb(a,npar,indx,x);    }
     for (i=1;i<=npar;i++){     printf("\n");
       matcov[i][j]=x[i];    fprintf(ficlog,"\n");
     }  
   }    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
     fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
   printf("\n#Hessian matrix#\n");   
   fprintf(ficlog,"\n#Hessian matrix#\n");    a=matrix(1,npar,1,npar);
   for (i=1;i<=npar;i++) {     y=matrix(1,npar,1,npar);
     for (j=1;j<=npar;j++) {     x=vector(1,npar);
       printf("%.3e ",hess[i][j]);    indx=ivector(1,npar);
       fprintf(ficlog,"%.3e ",hess[i][j]);    for (i=1;i<=npar;i++)
     }      for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
     printf("\n");    ludcmp(a,npar,indx,&pd);
     fprintf(ficlog,"\n");  
   }    for (j=1;j<=npar;j++) {
       for (i=1;i<=npar;i++) x[i]=0;
   /* Recompute Inverse */      x[j]=1;
   for (i=1;i<=npar;i++)      lubksb(a,npar,indx,x);
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];      for (i=1;i<=npar;i++){
   ludcmp(a,npar,indx,&pd);        matcov[i][j]=x[i];
       }
   /*  printf("\n#Hessian matrix recomputed#\n");    }
   
   for (j=1;j<=npar;j++) {    printf("\n#Hessian matrix#\n");
     for (i=1;i<=npar;i++) x[i]=0;    fprintf(ficlog,"\n#Hessian matrix#\n");
     x[j]=1;    for (i=1;i<=npar;i++) {
     lubksb(a,npar,indx,x);      for (j=1;j<=npar;j++) {
     for (i=1;i<=npar;i++){         printf("%.3e ",hess[i][j]);
       y[i][j]=x[i];        fprintf(ficlog,"%.3e ",hess[i][j]);
       printf("%.3e ",y[i][j]);      }
       fprintf(ficlog,"%.3e ",y[i][j]);      printf("\n");
     }      fprintf(ficlog,"\n");
     printf("\n");    }
     fprintf(ficlog,"\n");  
   }    /* Recompute Inverse */
   */    for (i=1;i<=npar;i++)
       for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
   free_matrix(a,1,npar,1,npar);    ludcmp(a,npar,indx,&pd);
   free_matrix(y,1,npar,1,npar);  
   free_vector(x,1,npar);    /*  printf("\n#Hessian matrix recomputed#\n");
   free_ivector(indx,1,npar);  
   free_matrix(hess,1,npar,1,npar);    for (j=1;j<=npar;j++) {
       for (i=1;i<=npar;i++) x[i]=0;
       x[j]=1;
 }      lubksb(a,npar,indx,x);
       for (i=1;i<=npar;i++){
 /*************** hessian matrix ****************/        y[i][j]=x[i];
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)        printf("%.3e ",y[i][j]);
 {        fprintf(ficlog,"%.3e ",y[i][j]);
   int i;      }
   int l=1, lmax=20;      printf("\n");
   double k1,k2;      fprintf(ficlog,"\n");
   double p2[NPARMAX+1];    }
   double res;    */
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;  
   double fx;    free_matrix(a,1,npar,1,npar);
   int k=0,kmax=10;    free_matrix(y,1,npar,1,npar);
   double l1;    free_vector(x,1,npar);
     free_ivector(indx,1,npar);
   fx=func(x);    free_matrix(hess,1,npar,1,npar);
   for (i=1;i<=npar;i++) p2[i]=x[i];  
   for(l=0 ; l <=lmax; l++){  
     l1=pow(10,l);  }
     delts=delt;  
     for(k=1 ; k <kmax; k=k+1){  /*************** hessian matrix ****************/
       delt = delta*(l1*k);  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
       p2[theta]=x[theta] +delt;  {
       k1=func(p2)-fx;    int i;
       p2[theta]=x[theta]-delt;    int l=1, lmax=20;
       k2=func(p2)-fx;    double k1,k2;
       /*res= (k1-2.0*fx+k2)/delt/delt; */    double p2[NPARMAX+1];
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */    double res;
           double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 #ifdef DEBUG    double fx;
       printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);    int k=0,kmax=10;
       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);    double l1;
 #endif  
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */    fx=func(x);
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){    for (i=1;i<=npar;i++) p2[i]=x[i];
         k=kmax;    for(l=0 ; l <=lmax; l++){
       }      l1=pow(10,l);
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */      delts=delt;
         k=kmax; l=lmax*10.;      for(k=1 ; k <kmax; k=k+1){
       }        delt = delta*(l1*k);
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){         p2[theta]=x[theta] +delt;
         delts=delt;        k1=func(p2)-fx;
       }        p2[theta]=x[theta]-delt;
     }        k2=func(p2)-fx;
   }        /*res= (k1-2.0*fx+k2)/delt/delt; */
   delti[theta]=delts;        res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
   return res;        
     #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);
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)  #endif
 {        /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
   int i;        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
   int l=1, l1, lmax=20;          k=kmax;
   double k1,k2,k3,k4,res,fx;        }
   double p2[NPARMAX+1];        else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
   int k;          k=kmax; l=lmax*10.;
         }
   fx=func(x);        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
   for (k=1; k<=2; k++) {          delts=delt;
     for (i=1;i<=npar;i++) p2[i]=x[i];        }
     p2[thetai]=x[thetai]+delti[thetai]/k;      }
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    }
     k1=func(p2)-fx;    delti[theta]=delts;
       return res;
     p2[thetai]=x[thetai]+delti[thetai]/k;   
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;  }
     k2=func(p2)-fx;  
     double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
     p2[thetai]=x[thetai]-delti[thetai]/k;  {
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    int i;
     k3=func(p2)-fx;    int l=1, l1, lmax=20;
       double k1,k2,k3,k4,res,fx;
     p2[thetai]=x[thetai]-delti[thetai]/k;    double p2[NPARMAX+1];
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    int k;
     k4=func(p2)-fx;  
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */    fx=func(x);
 #ifdef DEBUG    for (k=1; k<=2; k++) {
     printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);      for (i=1;i<=npar;i++) p2[i]=x[i];
     fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);      p2[thetai]=x[thetai]+delti[thetai]/k;
 #endif      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   }      k1=func(p2)-fx;
   return res;   
 }      p2[thetai]=x[thetai]+delti[thetai]/k;
       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 /************** Inverse of matrix **************/      k2=func(p2)-fx;
 void ludcmp(double **a, int n, int *indx, double *d)    
 {       p2[thetai]=x[thetai]-delti[thetai]/k;
   int i,imax,j,k;       p2[thetaj]=x[thetaj]+delti[thetaj]/k;
   double big,dum,sum,temp;       k3=func(p2)-fx;
   double *vv;    
        p2[thetai]=x[thetai]-delti[thetai]/k;
   vv=vector(1,n);       p2[thetaj]=x[thetaj]-delti[thetaj]/k;
   *d=1.0;       k4=func(p2)-fx;
   for (i=1;i<=n;i++) {       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
     big=0.0;   #ifdef DEBUG
     for (j=1;j<=n;j++)       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
       if ((temp=fabs(a[i][j])) > big) big=temp;       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);
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");   #endif
     vv[i]=1.0/big;     }
   }     return res;
   for (j=1;j<=n;j++) {   }
     for (i=1;i<j;i++) {   
       sum=a[i][j];   /************** Inverse of matrix **************/
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];   void ludcmp(double **a, int n, int *indx, double *d)
       a[i][j]=sum;   {
     }     int i,imax,j,k;
     big=0.0;     double big,dum,sum,temp;
     for (i=j;i<=n;i++) {     double *vv;
       sum=a[i][j];    
       for (k=1;k<j;k++)     vv=vector(1,n);
         sum -= a[i][k]*a[k][j];     *d=1.0;
       a[i][j]=sum;     for (i=1;i<=n;i++) {
       if ( (dum=vv[i]*fabs(sum)) >= big) {       big=0.0;
         big=dum;       for (j=1;j<=n;j++)
         imax=i;         if ((temp=fabs(a[i][j])) > big) big=temp;
       }       if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
     }       vv[i]=1.0/big;
     if (j != imax) {     }
       for (k=1;k<=n;k++) {     for (j=1;j<=n;j++) {
         dum=a[imax][k];       for (i=1;i<j;i++) {
         a[imax][k]=a[j][k];         sum=a[i][j];
         a[j][k]=dum;         for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
       }         a[i][j]=sum;
       *d = -(*d);       }
       vv[imax]=vv[j];       big=0.0;
     }       for (i=j;i<=n;i++) {
     indx[j]=imax;         sum=a[i][j];
     if (a[j][j] == 0.0) a[j][j]=TINY;         for (k=1;k<j;k++)
     if (j != n) {           sum -= a[i][k]*a[k][j];
       dum=1.0/(a[j][j]);         a[i][j]=sum;
       for (i=j+1;i<=n;i++) a[i][j] *= dum;         if ( (dum=vv[i]*fabs(sum)) >= big) {
     }           big=dum;
   }           imax=i;
   free_vector(vv,1,n);  /* Doesn't work */        }
 ;      }
 }       if (j != imax) {
         for (k=1;k<=n;k++) {
 void lubksb(double **a, int n, int *indx, double b[])           dum=a[imax][k];
 {           a[imax][k]=a[j][k];
   int i,ii=0,ip,j;           a[j][k]=dum;
   double sum;         }
          *d = -(*d);
   for (i=1;i<=n;i++) {         vv[imax]=vv[j];
     ip=indx[i];       }
     sum=b[ip];       indx[j]=imax;
     b[ip]=b[i];       if (a[j][j] == 0.0) a[j][j]=TINY;
     if (ii)       if (j != n) {
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];         dum=1.0/(a[j][j]);
     else if (sum) ii=i;         for (i=j+1;i<=n;i++) a[i][j] *= dum;
     b[i]=sum;       }
   }     }
   for (i=n;i>=1;i--) {     free_vector(vv,1,n);  /* Doesn't work */
     sum=b[i];   ;
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];   }
     b[i]=sum/a[i][i];   
   }   void lubksb(double **a, int n, int *indx, double b[])
 }   {
     int i,ii=0,ip,j;
 void pstamp(FILE *fichier)    double sum;
 {   
   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);    for (i=1;i<=n;i++) {
 }      ip=indx[i];
       sum=b[ip];
 /************ Frequencies ********************/      b[ip]=b[i];
 void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])      if (ii)
 {  /* Some frequencies */        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
         else if (sum) ii=i;
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;      b[i]=sum;
   int first;    }
   double ***freq; /* Frequencies */    for (i=n;i>=1;i--) {
   double *pp, **prop;      sum=b[i];
   double pos,posprop, k2, dateintsum=0,k2cpt=0;      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
   char fileresp[FILENAMELENGTH];      b[i]=sum/a[i][i];
       }
   pp=vector(1,nlstate);  }
   prop=matrix(1,nlstate,iagemin,iagemax+3);  
   strcpy(fileresp,"p");  void pstamp(FILE *fichier)
   strcat(fileresp,fileres);  {
   if((ficresp=fopen(fileresp,"w"))==NULL) {    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
     printf("Problem with prevalence resultfile: %s\n", fileresp);  }
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);  
     exit(0);  /************ Frequencies ********************/
   }  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);  {  /* Some frequencies */
   j1=0;   
       int i, m, jk, k1,i1, j1, bool, z1,z2,j;
   j=cptcoveff;    int first;
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    double ***freq; /* Frequencies */
     double *pp, **prop;
   first=1;    double pos,posprop, k2, dateintsum=0,k2cpt=0;
     char fileresp[FILENAMELENGTH];
   for(k1=1; k1<=j;k1++){   
     for(i1=1; i1<=ncodemax[k1];i1++){    pp=vector(1,nlstate);
       j1++;    prop=matrix(1,nlstate,iagemin,iagemax+3);
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    strcpy(fileresp,"p");
         scanf("%d", i);*/    strcat(fileresp,fileres);
       for (i=-5; i<=nlstate+ndeath; i++)      if((ficresp=fopen(fileresp,"w"))==NULL) {
         for (jk=-5; jk<=nlstate+ndeath; jk++)        printf("Problem with prevalence resultfile: %s\n", fileresp);
           for(m=iagemin; m <= iagemax+3; m++)      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
             freq[i][jk][m]=0;      exit(0);
     }
     for (i=1; i<=nlstate; i++)      freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
       for(m=iagemin; m <= iagemax+3; m++)    j1=0;
         prop[i][m]=0;   
           j=cptcoveff;
       dateintsum=0;    if (cptcovn<1) {j=1;ncodemax[1]=1;}
       k2cpt=0;  
       for (i=1; i<=imx; i++) {    first=1;
         bool=1;  
         if  (cptcovn>0) {    for(k1=1; k1<=j;k1++){
           for (z1=1; z1<=cptcoveff; z1++)       for(i1=1; i1<=ncodemax[k1];i1++){
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])         j1++;
               bool=0;        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
         }          scanf("%d", i);*/
         if (bool==1){        for (i=-5; i<=nlstate+ndeath; i++)  
           for(m=firstpass; m<=lastpass; m++){          for (jk=-5; jk<=nlstate+ndeath; jk++)  
             k2=anint[m][i]+(mint[m][i]/12.);            for(m=iagemin; m <= iagemax+3; m++)
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/              freq[i][jk][m]=0;
               if(agev[m][i]==0) agev[m][i]=iagemax+1;  
               if(agev[m][i]==1) agev[m][i]=iagemax+2;      for (i=1; i<=nlstate; i++)  
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];        for(m=iagemin; m <= iagemax+3; m++)
               if (m<lastpass) {          prop[i][m]=0;
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];       
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];        dateintsum=0;
               }        k2cpt=0;
                       for (i=1; i<=imx; i++) {
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {          bool=1;
                 dateintsum=dateintsum+k2;          if  (cptcovn>0) {
                 k2cpt++;            for (z1=1; z1<=cptcoveff; z1++)
               }              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
               /*}*/                bool=0;
           }          }
         }          if (bool==1){
       }            for(m=firstpass; m<=lastpass; m++){
                      k2=anint[m][i]+(mint[m][i]/12.);
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
       pstamp(ficresp);                if(agev[m][i]==0) agev[m][i]=iagemax+1;
       if  (cptcovn>0) {                if(agev[m][i]==1) agev[m][i]=iagemax+2;
         fprintf(ficresp, "\n#********** Variable ");                 if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);                if (m<lastpass) {
         fprintf(ficresp, "**********\n#");                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
       }                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
       for(i=1; i<=nlstate;i++)                 }
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);               
       fprintf(ficresp, "\n");                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                         dateintsum=dateintsum+k2;
       for(i=iagemin; i <= iagemax+3; i++){                  k2cpt++;
         if(i==iagemax+3){                }
           fprintf(ficlog,"Total");                /*}*/
         }else{            }
           if(first==1){          }
             first=0;        }
             printf("See log file for details...\n");         
           }        /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
           fprintf(ficlog,"Age %d", i);        pstamp(ficresp);
         }        if  (cptcovn>0) {
         for(jk=1; jk <=nlstate ; jk++){          fprintf(ficresp, "\n#********** Variable ");
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             pp[jk] += freq[jk][m][i];           fprintf(ficresp, "**********\n#");
         }        }
         for(jk=1; jk <=nlstate ; jk++){        for(i=1; i<=nlstate;i++)
           for(m=-1, pos=0; m <=0 ; m++)          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
             pos += freq[jk][m][i];        fprintf(ficresp, "\n");
           if(pp[jk]>=1.e-10){       
             if(first==1){        for(i=iagemin; i <= iagemax+3; i++){
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);          if(i==iagemax+3){
             }            fprintf(ficlog,"Total");
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);          }else{
           }else{            if(first==1){
             if(first==1)              first=0;
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);              printf("See log file for details...\n");
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);            }
           }            fprintf(ficlog,"Age %d", i);
         }          }
           for(jk=1; jk <=nlstate ; jk++){
         for(jk=1; jk <=nlstate ; jk++){            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)              pp[jk] += freq[jk][m][i];
             pp[jk] += freq[jk][m][i];          }
         }                 for(jk=1; jk <=nlstate ; jk++){
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){            for(m=-1, pos=0; m <=0 ; m++)
           pos += pp[jk];              pos += freq[jk][m][i];
           posprop += prop[jk][i];            if(pp[jk]>=1.e-10){
         }              if(first==1){
         for(jk=1; jk <=nlstate ; jk++){              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
           if(pos>=1.e-5){              }
             if(first==1)              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);            }else{
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);              if(first==1)
           }else{                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             if(first==1)              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);            }
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);          }
           }  
           if( i <= iagemax){          for(jk=1; jk <=nlstate ; jk++){
             if(pos>=1.e-5){            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);              pp[jk] += freq[jk][m][i];
               /*probs[i][jk][j1]= pp[jk]/pos;*/          }      
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
             }            pos += pp[jk];
             else            posprop += prop[jk][i];
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);          }
           }          for(jk=1; jk <=nlstate ; jk++){
         }            if(pos>=1.e-5){
                       if(first==1)
         for(jk=-1; jk <=nlstate+ndeath; jk++)                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
           for(m=-1; m <=nlstate+ndeath; m++)              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             if(freq[jk][m][i] !=0 ) {            }else{
             if(first==1)              if(first==1)
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
             }            }
         if(i <= iagemax)            if( i <= iagemax){
           fprintf(ficresp,"\n");              if(pos>=1.e-5){
         if(first==1)                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
           printf("Others in log...\n");                /*probs[i][jk][j1]= pp[jk]/pos;*/
         fprintf(ficlog,"\n");                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
       }              }
     }              else
   }                fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
   dateintmean=dateintsum/k2cpt;             }
            }
   fclose(ficresp);         
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);          for(jk=-1; jk <=nlstate+ndeath; jk++)
   free_vector(pp,1,nlstate);            for(m=-1; m <=nlstate+ndeath; m++)
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);              if(freq[jk][m][i] !=0 ) {
   /* End of Freq */              if(first==1)
 }                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 /************ Prevalence ********************/              }
 void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)          if(i <= iagemax)
 {              fprintf(ficresp,"\n");
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people          if(first==1)
      in each health status at the date of interview (if between dateprev1 and dateprev2).            printf("Others in log...\n");
      We still use firstpass and lastpass as another selection.          fprintf(ficlog,"\n");
   */        }
        }
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;    }
   double ***freq; /* Frequencies */    dateintmean=dateintsum/k2cpt;
   double *pp, **prop;   
   double pos,posprop;     fclose(ficresp);
   double  y2; /* in fractional years */    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
   int iagemin, iagemax;    free_vector(pp,1,nlstate);
     free_matrix(prop,1,nlstate,iagemin, iagemax+3);
   iagemin= (int) agemin;    /* End of Freq */
   iagemax= (int) agemax;  }
   /*pp=vector(1,nlstate);*/  
   prop=matrix(1,nlstate,iagemin,iagemax+3);   /************ Prevalence ********************/
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/  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)
   j1=0;  {  
       /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
   j=cptcoveff;       in each health status at the date of interview (if between dateprev1 and dateprev2).
   if (cptcovn<1) {j=1;ncodemax[1]=1;}       We still use firstpass and lastpass as another selection.
       */
   for(k1=1; k1<=j;k1++){   
     for(i1=1; i1<=ncodemax[k1];i1++){    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
       j1++;    double ***freq; /* Frequencies */
           double *pp, **prop;
       for (i=1; i<=nlstate; i++)      double pos,posprop;
         for(m=iagemin; m <= iagemax+3; m++)    double  y2; /* in fractional years */
           prop[i][m]=0.0;    int iagemin, iagemax;
        
       for (i=1; i<=imx; i++) { /* Each individual */    iagemin= (int) agemin;
         bool=1;    iagemax= (int) agemax;
         if  (cptcovn>0) {    /*pp=vector(1,nlstate);*/
           for (z1=1; z1<=cptcoveff; z1++)     prop=matrix(1,nlstate,iagemin,iagemax+3);
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])     /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
               bool=0;    j1=0;
         }    
         if (bool==1) {     j=cptcoveff;
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/    if (cptcovn<1) {j=1;ncodemax[1]=1;}
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */   
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */    for(k1=1; k1<=j;k1++){
               if(agev[m][i]==0) agev[m][i]=iagemax+1;      for(i1=1; i1<=ncodemax[k1];i1++){
               if(agev[m][i]==1) agev[m][i]=iagemax+2;        j1++;
               if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m);        
               if (s[m][i]>0 && s[m][i]<=nlstate) {         for (i=1; i<=nlstate; i++)  
                 /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/          for(m=iagemin; m <= iagemax+3; m++)
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];            prop[i][m]=0.0;
                 prop[s[m][i]][iagemax+3] += weight[i];        
               }         for (i=1; i<=imx; i++) { /* Each individual */
             }          bool=1;
           } /* end selection of waves */          if  (cptcovn>0) {
         }            for (z1=1; z1<=cptcoveff; z1++)
       }              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
       for(i=iagemin; i <= iagemax+3; i++){                  bool=0;
                   }
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {           if (bool==1) {
           posprop += prop[jk][i];             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 */
               if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
         for(jk=1; jk <=nlstate ; jk++){                     if(agev[m][i]==0) agev[m][i]=iagemax+1;
           if( i <=  iagemax){                 if(agev[m][i]==1) agev[m][i]=iagemax+2;
             if(posprop>=1.e-5){                 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);
               probs[i][jk][j1]= prop[jk][i]/posprop;                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];
         }/* end jk */                   prop[s[m][i]][iagemax+3] += weight[i];
       }/* end i */                 }
     } /* end i1 */              }
   } /* end k1 */            } /* end selection of waves */
             }
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/        }
   /*free_vector(pp,1,nlstate);*/        for(i=iagemin; i <= iagemax+3; i++){  
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);         
 }  /* End of prevalence */          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
             posprop += prop[jk][i];
 /************* Waves Concatenation ***************/          }
   
 void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)          for(jk=1; jk <=nlstate ; jk++){    
 {            if( i <=  iagemax){
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.              if(posprop>=1.e-5){
      Death is a valid wave (if date is known).                probs[i][jk][j1]= prop[jk][i]/posprop;
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i              }
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]            }
      and mw[mi+1][i]. dh depends on stepm.          }/* end jk */
      */        }/* end i */
       } /* end i1 */
   int i, mi, m;    } /* end k1 */
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;   
      double sum=0., jmean=0.;*/    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
   int first;    /*free_vector(pp,1,nlstate);*/
   int j, k=0,jk, ju, jl;    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
   double sum=0.;  }  /* End of prevalence */
   first=0;  
   jmin=1e+5;  /************* Waves Concatenation ***************/
   jmax=-1;  
   jmean=0.;  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(i=1; i<=imx; i++){  {
     mi=0;    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
     m=firstpass;       Death is a valid wave (if date is known).
     while(s[m][i] <= nlstate){       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)       dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
         mw[++mi][i]=m;       and mw[mi+1][i]. dh depends on stepm.
       if(m >=lastpass)       */
         break;  
       else    int i, mi, m;
         m++;    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
     }/* end while */       double sum=0., jmean=0.;*/
     if (s[m][i] > nlstate){    int first;
       mi++;     /* Death is another wave */    int j, k=0,jk, ju, jl;
       /* if(mi==0)  never been interviewed correctly before death */    double sum=0.;
          /* Only death is a correct wave */    first=0;
       mw[mi][i]=m;    jmin=1e+5;
     }    jmax=-1;
     jmean=0.;
     wav[i]=mi;    for(i=1; i<=imx; i++){
     if(mi==0){      mi=0;
       nbwarn++;      m=firstpass;
       if(first==0){      while(s[m][i] <= nlstate){
         printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
         first=1;          mw[++mi][i]=m;
       }        if(m >=lastpass)
       if(first==1){          break;
         fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);        else
       }          m++;
     } /* end mi==0 */      }/* end while */
   } /* End individuals */      if (s[m][i] > nlstate){
         mi++;     /* Death is another wave */
   for(i=1; i<=imx; i++){        /* if(mi==0)  never been interviewed correctly before death */
     for(mi=1; mi<wav[i];mi++){           /* Only death is a correct wave */
       if (stepm <=0)        mw[mi][i]=m;
         dh[mi][i]=1;      }
       else{  
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */      wav[i]=mi;
           if (agedc[i] < 2*AGESUP) {      if(mi==0){
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);         nbwarn++;
             if(j==0) j=1;  /* Survives at least one month after exam */        if(first==0){
             else if(j<0){          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
               nberr++;          first=1;
               printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);        }
               j=1; /* Temporary Dangerous patch */        if(first==1){
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
               fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);        }
               fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);      } /* end mi==0 */
             }    } /* End individuals */
             k=k+1;  
             if (j >= jmax){    for(i=1; i<=imx; i++){
               jmax=j;      for(mi=1; mi<wav[i];mi++){
               ijmax=i;        if (stepm <=0)
             }          dh[mi][i]=1;
             if (j <= jmin){        else{
               jmin=j;          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
               ijmin=i;            if (agedc[i] < 2*AGESUP) {
             }              j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
             sum=sum+j;              if(j==0) j=1;  /* Survives at least one month after exam */
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/              else if(j<0){
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,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]);
         }                j=1; /* Temporary Dangerous patch */
         else{                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);
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));                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 (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */                fprintf(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);
               }
           k=k+1;              k=k+1;
           if (j >= jmax) {              if (j >= jmax){
             jmax=j;                jmax=j;
             ijmax=i;                ijmax=i;
           }              }
           else if (j <= jmin){              if (j <= jmin){
             jmin=j;                jmin=j;
             ijmin=i;                ijmin=i;
           }              }
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */              sum=sum+j;
           /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/              /*if (j<0) printf("j=%d num=%d \n",j,i);*/
           if(j<0){              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
             nberr++;            }
             printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);          }
             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]);          else{
           }            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
           sum=sum+j;  /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */
         }  
         jk= j/stepm;            k=k+1;
         jl= j -jk*stepm;            if (j >= jmax) {
         ju= j -(jk+1)*stepm;              jmax=j;
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */              ijmax=i;
           if(jl==0){            }
             dh[mi][i]=jk;            else if (j <= jmin){
             bh[mi][i]=0;              jmin=j;
           }else{ /* We want a negative bias in order to only have interpolation ie              ijmin=i;
                   * at the price of an extra matrix product in likelihood */            }
             dh[mi][i]=jk+1;            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
             bh[mi][i]=ju;            /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
           }            if(j<0){
         }else{              nberr++;
           if(jl <= -ju){              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]);
             dh[mi][i]=jk;              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]);
             bh[mi][i]=jl;       /* bias is positive if real duration            }
                                  * is higher than the multiple of stepm and negative otherwise.            sum=sum+j;
                                  */          }
           }          jk= j/stepm;
           else{          jl= j -jk*stepm;
             dh[mi][i]=jk+1;          ju= j -(jk+1)*stepm;
             bh[mi][i]=ju;          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
           }            if(jl==0){
           if(dh[mi][i]==0){              dh[mi][i]=jk;
             dh[mi][i]=1; /* At least one step */              bh[mi][i]=0;
             bh[mi][i]=ju; /* At least one step */            }else{ /* We want a negative bias in order to only have interpolation ie
             /*  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);*/                    * at the price of an extra matrix product in likelihood */
           }              dh[mi][i]=jk+1;
         } /* end if mle */              bh[mi][i]=ju;
       }            }
     } /* end wave */          }else{
   }            if(jl <= -ju){
   jmean=sum/k;              dh[mi][i]=jk;
   printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);              bh[mi][i]=jl;       /* bias is positive if real duration
   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);                                   * is higher than the multiple of stepm and negative otherwise.
  }                                   */
             }
 /*********** Tricode ****************************/            else{
 void tricode(int *Tvar, int **nbcode, int imx)              dh[mi][i]=jk+1;
 {              bh[mi][i]=ju;
               }
   int Ndum[20],ij=1, k, j, i, maxncov=19;            if(dh[mi][i]==0){
   int cptcode=0;              dh[mi][i]=1; /* At least one step */
   cptcoveff=0;               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);*/
   for (k=0; k<maxncov; k++) Ndum[k]=0;            }
   for (k=1; k<=7; k++) ncodemax[k]=0;          } /* end if mle */
         }
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {      } /* end wave */
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum     }
                                modality*/     jmean=sum/k;
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/    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);
       Ndum[ij]++; /*store the modality */    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("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/   }
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable   
                                        Tvar[j]. If V=sex and male is 0 and   /*********** Tricode ****************************/
                                        female is 1, then  cptcode=1.*/  void tricode(int *Tvar, int **nbcode, int imx)
     }  {
    
     for (i=0; i<=cptcode; i++) {    int Ndum[20],ij=1, k, j, i, maxncov=19;
       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 */    int cptcode=0;
     }    cptcoveff=0;
    
     ij=1;     for (k=0; k<maxncov; k++) Ndum[k]=0;
     for (i=1; i<=ncodemax[j]; i++) {    for (k=1; k<=7; k++) ncodemax[k]=0;
       for (k=0; k<= maxncov; k++) {  
         if (Ndum[k] != 0) {    for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
           nbcode[Tvar[j]][ij]=k;       for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
           /* 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; */                                 modality*/
                   ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
           ij++;        Ndum[ij]++; /*store the modality */
         }        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
         if (ij > ncodemax[j]) break;         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.*/
   }        }
   
  for (k=0; k< maxncov; k++) Ndum[k]=0;      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 */
  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.*/  
    ij=Tvar[i];      ij=1;
    Ndum[ij]++;      for (i=1; i<=ncodemax[j]; i++) {
  }        for (k=0; k<= maxncov; k++) {
           if (Ndum[k] != 0) {
  ij=1;            nbcode[Tvar[j]][ij]=k;
  for (i=1; i<= maxncov; i++) {            /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
    if((Ndum[i]!=0) && (i<=ncovcol)){           
      Tvaraff[ij]=i; /*For printing */            ij++;
      ij++;          }
    }          if (ij > ncodemax[j]) break;
  }        }  
        }
  cptcoveff=ij-1; /*Number of simple covariates*/    }  
 }  
    for (k=0; k< maxncov; k++) Ndum[k]=0;
 /*********** Health Expectancies ****************/  
    for (i=1; i<=ncovmodel-2; i++) {
 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[] )     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
      ij=Tvar[i];
 {     Ndum[ij]++;
   /* Health expectancies, no variances */   }
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;  
   double age, agelim, hf;   ij=1;
   double ***p3mat;   for (i=1; i<= maxncov; i++) {
   double eip;     if((Ndum[i]!=0) && (i<=ncovcol)){
        Tvaraff[ij]=i; /*For printing */
   pstamp(ficreseij);       ij++;
   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");   }
   for(i=1; i<=nlstate;i++){   
     for(j=1; j<=nlstate;j++){   cptcoveff=ij-1; /*Number of simple covariates*/
       fprintf(ficreseij," e%1d%1d ",i,j);  }
     }  
     fprintf(ficreseij," e%1d. ",i);  /*********** Health Expectancies ****************/
   }  
   fprintf(ficreseij,"\n");  void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
   
     {
   if(estepm < stepm){    /* Health expectancies, no variances */
     printf ("Problem %d lower than %d\n",estepm, stepm);    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
   }    double age, agelim, hf;
   else  hstepm=estepm;       double ***p3mat;
   /* We compute the life expectancy from trapezoids spaced every estepm months    double eip;
    * This is mainly to measure the difference between two models: for example  
    * if stepm=24 months pijx are given only every 2 years and by summing them    pstamp(ficreseij);
    * we are calculating an estimate of the Life Expectancy assuming a linear     fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
    * progression in between and thus overestimating or underestimating according    fprintf(ficreseij,"# Age");
    * to the curvature of the survival function. If, for the same date, we     for(i=1; i<=nlstate;i++){
    * estimate the model with stepm=1 month, we can keep estepm to 24 months      for(j=1; j<=nlstate;j++){
    * to compare the new estimate of Life expectancy with the same linear         fprintf(ficreseij," e%1d%1d ",i,j);
    * hypothesis. A more precise result, taking into account a more precise      }
    * curvature will be obtained if estepm is as small as stepm. */      fprintf(ficreseij," e%1d. ",i);
     }
   /* For example we decided to compute the life expectancy with the smallest unit */    fprintf(ficreseij,"\n");
   /* 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.     if(estepm < stepm){
      Look at hpijx to understand the reason of that which relies in memory size      printf ("Problem %d lower than %d\n",estepm, stepm);
      and note for a fixed period like estepm months */    }
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    else  hstepm=estepm;  
      survival function given by stepm (the optimization length). Unfortunately it    /* We compute the life expectancy from trapezoids spaced every estepm months
      means that if the survival funtion is printed only each two years of age and if     * This is mainly to measure the difference between two models: for example
      you sum them up and add 1 year (area under the trapezoids) you won't get the same      * if stepm=24 months pijx are given only every 2 years and by summing them
      results. So we changed our mind and took the option of the best precision.     * we are calculating an estimate of the Life Expectancy assuming a linear
   */     * progression in between and thus overestimating or underestimating according
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */      * 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
   agelim=AGESUP;     * to compare the new estimate of Life expectancy with the same linear
   /* nhstepm age range expressed in number of stepm */     * hypothesis. A more precise result, taking into account a more precise
   nstepm=(int) rint((agelim-age)*YEARM/stepm);      * curvature will be obtained if estepm is as small as stepm. */
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */   
   /* if (stepm >= YEARM) hstepm=1;*/    /* For example we decided to compute the life expectancy with the smallest unit */
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);       nhstepm is the number of hstepm from age to agelim
        nstepm is the number of stepm from age to agelin.
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */       Look at hpijx to understand the reason of that which relies in memory size
     /* Computed by stepm unit matrices, product of hstepm matrices, stored       and note for a fixed period like estepm months */
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
            survival function given by stepm (the optimization length). Unfortunately it
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);         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
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */       results. So we changed our mind and took the option of the best precision.
         */
     printf("%d|",(int)age);fflush(stdout);    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);  
         agelim=AGESUP;
     /* Computing expectancies */    /* If stepm=6 months */
     for(i=1; i<=nlstate;i++)      /* Computed by stepm unit matrices, product of hstepm matrices, stored
       for(j=1; j<=nlstate;j++)         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){     
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;  /* nhstepm age range expressed in number of stepm */
               nstepm=(int) rint((agelim-bage)*YEARM/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]);*/    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
     /* if (stepm >= YEARM) hstepm=1;*/
         }    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     fprintf(ficreseij,"%3.0f",age );  
     for(i=1; i<=nlstate;i++){    for (age=bage; age<=fage; age ++){
       eip=0;  
       for(j=1; j<=nlstate;j++){  
         eip +=eij[i][j][(int)age];      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
         fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );     
       }      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
       fprintf(ficreseij,"%9.4f", eip );     
     }      printf("%d|",(int)age);fflush(stdout);
     fprintf(ficreseij,"\n");      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
          
   }  
   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      /* Computing expectancies */
   printf("\n");      for(i=1; i<=nlstate;i++)
   fprintf(ficlog,"\n");        for(j=1; j<=nlstate;j++)
             for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 }            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
            
 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((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]);*/
   
 {          }
   /* Covariances of health expectancies eij and of total life expectancies according     
    to initial status i, ei. .      fprintf(ficreseij,"%3.0f",age );
   */      for(i=1; i<=nlstate;i++){
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;        eip=0;
   double age, agelim, hf;        for(j=1; j<=nlstate;j++){
   double ***p3matp, ***p3matm, ***varhe;          eip +=eij[i][j][(int)age];
   double **dnewm,**doldm;          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
   double *xp, *xm;        }
   double **gp, **gm;        fprintf(ficreseij,"%9.4f", eip );
   double ***gradg, ***trgradg;      }
   int theta;      fprintf(ficreseij,"\n");
      
   double eip, vip;    }
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);    printf("\n");
   xp=vector(1,npar);    fprintf(ficlog,"\n");
   xm=vector(1,npar);   
   dnewm=matrix(1,nlstate*nlstate,1,npar);  }
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);  
     void cvevsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
   pstamp(ficresstdeij);  
   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");  {
   fprintf(ficresstdeij,"# Age");    /* Covariances of health expectancies eij and of total life expectancies according
   for(i=1; i<=nlstate;i++){     to initial status i, ei. .
     for(j=1; j<=nlstate;j++)    */
       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
     fprintf(ficresstdeij," e%1d. ",i);    double age, agelim, hf;
   }    double ***p3matp, ***p3matm, ***varhe;
   fprintf(ficresstdeij,"\n");    double **dnewm,**doldm;
     double *xp, *xm;
   pstamp(ficrescveij);    double **gp, **gm;
   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");    double ***gradg, ***trgradg;
   fprintf(ficrescveij,"# Age");    int theta;
   for(i=1; i<=nlstate;i++)  
     for(j=1; j<=nlstate;j++){    double eip, vip;
       cptj= (j-1)*nlstate+i;  
       for(i2=1; i2<=nlstate;i2++)    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
         for(j2=1; j2<=nlstate;j2++){    xp=vector(1,npar);
           cptj2= (j2-1)*nlstate+i2;    xm=vector(1,npar);
           if(cptj2 <= cptj)    dnewm=matrix(1,nlstate*nlstate,1,npar);
             fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);    doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
         }   
     }    pstamp(ficresstdeij);
   fprintf(ficrescveij,"\n");    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
       fprintf(ficresstdeij,"# Age");
   if(estepm < stepm){    for(i=1; i<=nlstate;i++){
     printf ("Problem %d lower than %d\n",estepm, stepm);      for(j=1; j<=nlstate;j++)
   }        fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
   else  hstepm=estepm;         fprintf(ficresstdeij," e%1d. ",i);
   /* We compute the life expectancy from trapezoids spaced every estepm months    }
    * This is mainly to measure the difference between two models: for example    fprintf(ficresstdeij,"\n");
    * 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     pstamp(ficrescveij);
    * progression in between and thus overestimating or underestimating according    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
    * to the curvature of the survival function. If, for the same date, we     fprintf(ficrescveij,"# Age");
    * estimate the model with stepm=1 month, we can keep estepm to 24 months    for(i=1; i<=nlstate;i++)
    * to compare the new estimate of Life expectancy with the same linear       for(j=1; j<=nlstate;j++){
    * hypothesis. A more precise result, taking into account a more precise        cptj= (j-1)*nlstate+i;
    * curvature will be obtained if estepm is as small as stepm. */        for(i2=1; i2<=nlstate;i2++)
           for(j2=1; j2<=nlstate;j2++){
   /* For example we decided to compute the life expectancy with the smallest unit */            cptj2= (j2-1)*nlstate+i2;
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.             if(cptj2 <= cptj)
      nhstepm is the number of hstepm from age to agelim               fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
      nstepm is the number of stepm from age to agelin.           }
      Look at hpijx to understand the reason of that which relies in memory size      }
      and note for a fixed period like estepm months */    fprintf(ficrescveij,"\n");
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the   
      survival function given by stepm (the optimization length). Unfortunately it    if(estepm < stepm){
      means that if the survival funtion is printed only each two years of age and if      printf ("Problem %d lower than %d\n",estepm, stepm);
      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.    else  hstepm=estepm;  
   */    /* We compute the life expectancy from trapezoids spaced every estepm months
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */      * This is mainly to measure the difference between two models: for example
      * if stepm=24 months pijx are given only every 2 years and by summing them
   /* If stepm=6 months */     * we are calculating an estimate of the Life Expectancy assuming a linear
   /* nhstepm age range expressed in number of stepm */     * progression in between and thus overestimating or underestimating according
   agelim=AGESUP;     * to the curvature of the survival function. If, for the same date, we
   nstepm=(int) rint((agelim-age)*YEARM/stepm);      * estimate the model with stepm=1 month, we can keep estepm to 24 months
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */      * to compare the new estimate of Life expectancy with the same linear
   /* if (stepm >= YEARM) hstepm=1;*/     * hypothesis. A more precise result, taking into account a more precise
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */     * curvature will be obtained if estepm is as small as stepm. */
     
   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    /* For example we decided to compute the life expectancy with the smallest unit */
   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);       nhstepm is the number of hstepm from age to agelim
   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);       nstepm is the number of stepm from age to agelin.
   gp=matrix(0,nhstepm,1,nlstate*nlstate);       Look at hpijx to understand the reason of that which relies in memory size
   gm=matrix(0,nhstepm,1,nlstate*nlstate);       and note for a fixed period like estepm months */
     /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   for (age=bage; age<=fage; age ++){        survival function given by stepm (the optimization length). Unfortunately it
        means that if the survival funtion is printed only each two years of age and if
     /* Computed by stepm unit matrices, product of hstepm matrices, stored       you sum them up and add 1 year (area under the trapezoids) you won't get the same
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */       results. So we changed our mind and took the option of the best precision.
      */
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   
     /* Computing  Variances of health expectancies */    /* If stepm=6 months */
     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to    /* nhstepm age range expressed in number of stepm */
        decrease memory allocation */    agelim=AGESUP;
     for(theta=1; theta <=npar; theta++){    nstepm=(int) rint((agelim-bage)*YEARM/stepm);
       for(i=1; i<=npar; i++){     /* Typically if 20 years nstepm = 20*12/6=40 stepm */
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    /* if (stepm >= YEARM) hstepm=1;*/
         xm[i] = x[i] - (i==theta ?delti[theta]:0);    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       }   
       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);      p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);      p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
       for(j=1; j<= nlstate; j++){    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
         for(i=1; i<=nlstate; i++){    gp=matrix(0,nhstepm,1,nlstate*nlstate);
           for(h=0; h<=nhstepm-1; h++){    gm=matrix(0,nhstepm,1,nlstate*nlstate);
             gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;  
             gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;    for (age=bage; age<=fage; age ++){
           }  
         }      /* Computed by stepm unit matrices, product of hstepm matrices, stored
       }         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
         
       for(ij=1; ij<= nlstate*nlstate; ij++)      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
         for(h=0; h<=nhstepm-1; h++){  
           gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];      /* Computing  Variances of health expectancies */
         }      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
     }/* End theta */         decrease memory allocation */
           for(theta=1; theta <=npar; theta++){
             for(i=1; i<=npar; i++){
     for(h=0; h<=nhstepm-1; h++)          xp[i] = x[i] + (i==theta ?delti[theta]:0);
       for(j=1; j<=nlstate*nlstate;j++)          xm[i] = x[i] - (i==theta ?delti[theta]:0);
         for(theta=1; theta <=npar; theta++)        }
           trgradg[h][j][theta]=gradg[h][theta][j];        hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
             hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
    
      for(ij=1;ij<=nlstate*nlstate;ij++)        for(j=1; j<= nlstate; j++){
       for(ji=1;ji<=nlstate*nlstate;ji++)          for(i=1; i<=nlstate; i++){
         varhe[ij][ji][(int)age] =0.;            for(h=0; h<=nhstepm-1; h++){
               gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
      printf("%d|",(int)age);fflush(stdout);              gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);            }
      for(h=0;h<=nhstepm-1;h++){          }
       for(k=0;k<=nhstepm-1;k++){        }
         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++)
         for(ij=1;ij<=nlstate*nlstate;ij++)          for(h=0; h<=nhstepm-1; h++){
           for(ji=1;ji<=nlstate*nlstate;ji++)            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
             varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;          }
       }      }/* End theta */
     }     
     /* Computing expectancies */     
     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);        for(h=0; h<=nhstepm-1; h++)
     for(i=1; i<=nlstate;i++)        for(j=1; j<=nlstate*nlstate;j++)
       for(j=1; j<=nlstate;j++)          for(theta=1; theta <=npar; theta++)
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){            trgradg[h][j][theta]=gradg[h][theta][j];
           eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;     
             
           /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/       for(ij=1;ij<=nlstate*nlstate;ij++)
         for(ji=1;ji<=nlstate*nlstate;ji++)
         }          varhe[ij][ji][(int)age] =0.;
   
     fprintf(ficresstdeij,"%3.0f",age );       printf("%d|",(int)age);fflush(stdout);
     for(i=1; i<=nlstate;i++){       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
       eip=0.;       for(h=0;h<=nhstepm-1;h++){
       vip=0.;        for(k=0;k<=nhstepm-1;k++){
       for(j=1; j<=nlstate;j++){          matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
         eip += eij[i][j][(int)age];          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
         for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */          for(ij=1;ij<=nlstate*nlstate;ij++)
           vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];            for(ji=1;ji<=nlstate*nlstate;ji++)
         fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
       }        }
       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));      }
     }  
     fprintf(ficresstdeij,"\n");      /* Computing expectancies */
       hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
     fprintf(ficrescveij,"%3.0f",age );      for(i=1; i<=nlstate;i++)
     for(i=1; i<=nlstate;i++)        for(j=1; j<=nlstate;j++)
       for(j=1; j<=nlstate;j++){          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
         cptj= (j-1)*nlstate+i;            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
         for(i2=1; i2<=nlstate;i2++)           
           for(j2=1; j2<=nlstate;j2++){            /* 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]);*/
             cptj2= (j2-1)*nlstate+i2;  
             if(cptj2 <= cptj)          }
               fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);  
           }      fprintf(ficresstdeij,"%3.0f",age );
       }      for(i=1; i<=nlstate;i++){
     fprintf(ficrescveij,"\n");        eip=0.;
            vip=0.;
   }        for(j=1; j<=nlstate;j++){
   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);          eip += eij[i][j][(int)age];
   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        }
   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
   printf("\n");      }
   fprintf(ficlog,"\n");      fprintf(ficresstdeij,"\n");
   
   free_vector(xm,1,npar);      fprintf(ficrescveij,"%3.0f",age );
   free_vector(xp,1,npar);      for(i=1; i<=nlstate;i++)
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);        for(j=1; j<=nlstate;j++){
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);          cptj= (j-1)*nlstate+i;
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);          for(i2=1; i2<=nlstate;i2++)
 }            for(j2=1; j2<=nlstate;j2++){
               cptj2= (j2-1)*nlstate+i2;
 /************ Variance ******************/              if(cptj2 <= cptj)
 void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 {            }
   /* Variance of health expectancies */        }
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/      fprintf(ficrescveij,"\n");
   /* double **newm;*/     
   double **dnewm,**doldm;    }
   double **dnewmp,**doldmp;    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
   int i, j, nhstepm, hstepm, h, nstepm ;    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
   int k, cptcode;    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
   double *xp;    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
   double **gp, **gm;  /* for var eij */    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double ***gradg, ***trgradg; /*for var eij */    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double **gradgp, **trgradgp; /* for var p point j */    printf("\n");
   double *gpp, *gmp; /* for var p point j */    fprintf(ficlog,"\n");
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */  
   double ***p3mat;    free_vector(xm,1,npar);
   double age,agelim, hf;    free_vector(xp,1,npar);
   double ***mobaverage;    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
   int theta;    free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
   char digit[4];    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
   char digitp[25];  }
   
   char fileresprobmorprev[FILENAMELENGTH];  /************ Variance ******************/
   void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
   if(popbased==1){  {
     if(mobilav!=0)    /* Variance of health expectancies */
       strcpy(digitp,"-populbased-mobilav-");    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
     else strcpy(digitp,"-populbased-nomobil-");    /* double **newm;*/
   }    double **dnewm,**doldm;
   else     double **dnewmp,**doldmp;
     strcpy(digitp,"-stablbased-");    int i, j, nhstepm, hstepm, h, nstepm ;
     int k, cptcode;
   if (mobilav!=0) {    double *xp;
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    double **gp, **gm;  /* for var eij */
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){    double ***gradg, ***trgradg; /*for var eij */
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    double **gradgp, **trgradgp; /* for var p point j */
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    double *gpp, *gmp; /* for var p point j */
     }    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
   }    double ***p3mat;
     double age,agelim, hf;
   strcpy(fileresprobmorprev,"prmorprev");     double ***mobaverage;
   sprintf(digit,"%-d",ij);    int theta;
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/    char digit[4];
   strcat(fileresprobmorprev,digit); /* Tvar to be done */    char digitp[25];
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */  
   strcat(fileresprobmorprev,fileres);    char fileresprobmorprev[FILENAMELENGTH];
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {  
     printf("Problem with resultfile: %s\n", fileresprobmorprev);    if(popbased==1){
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);      if(mobilav!=0)
   }        strcpy(digitp,"-populbased-mobilav-");
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);      else strcpy(digitp,"-populbased-nomobil-");
      }
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    else
   pstamp(ficresprobmorprev);      strcpy(digitp,"-stablbased-");
   fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);  
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);    if (mobilav!=0) {
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     fprintf(ficresprobmorprev," p.%-d SE",j);      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
     for(i=1; i<=nlstate;i++)        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   }        }
   fprintf(ficresprobmorprev,"\n");    }
   fprintf(ficgp,"\n# Routine varevsij");  
   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/    strcpy(fileresprobmorprev,"prmorprev");
   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");    sprintf(digit,"%-d",ij);
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 /*   } */    strcat(fileresprobmorprev,digit); /* Tvar to be done */
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
   pstamp(ficresvij);    strcat(fileresprobmorprev,fileres);
   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
   if(popbased==1)      printf("Problem with resultfile: %s\n", fileresprobmorprev);
     fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
   else    }
     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   fprintf(ficresvij,"# Age");   
   for(i=1; i<=nlstate;i++)    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
     for(j=1; j<=nlstate;j++)    pstamp(ficresprobmorprev);
       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);    fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);
   fprintf(ficresvij,"\n");    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   xp=vector(1,npar);      fprintf(ficresprobmorprev," p.%-d SE",j);
   dnewm=matrix(1,nlstate,1,npar);      for(i=1; i<=nlstate;i++)
   doldm=matrix(1,nlstate,1,nlstate);        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);    }  
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    fprintf(ficresprobmorprev,"\n");
     fprintf(ficgp,"\n# Routine varevsij");
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
   gpp=vector(nlstate+1,nlstate+ndeath);    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");
   gmp=vector(nlstate+1,nlstate+ndeath);    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/  /*   } */
       varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   if(estepm < stepm){    pstamp(ficresvij);
     printf ("Problem %d lower than %d\n",estepm, stepm);    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
   }    if(popbased==1)
   else  hstepm=estepm;         fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
   /* For example we decided to compute the life expectancy with the smallest unit */    else
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.       fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
      nhstepm is the number of hstepm from age to agelim     fprintf(ficresvij,"# Age");
      nstepm is the number of stepm from age to agelin.     for(i=1; i<=nlstate;i++)
      Look at hpijx to understand the reason of that which relies in memory size      for(j=1; j<=nlstate;j++)
      and note for a fixed period like k years */        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    fprintf(ficresvij,"\n");
      survival function given by stepm (the optimization length). Unfortunately it  
      means that if the survival funtion is printed every two years of age and if    xp=vector(1,npar);
      you sum them up and add 1 year (area under the trapezoids) you won't get the same     dnewm=matrix(1,nlstate,1,npar);
      results. So we changed our mind and took the option of the best precision.    doldm=matrix(1,nlstate,1,nlstate);
   */    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   agelim = AGESUP;  
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     gpp=vector(nlstate+1,nlstate+ndeath);
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */    gmp=vector(nlstate+1,nlstate+ndeath);
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);   
     gp=matrix(0,nhstepm,1,nlstate);    if(estepm < stepm){
     gm=matrix(0,nhstepm,1,nlstate);      printf ("Problem %d lower than %d\n",estepm, stepm);
     }
     else  hstepm=estepm;  
     for(theta=1; theta <=npar; theta++){    /* For example we decided to compute the life expectancy with the smallest unit */
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
         xp[i] = x[i] + (i==theta ?delti[theta]:0);       nhstepm is the number of hstepm from age to agelim
       }       nstepm is the number of stepm from age to agelin.
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);         Look at hpijx to understand the reason of that which relies in memory size
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);       and note for a fixed period like k years */
     /* We decided (b) to get a life expectancy respecting the most precise curvature of the
       if (popbased==1) {       survival function given by stepm (the optimization length). Unfortunately it
         if(mobilav ==0){       means that if the survival funtion is printed every two years of age and if
           for(i=1; i<=nlstate;i++)       you sum them up and add 1 year (area under the trapezoids) you won't get the same
             prlim[i][i]=probs[(int)age][i][ij];       results. So we changed our mind and took the option of the best precision.
         }else{ /* mobilav */     */
           for(i=1; i<=nlstate;i++)    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
             prlim[i][i]=mobaverage[(int)age][i][ij];    agelim = AGESUP;
         }    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
       }      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 */
       for(j=1; j<= nlstate; j++){      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         for(h=0; h<=nhstepm; h++){      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)      gp=matrix(0,nhstepm,1,nlstate);
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];      gm=matrix(0,nhstepm,1,nlstate);
         }  
       }  
       /* This for computing probability of death (h=1 means      for(theta=1; theta <=npar; theta++){
          computed over hstepm matrices product = hstepm*stepm months)         for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
          as a weighted average of prlim.          xp[i] = x[i] + (i==theta ?delti[theta]:0);
       */        }
       for(j=nlstate+1;j<=nlstate+ndeath;j++){        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
         for(i=1,gpp[j]=0.; i<= nlstate; i++)        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
           gpp[j] += prlim[i][i]*p3mat[i][j][1];  
       }            if (popbased==1) {
       /* end probability of death */          if(mobilav ==0){
             for(i=1; i<=nlstate;i++)
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */              prlim[i][i]=probs[(int)age][i][ij];
         xp[i] = x[i] - (i==theta ?delti[theta]:0);          }else{ /* mobilav */
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);              for(i=1; i<=nlstate;i++)
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);              prlim[i][i]=mobaverage[(int)age][i][ij];
            }
       if (popbased==1) {        }
         if(mobilav ==0){   
           for(i=1; i<=nlstate;i++)        for(j=1; j<= nlstate; j++){
             prlim[i][i]=probs[(int)age][i][ij];          for(h=0; h<=nhstepm; h++){
         }else{ /* mobilav */             for(i=1, gp[h][j]=0.;i<=nlstate;i++)
           for(i=1; i<=nlstate;i++)              gp[h][j] += prlim[i][i]*p3mat[i][j][h];
             prlim[i][i]=mobaverage[(int)age][i][ij];          }
         }        }
       }        /* This for computing probability of death (h=1 means
            computed over hstepm matrices product = hstepm*stepm months)
       for(j=1; j<= nlstate; j++){           as a weighted average of prlim.
         for(h=0; h<=nhstepm; h++){        */
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)        for(j=nlstate+1;j<=nlstate+ndeath;j++){
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];          for(i=1,gpp[j]=0.; i<= nlstate; i++)
         }            gpp[j] += prlim[i][i]*p3mat[i][j][1];
       }        }    
       /* This for computing probability of death (h=1 means        /* end probability of death */
          computed over hstepm matrices product = hstepm*stepm months)   
          as a weighted average of prlim.        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
       */          xp[i] = x[i] - (i==theta ?delti[theta]:0);
       for(j=nlstate+1;j<=nlstate+ndeath;j++){        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
         for(i=1,gmp[j]=0.; i<= nlstate; i++)        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
          gmp[j] += prlim[i][i]*p3mat[i][j][1];   
       }            if (popbased==1) {
       /* end probability of death */          if(mobilav ==0){
             for(i=1; i<=nlstate;i++)
       for(j=1; j<= nlstate; j++) /* vareij */              prlim[i][i]=probs[(int)age][i][ij];
         for(h=0; h<=nhstepm; h++){          }else{ /* mobilav */
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];            for(i=1; i<=nlstate;i++)
         }              prlim[i][i]=mobaverage[(int)age][i][ij];
           }
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */        }
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];  
       }        for(j=1; j<= nlstate; j++){
           for(h=0; h<=nhstepm; h++){
     } /* End theta */            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
               gm[h][j] += prlim[i][i]*p3mat[i][j][h];
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */          }
         }
     for(h=0; h<=nhstepm; h++) /* veij */        /* This for computing probability of death (h=1 means
       for(j=1; j<=nlstate;j++)           computed over hstepm matrices product = hstepm*stepm months)
         for(theta=1; theta <=npar; theta++)           as a weighted average of prlim.
           trgradg[h][j][theta]=gradg[h][theta][j];        */
         for(j=nlstate+1;j<=nlstate+ndeath;j++){
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */          for(i=1,gmp[j]=0.; i<= nlstate; i++)
       for(theta=1; theta <=npar; theta++)           gmp[j] += prlim[i][i]*p3mat[i][j][1];
         trgradgp[j][theta]=gradgp[theta][j];        }    
           /* end probability of death */
   
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */        for(j=1; j<= nlstate; j++) /* vareij */
     for(i=1;i<=nlstate;i++)          for(h=0; h<=nhstepm; h++){
       for(j=1;j<=nlstate;j++)            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
         vareij[i][j][(int)age] =0.;          }
   
     for(h=0;h<=nhstepm;h++){        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
       for(k=0;k<=nhstepm;k++){          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);        }
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);  
         for(i=1;i<=nlstate;i++)      } /* End theta */
           for(j=1;j<=nlstate;j++)  
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
       }  
     }      for(h=0; h<=nhstepm; h++) /* veij */
           for(j=1; j<=nlstate;j++)
     /* pptj */          for(theta=1; theta <=npar; theta++)
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);            trgradg[h][j][theta]=gradg[h][theta][j];
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);  
     for(j=nlstate+1;j<=nlstate+ndeath;j++)      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
       for(i=nlstate+1;i<=nlstate+ndeath;i++)        for(theta=1; theta <=npar; theta++)
         varppt[j][i]=doldmp[j][i];          trgradgp[j][theta]=gradgp[theta][j];
     /* end ppptj */   
     /*  x centered again */  
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);        hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);      for(i=1;i<=nlstate;i++)
          for(j=1;j<=nlstate;j++)
     if (popbased==1) {          vareij[i][j][(int)age] =0.;
       if(mobilav ==0){  
         for(i=1; i<=nlstate;i++)      for(h=0;h<=nhstepm;h++){
           prlim[i][i]=probs[(int)age][i][ij];        for(k=0;k<=nhstepm;k++){
       }else{ /* mobilav */           matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
         for(i=1; i<=nlstate;i++)          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
           prlim[i][i]=mobaverage[(int)age][i][ij];          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 (estepm) matrices product = hstepm*stepm months)    
        as a weighted average of prlim.      /* pptj */
     */      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
     for(j=nlstate+1;j<=nlstate+ndeath;j++){      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
       for(i=1,gmp[j]=0.;i<= nlstate; i++)       for(j=nlstate+1;j<=nlstate+ndeath;j++)
         gmp[j] += prlim[i][i]*p3mat[i][j][1];         for(i=nlstate+1;i<=nlstate+ndeath;i++)
     }              varppt[j][i]=doldmp[j][i];
     /* end probability of death */      /* end ppptj */
       /*  x centered again */
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));   
       for(i=1; i<=nlstate;i++){      if (popbased==1) {
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);        if(mobilav ==0){
       }          for(i=1; i<=nlstate;i++)
     }             prlim[i][i]=probs[(int)age][i][ij];
     fprintf(ficresprobmorprev,"\n");        }else{ /* mobilav */
           for(i=1; i<=nlstate;i++)
     fprintf(ficresvij,"%.0f ",age );            prlim[i][i]=mobaverage[(int)age][i][ij];
     for(i=1; i<=nlstate;i++)        }
       for(j=1; j<=nlstate;j++){      }
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);               
       }      /* This for computing probability of death (h=1 means
     fprintf(ficresvij,"\n");         computed over hstepm (estepm) matrices product = hstepm*stepm months)
     free_matrix(gp,0,nhstepm,1,nlstate);         as a weighted average of prlim.
     free_matrix(gm,0,nhstepm,1,nlstate);      */
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);      for(j=nlstate+1;j<=nlstate+ndeath;j++){
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);        for(i=1,gmp[j]=0.;i<= nlstate; i++)
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          gmp[j] += prlim[i][i]*p3mat[i][j][1];
   } /* End age */      }    
   free_vector(gpp,nlstate+1,nlstate+ndeath);      /* end probability of death */
   free_vector(gmp,nlstate+1,nlstate+ndeath);  
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */        for(i=1; i<=nlstate;i++){
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */        }
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */      }
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */      fprintf(ficresprobmorprev,"\n");
   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(ficresvij,"%.0f ",age );
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));      for(i=1; i<=nlstate;i++)
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));        for(j=1; j<=nlstate;j++){
   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
   /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);        }
 */      fprintf(ficresvij,"\n");
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */      free_matrix(gp,0,nhstepm,1,nlstate);
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);      free_matrix(gm,0,nhstepm,1,nlstate);
       free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
   free_vector(xp,1,npar);      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
   free_matrix(doldm,1,nlstate,1,nlstate);      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   free_matrix(dnewm,1,nlstate,1,npar);    } /* End age */
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    free_vector(gpp,nlstate+1,nlstate+ndeath);
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);    free_vector(gmp,nlstate+1,nlstate+ndeath);
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
   fclose(ficresprobmorprev);    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
   fflush(ficgp);    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
   fflush(fichtm);     fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 }  /* end varevsij */  /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
   /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 /************ Variance of prevlim ******************/  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])    fprintf(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));
   /* Variance of prevalence limit */    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
   double **newm;    fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
   double **dnewm,**doldm;    /*  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);
   int i, j, nhstepm, hstepm;  */
   int k, cptcode;  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
   double *xp;    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
   double *gp, *gm;  
   double **gradg, **trgradg;    free_vector(xp,1,npar);
   double age,agelim;    free_matrix(doldm,1,nlstate,1,nlstate);
   int theta;    free_matrix(dnewm,1,nlstate,1,npar);
       free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   pstamp(ficresvpl);    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   fprintf(ficresvpl,"# Age");    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   for(i=1; i<=nlstate;i++)    fclose(ficresprobmorprev);
       fprintf(ficresvpl," %1d-%1d",i,i);    fflush(ficgp);
   fprintf(ficresvpl,"\n");    fflush(fichtm);
   }  /* end varevsij */
   xp=vector(1,npar);  
   dnewm=matrix(1,nlstate,1,npar);  /************ Variance of prevlim ******************/
   doldm=matrix(1,nlstate,1,nlstate);  void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])
     {
   hstepm=1*YEARM; /* Every year of age */    /* Variance of prevalence limit */
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */     /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
   agelim = AGESUP;    double **newm;
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    double **dnewm,**doldm;
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     int i, j, nhstepm, hstepm;
     if (stepm >= YEARM) hstepm=1;    int k, cptcode;
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */    double *xp;
     gradg=matrix(1,npar,1,nlstate);    double *gp, *gm;
     gp=vector(1,nlstate);    double **gradg, **trgradg;
     gm=vector(1,nlstate);    double age,agelim;
     int theta;
     for(theta=1; theta <=npar; theta++){   
       for(i=1; i<=npar; i++){ /* Computes gradient */    pstamp(ficresvpl);
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
       }    fprintf(ficresvpl,"# Age");
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    for(i=1; i<=nlstate;i++)
       for(i=1;i<=nlstate;i++)        fprintf(ficresvpl," %1d-%1d",i,i);
         gp[i] = prlim[i][i];    fprintf(ficresvpl,"\n");
       
       for(i=1; i<=npar; i++) /* Computes gradient */    xp=vector(1,npar);
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    dnewm=matrix(1,nlstate,1,npar);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    doldm=matrix(1,nlstate,1,nlstate);
       for(i=1;i<=nlstate;i++)   
         gm[i] = prlim[i][i];    hstepm=1*YEARM; /* Every year of age */
     hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
       for(i=1;i<=nlstate;i++)    agelim = AGESUP;
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
     } /* End theta */      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
       if (stepm >= YEARM) hstepm=1;
     trgradg =matrix(1,nlstate,1,npar);      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
       gradg=matrix(1,npar,1,nlstate);
     for(j=1; j<=nlstate;j++)      gp=vector(1,nlstate);
       for(theta=1; theta <=npar; theta++)      gm=vector(1,nlstate);
         trgradg[j][theta]=gradg[theta][j];  
       for(theta=1; theta <=npar; theta++){
     for(i=1;i<=nlstate;i++)        for(i=1; i<=npar; i++){ /* Computes gradient */
       varpl[i][(int)age] =0.;          xp[i] = x[i] + (i==theta ?delti[theta]:0);
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);        }
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
     for(i=1;i<=nlstate;i++)        for(i=1;i<=nlstate;i++)
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */          gp[i] = prlim[i][i];
      
     fprintf(ficresvpl,"%.0f ",age );        for(i=1; i<=npar; i++) /* Computes gradient */
     for(i=1; i<=nlstate;i++)          xp[i] = x[i] - (i==theta ?delti[theta]:0);
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
     fprintf(ficresvpl,"\n");        for(i=1;i<=nlstate;i++)
     free_vector(gp,1,nlstate);          gm[i] = prlim[i][i];
     free_vector(gm,1,nlstate);  
     free_matrix(gradg,1,npar,1,nlstate);        for(i=1;i<=nlstate;i++)
     free_matrix(trgradg,1,nlstate,1,npar);          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
   } /* End age */      } /* End theta */
   
   free_vector(xp,1,npar);      trgradg =matrix(1,nlstate,1,npar);
   free_matrix(doldm,1,nlstate,1,npar);  
   free_matrix(dnewm,1,nlstate,1,nlstate);      for(j=1; j<=nlstate;j++)
         for(theta=1; theta <=npar; theta++)
 }          trgradg[j][theta]=gradg[theta][j];
   
 /************ Variance of one-step probabilities  ******************/      for(i=1;i<=nlstate;i++)
 void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])        varpl[i][(int)age] =0.;
 {      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
   int i, j=0,  i1, k1, l1, t, tj;      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
   int k2, l2, j1,  z1;      for(i=1;i<=nlstate;i++)
   int k=0,l, cptcode;        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
   int first=1, first1;  
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;      fprintf(ficresvpl,"%.0f ",age );
   double **dnewm,**doldm;      for(i=1; i<=nlstate;i++)
   double *xp;        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
   double *gp, *gm;      fprintf(ficresvpl,"\n");
   double **gradg, **trgradg;      free_vector(gp,1,nlstate);
   double **mu;      free_vector(gm,1,nlstate);
   double age,agelim, cov[NCOVMAX];      free_matrix(gradg,1,npar,1,nlstate);
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */      free_matrix(trgradg,1,nlstate,1,npar);
   int theta;    } /* End age */
   char fileresprob[FILENAMELENGTH];  
   char fileresprobcov[FILENAMELENGTH];    free_vector(xp,1,npar);
   char fileresprobcor[FILENAMELENGTH];    free_matrix(doldm,1,nlstate,1,npar);
     free_matrix(dnewm,1,nlstate,1,nlstate);
   double ***varpij;  
   }
   strcpy(fileresprob,"prob");   
   strcat(fileresprob,fileres);  /************ Variance of one-step probabilities  ******************/
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {  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[])
     printf("Problem with resultfile: %s\n", fileresprob);  {
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);    int i, j=0,  i1, k1, l1, t, tj;
   }    int k2, l2, j1,  z1;
   strcpy(fileresprobcov,"probcov");     int k=0,l, cptcode;
   strcat(fileresprobcov,fileres);    int first=1, first1;
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
     printf("Problem with resultfile: %s\n", fileresprobcov);    double **dnewm,**doldm;
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);    double *xp;
   }    double *gp, *gm;
   strcpy(fileresprobcor,"probcor");     double **gradg, **trgradg;
   strcat(fileresprobcor,fileres);    double **mu;
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {    double age,agelim, cov[NCOVMAX];
     printf("Problem with resultfile: %s\n", fileresprobcor);    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);    int theta;
   }    char fileresprob[FILENAMELENGTH];
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    char fileresprobcov[FILENAMELENGTH];
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    char fileresprobcor[FILENAMELENGTH];
   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);    double ***varpij;
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);  
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    strcpy(fileresprob,"prob");
   pstamp(ficresprob);    strcat(fileresprob,fileres);
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
   fprintf(ficresprob,"# Age");      printf("Problem with resultfile: %s\n", fileresprob);
   pstamp(ficresprobcov);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");    }
   fprintf(ficresprobcov,"# Age");    strcpy(fileresprobcov,"probcov");
   pstamp(ficresprobcor);    strcat(fileresprobcov,fileres);
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
   fprintf(ficresprobcor,"# Age");      printf("Problem with resultfile: %s\n", fileresprobcov);
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
     }
   for(i=1; i<=nlstate;i++)    strcpy(fileresprobcor,"probcor");
     for(j=1; j<=(nlstate+ndeath);j++){    strcat(fileresprobcor,fileres);
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
       fprintf(ficresprobcov," p%1d-%1d ",i,j);      printf("Problem with resultfile: %s\n", fileresprobcor);
       fprintf(ficresprobcor," p%1d-%1d ",i,j);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
     }      }
  /* fprintf(ficresprob,"\n");    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(ficresprobcov,"\n");    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(ficresprobcor,"\n");    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);
  xp=vector(1,npar);    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));    pstamp(ficresprob);
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);    fprintf(ficresprob,"# Age");
   first=1;    pstamp(ficresprobcov);
   fprintf(ficgp,"\n# Routine varprob");    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");    fprintf(ficresprobcov,"# Age");
   fprintf(fichtm,"\n");    pstamp(ficresprobcor);
     fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);    fprintf(ficresprobcor,"# Age");
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\  
   file %s<br>\n",optionfilehtmcov);  
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\    for(i=1; i<=nlstate;i++)
 and drawn. It helps understanding how is the covariance between two incidences.\      for(j=1; j<=(nlstate+ndeath);j++){
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
   fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \      }  
 standard deviations wide on each axis. <br>\   /* fprintf(ficresprob,"\n");
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\    fprintf(ficresprobcov,"\n");
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\    fprintf(ficresprobcor,"\n");
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");   */
    xp=vector(1,npar);
   cov[1]=1;    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
   tj=cptcoveff;    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
   j1=0;    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
   for(t=1; t<=tj;t++){    first=1;
     for(i1=1; i1<=ncodemax[t];i1++){     fprintf(ficgp,"\n# Routine varprob");
       j1++;    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
       if  (cptcovn>0) {    fprintf(fichtm,"\n");
         fprintf(ficresprob, "\n#********** Variable ");   
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
         fprintf(ficresprob, "**********\n#\n");    fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
         fprintf(ficresprobcov, "\n#********** Variable ");     file %s<br>\n",optionfilehtmcov);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
         fprintf(ficresprobcov, "**********\n#\n");  and drawn. It helps understanding how is the covariance between two incidences.\
            They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
         fprintf(ficgp, "\n#********** Variable ");     fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
         fprintf(ficgp, "**********\n#\n");  would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
           standard deviations wide on each axis. <br>\
            Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");    and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");  
             cov[1]=1;
         fprintf(ficresprobcor, "\n#********** Variable ");        tj=cptcoveff;
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
         fprintf(ficresprobcor, "**********\n#");        j1=0;
       }    for(t=1; t<=tj;t++){
             for(i1=1; i1<=ncodemax[t];i1++){
       for (age=bage; age<=fage; age ++){         j1++;
         cov[2]=age;        if  (cptcovn>0) {
         for (k=1; k<=cptcovn;k++) {          fprintf(ficresprob, "\n#********** Variable ");
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         }          fprintf(ficresprob, "**********\n#\n");
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          fprintf(ficresprobcov, "\n#********** Variable ");
         for (k=1; k<=cptcovprod;k++)          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];          fprintf(ficresprobcov, "**********\n#\n");
                  
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));          fprintf(ficgp, "\n#********** Variable ");
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         gp=vector(1,(nlstate)*(nlstate+ndeath));          fprintf(ficgp, "**********\n#\n");
         gm=vector(1,(nlstate)*(nlstate+ndeath));         
              
         for(theta=1; theta <=npar; theta++){          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
           for(i=1; i<=npar; i++)          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                    
           pmij(pmmij,cov,ncovmodel,xp,nlstate);          fprintf(ficresprobcor, "\n#********** Variable ");    
                     for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           k=0;          fprintf(ficresprobcor, "**********\n#");    
           for(i=1; i<= (nlstate); i++){        }
             for(j=1; j<=(nlstate+ndeath);j++){       
               k=k+1;        for (age=bage; age<=fage; age ++){
               gp[k]=pmmij[i][j];          cov[2]=age;
             }          for (k=1; k<=cptcovn;k++) {
           }            cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
                     }
           for(i=1; i<=npar; i++)          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);          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]]];
           pmij(pmmij,cov,ncovmodel,xp,nlstate);         
           k=0;          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
           for(i=1; i<=(nlstate); i++){          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
             for(j=1; j<=(nlstate+ndeath);j++){          gp=vector(1,(nlstate)*(nlstate+ndeath));
               k=k+1;          gm=vector(1,(nlstate)*(nlstate+ndeath));
               gm[k]=pmmij[i][j];     
             }          for(theta=1; theta <=npar; theta++){
           }            for(i=1; i<=npar; i++)
                    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)            
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];              pmij(pmmij,cov,ncovmodel,xp,nlstate);
         }           
             k=0;
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)            for(i=1; i<= (nlstate); i++){
           for(theta=1; theta <=npar; theta++)              for(j=1; j<=(nlstate+ndeath);j++){
             trgradg[j][theta]=gradg[theta][j];                k=k+1;
                         gp[k]=pmmij[i][j];
         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));           
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));            for(i=1; i<=npar; i++)
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);     
             pmij(pmmij,cov,ncovmodel,xp,nlstate);
         pmij(pmmij,cov,ncovmodel,x,nlstate);            k=0;
                     for(i=1; i<=(nlstate); i++){
         k=0;              for(j=1; j<=(nlstate+ndeath);j++){
         for(i=1; i<=(nlstate); i++){                k=k+1;
           for(j=1; j<=(nlstate+ndeath);j++){                gm[k]=pmmij[i][j];
             k=k+1;              }
             mu[k][(int) age]=pmmij[i][j];            }
           }       
         }            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)              gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)          }
             varpij[i][j][(int)age] = doldm[i][j];  
           for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
         /*printf("\n%d ",(int)age);            for(theta=1; theta <=npar; theta++)
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){              trgradg[j][theta]=gradg[theta][j];
           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]));          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));
         fprintf(ficresprob,"\n%d ",(int)age);          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
         fprintf(ficresprobcov,"\n%d ",(int)age);          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
         fprintf(ficresprobcor,"\n%d ",(int)age);          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
   
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)          pmij(pmmij,cov,ncovmodel,x,nlstate);
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));         
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){          k=0;
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);          for(i=1; i<=(nlstate); i++){
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);            for(j=1; j<=(nlstate+ndeath);j++){
         }              k=k+1;
         i=0;              mu[k][(int) age]=pmmij[i][j];
         for (k=1; k<=(nlstate);k++){            }
           for (l=1; l<=(nlstate+ndeath);l++){           }
             i=i++;          for(i=1;i<=(nlstate)*(nlstate+ndeath);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);              varpij[i][j][(int)age] = doldm[i][j];
             for (j=1; j<=i;j++){  
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);          /*printf("\n%d ",(int)age);
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));            for (i=1; i<=(nlstate)*(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]));
         }/* end of loop for state */            }*/
       } /* end of loop for age */  
           fprintf(ficresprob,"\n%d ",(int)age);
       /* Confidence intervalle of pij  */          fprintf(ficresprobcov,"\n%d ",(int)age);
       /*          fprintf(ficresprobcor,"\n%d ",(int)age);
         fprintf(ficgp,"\nset noparametric;unset label");  
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
         fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);          }
       */          i=0;
           for (k=1; k<=(nlstate);k++){
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/            for (l=1; l<=(nlstate+ndeath);l++){
       first1=1;              i=i++;
       for (k2=1; k2<=(nlstate);k2++){              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
         for (l2=1; l2<=(nlstate+ndeath);l2++){               fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
           if(l2==k2) continue;              for (j=1; j<=i;j++){
           j=(k2-1)*(nlstate+ndeath)+l2;                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
           for (k1=1; k1<=(nlstate);k1++){                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
             for (l1=1; l1<=(nlstate+ndeath);l1++){               }
               if(l1==k1) continue;            }
               i=(k1-1)*(nlstate+ndeath)+l1;          }/* end of loop for state */
               if(i<=j) continue;        } /* end of loop for age */
               for (age=bage; age<=fage; age ++){   
                 if ((int)age %5==0){        /* Confidence intervalle of pij  */
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;        /*
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;          fprintf(ficgp,"\nset noparametric;unset label");
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   mu1=mu[i][(int) age]/stepm*YEARM ;          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   mu2=mu[j][(int) age]/stepm*YEARM;          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);
                   c12=cv12/sqrt(v1*v2);          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   /* Computing eigen value of matrix of covariance */          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;        */
                   /* Eigen vectors */  
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   /*v21=sqrt(1.-v11*v11); *//* error */        first1=1;
                   v21=(lc1-v1)/cv12*v11;        for (k2=1; k2<=(nlstate);k2++){
                   v12=-v21;          for (l2=1; l2<=(nlstate+ndeath);l2++){
                   v22=v11;            if(l2==k2) continue;
                   tnalp=v21/v11;            j=(k2-1)*(nlstate+ndeath)+l2;
                   if(first1==1){            for (k1=1; k1<=(nlstate);k1++){
                     first1=0;              for (l1=1; l1<=(nlstate+ndeath);l1++){
                     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);                if(l1==k1) continue;
                   }                i=(k1-1)*(nlstate+ndeath)+l1;
                   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);                if(i<=j) continue;
                   /*printf(fignu*/                for (age=bage; age<=fage; age ++){
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */                  if ((int)age %5==0){
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   if(first==1){                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                     first=0;                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                     fprintf(ficgp,"\nset parametric;unset label");                    mu1=mu[i][(int) age]/stepm*YEARM ;
                     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);                    mu2=mu[j][(int) age]/stepm*YEARM;
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");                    c12=cv12/sqrt(v1*v2);
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\                    /* Computing eigen value of matrix of covariance */
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\                    /* Eigen vectors */
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    /*v21=sqrt(1.-v11*v11); *//* error */
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);                    v21=(lc1-v1)/cv12*v11;
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    v12=-v21;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                    v22=v11;
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                    tnalp=v21/v11;
                     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(first1==1){
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                      first1=0;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                      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);
                   }else{                    }
                     first=0;                    fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);                    /*printf(fignu*/
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                     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",\                    if(first==1){
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                      first=0;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                      fprintf(ficgp,"\nset parametric;unset label");
                   }/* if first */                      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);
                 } /* age mod 5 */                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
               } /* end loop age */                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
               first=1;  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
             } /*l12 */                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
           } /* k12 */                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
         } /*l1 */                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
       }/* k1 */                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
     } /* loop covariates */                      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   }                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);                      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",\
   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
   free_vector(xp,1,npar);                    }else{
   fclose(ficresprob);                      first=0;
   fclose(ficresprobcov);                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
   fclose(ficresprobcor);                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
   fflush(ficgp);                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
   fflush(fichtmcov);                      fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
 }                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                               mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                     }/* if first */
 /******************* Printing html file ***********/                  } /* age mod 5 */
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \                } /* end loop age */
                   int lastpass, int stepm, int weightopt, char model[],\                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\                first=1;
                   int popforecast, int estepm ,\              } /*l12 */
                   double jprev1, double mprev1,double anprev1, \            } /* k12 */
                   double jprev2, double mprev2,double anprev2){          } /*l1 */
   int jj1, k1, i1, cpt;        }/* k1 */
       } /* loop covariates */
    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \    }
    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 </ul>");    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));    free_vector(xp,1,npar);
    fprintf(fichtm,"\    fclose(ficresprob);
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",    fclose(ficresprobcov);
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));    fclose(ficresprobcor);
    fprintf(fichtm,"\    fflush(ficgp);
  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",    fflush(fichtmcov);
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));  }
    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): \  
    <a href=\"%s\">%s</a> <br>\n</li>",  /******************* Printing html file ***********/
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                     int lastpass, int stepm, int weightopt, char model[],\
                     int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");                    int popforecast, int estepm ,\
                     double jprev1, double mprev1,double anprev1, \
  m=cptcoveff;                    double jprev2, double mprev2,double anprev2){
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}    int jj1, k1, i1, cpt;
   
  jj1=0;     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
  for(k1=1; k1<=m;k1++){     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
    for(i1=1; i1<=ncodemax[k1];i1++){  </ul>");
      jj1++;     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
      if (cptcovn > 0) {   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
        for (cpt=1; cpt<=cptcoveff;cpt++)      fprintf(fichtm,"\
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
      }     fprintf(fichtm,"\
      /* Pij */   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);          fprintf(fichtm,"\
      /* Quasi-incidences */   - (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,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\     <a href=\"%s\">%s</a> <br>\n",
  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> \             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);      fprintf(fichtm,"\
        /* Period (stable) prevalence in each health state */   - Population projections by age and states: \
        for(cpt=1; cpt<nlstate;cpt++){     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
          fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \  
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
        }  
      for(cpt=1; cpt<=nlstate;cpt++) {   m=cptcoveff;
         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);  
      }   jj1=0;
    } /* end i1 */   for(k1=1; k1<=m;k1++){
  }/* End k1 */     for(i1=1; i1<=ncodemax[k1];i1++){
  fprintf(fichtm,"</ul>");       jj1++;
        if (cptcovn > 0) {
          fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
  fprintf(fichtm,"\         for (cpt=1; cpt<=cptcoveff;cpt++)
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        }
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",       /* Pij */
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));       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);    
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",       /* Quasi-incidences */
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));       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> \
  fprintf(fichtm,"\  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",         /* Period (stable) prevalence in each health state */
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));         for(cpt=1; cpt<nlstate;cpt++){
  fprintf(fichtm,"\           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
  - 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): \  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
    <a href=\"%s\">%s</a> <br>\n</li>",         }
            estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));       for(cpt=1; cpt<=nlstate;cpt++) {
  fprintf(fichtm,"\          fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
  - (a) 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): \  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
    <a href=\"%s\">%s</a> <br>\n</li>",       }
            estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));     } /* end i1 */
  fprintf(fichtm,"\   }/* End k1 */
  - 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,"</ul>");
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));  
  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",   fprintf(fichtm,"\
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
  fprintf(fichtm,"\   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\  
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
            subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 /*  if(popforecast==1) fprintf(fichtm,"\n */   fprintf(fichtm,"\
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 /*      <br>",fileres,fileres,fileres,fileres); */  
 /*  else  */   fprintf(fichtm,"\
 /*    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); */   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
  fflush(fichtm);           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");   fprintf(fichtm,"\
    - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
  m=cptcoveff;     <a href=\"%s\">%s</a> <br>\n</li>",
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
    fprintf(fichtm,"\
  jj1=0;   - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \
  for(k1=1; k1<=m;k1++){     <a href=\"%s\">%s</a> <br>\n</li>",
    for(i1=1; i1<=ncodemax[k1];i1++){             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
      jj1++;   fprintf(fichtm,"\
      if (cptcovn > 0) {   - 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,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");           estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
        for (cpt=1; cpt<=cptcoveff;cpt++)    fprintf(fichtm,"\
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);   - 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",
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");           subdirf2(fileres,"t"),subdirf2(fileres,"t"));
      }   fprintf(fichtm,"\
      for(cpt=1; cpt<=nlstate;cpt++) {   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 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);    /*  if(popforecast==1) fprintf(fichtm,"\n */
      }  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 health expectancies in states (1) and (2): %s%d.png<br>\  /*      <br>",fileres,fileres,fileres,fileres); */
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);  /*  else  */
    } /* end i1 */  /*    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); */
  }/* End k1 */   fflush(fichtm);
  fprintf(fichtm,"</ul>");   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
  fflush(fichtm);  
 }   m=cptcoveff;
    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 /******************* Gnuplot file **************/  
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){   jj1=0;
    for(k1=1; k1<=m;k1++){
   char dirfileres[132],optfileres[132];     for(i1=1; i1<=ncodemax[k1];i1++){
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;       jj1++;
   int ng;       if (cptcovn > 0) {
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 /*     printf("Problem with file %s",optionfilegnuplot); */         for (cpt=1; cpt<=cptcoveff;cpt++)
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 /*   } */         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        }
   /*#ifdef windows */       for(cpt=1; cpt<=nlstate;cpt++) {
   fprintf(ficgp,"cd \"%s\" \n",pathc);         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
     /*#endif */  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
   m=pow(2,cptcoveff);  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
        }
   strcpy(dirfileres,optionfilefiname);       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
   strcpy(optfileres,"vpl");  health expectancies in states (1) and (2): %s%d.png<br>\
  /* 1eme*/  <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
   for (cpt=1; cpt<= nlstate ; cpt ++) {     } /* end i1 */
    for (k1=1; k1<= m ; k1 ++) {   }/* End k1 */
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);   fprintf(fichtm,"</ul>");
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);   fflush(fichtm);
      fprintf(ficgp,"set xlabel \"Age\" \n\  }
 set ylabel \"Probability\" \n\  
 set ter png small\n\  /******************* Gnuplot file **************/
 set size 0.65,0.65\n\  void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);  
     char dirfileres[132],optfileres[132];
      for (i=1; i<= nlstate ; i ++) {    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");    int ng;
        else fprintf(ficgp," \%%*lf (\%%*lf)");  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
      }  /*     printf("Problem with file %s",optionfilegnuplot); */
      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(ficlog,"Problem with file %s",optionfilegnuplot); */
      for (i=1; i<= nlstate ; i ++) {  /*   } */
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");  
        else fprintf(ficgp," \%%*lf (\%%*lf)");    /*#ifdef windows */
      }     fprintf(ficgp,"cd \"%s\" \n",pathc);
      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);       /*#endif */
      for (i=1; i<= nlstate ; i ++) {    m=pow(2,cptcoveff);
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");  
        else fprintf(ficgp," \%%*lf (\%%*lf)");    strcpy(dirfileres,optionfilefiname);
      }      strcpy(optfileres,"vpl");
      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));   /* 1eme*/
    }    for (cpt=1; cpt<= nlstate ; cpt ++) {
   }     for (k1=1; k1<= m ; k1 ++) {
   /*2 eme*/       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);
   for (k1=1; k1<= m ; k1 ++) {        fprintf(ficgp,"set xlabel \"Age\" \n\
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);  set ylabel \"Probability\" \n\
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);  set ter png small\n\
       set size 0.65,0.65\n\
     for (i=1; i<= nlstate+1 ; i ++) {  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
       k=2*i;  
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);       for (i=1; i<= nlstate ; i ++) {
       for (j=1; j<= nlstate+1 ; j ++) {         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");         else fprintf(ficgp," \%%*lf (\%%*lf)");
         else fprintf(ficgp," \%%*lf (\%%*lf)");       }
       }          fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");       for (i=1; i<= nlstate ; i ++) {
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);         else fprintf(ficgp," \%%*lf (\%%*lf)");
       for (j=1; j<= nlstate+1 ; j ++) {       }
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");       fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
         else fprintf(ficgp," \%%*lf (\%%*lf)");       for (i=1; i<= nlstate ; i ++) {
       }            if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficgp,"\" t\"\" w l 0,");         else fprintf(ficgp," \%%*lf (\%%*lf)");
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);       }  
       for (j=1; j<= nlstate+1 ; j ++) {       fprintf(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));
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");     }
         else fprintf(ficgp," \%%*lf (\%%*lf)");    }
       }       /*2 eme*/
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");   
       else fprintf(ficgp,"\" t\"\" w l 0,");    for (k1=1; k1<= m ; k1 ++) {
     }      fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
   }      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
        
   /*3eme*/      for (i=1; i<= nlstate+1 ; i ++) {
           k=2*i;
   for (k1=1; k1<= m ; k1 ++) {         fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
     for (cpt=1; cpt<= nlstate ; cpt ++) {        for (j=1; j<= nlstate+1 ; j ++) {
       /*       k=2+nlstate*(2*cpt-2); */          if (j==i) 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\        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 set size 0.65,0.65\n\        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 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,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);        for (j=1; j<= nlstate+1 ; j ++) {
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);          else 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);        }  
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");        fprintf(ficgp,"\" t\"\" w l 0,");
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                 for (j=1; j<= nlstate+1 ; j ++) {
       */          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       for (i=1; i< nlstate ; i ++) {          else fprintf(ficgp," \%%*lf (\%%*lf)");
         fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);        }  
         /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
                 else fprintf(ficgp,"\" t\"\" w l 0,");
       }       }
       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);    }
     }   
   }    /*3eme*/
      
   /* CV preval stable (period) */    for (k1=1; k1<= m ; k1 ++) {
   for (k1=1; k1<= m ; k1 ++) {       for (cpt=1; cpt<= nlstate ; cpt ++) {
     for (cpt=1; cpt<=nlstate ; cpt ++) {        /*       k=2+nlstate*(2*cpt-2); */
       k=3;        k=2+(nlstate+1)*(cpt-1);
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\        fprintf(ficgp,"set ter png small\n\
 set ter png small\nset size 0.65,0.65\n\  set size 0.65,0.65\n\
 unset log y\n\  plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
 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,",\"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) ");
       for (i=1; i< nlstate ; i ++)          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
         fprintf(ficgp,"+$%d",k+i+1);          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                 fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
       l=3+(nlstate+ndeath)*cpt;         
       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 ++) {        for (i=1; i< nlstate ; i ++) {
         l=3+(nlstate+ndeath)*cpt;          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,"+$%d",l+i+1);          /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/
       }         
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);           }
     }         fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
   }        }
       }
   /* proba elementaires */   
   for(i=1,jk=1; i <=nlstate; i++){    /* CV preval stable (period) */
     for(k=1; k <=(nlstate+ndeath); k++){    for (k1=1; k1<= m ; k1 ++) {
       if (k != i) {      for (cpt=1; cpt<=nlstate ; cpt ++) {
         for(j=1; j <=ncovmodel; j++){        k=3;
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
           jk++;         fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
           fprintf(ficgp,"\n");  set ter png small\nset size 0.65,0.65\n\
         }  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);
     }       
    }        for (i=1; i< nlstate ; i ++)
           fprintf(ficgp,"+$%d",k+i+1);
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
      for(jk=1; jk <=m; jk++) {       
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);         l=3+(nlstate+ndeath)*cpt;
        if (ng==2)        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");        for (i=1; i< nlstate ; i ++) {
        else          l=3+(nlstate+ndeath)*cpt;
          fprintf(ficgp,"\nset title \"Probability\"\n");          fprintf(ficgp,"+$%d",l+i+1);
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);        }
        i=1;        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
        for(k2=1; k2<=nlstate; k2++) {      }
          k3=i;    }  
          for(k=1; k<=(nlstate+ndeath); k++) {   
            if (k != k2){    /* proba elementaires */
              if(ng==2)    for(i=1,jk=1; i <=nlstate; i++){
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);      for(k=1; k <=(nlstate+ndeath); k++){
              else        if (k != i) {
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);          for(j=1; j <=ncovmodel; j++){
              ij=1;            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
              for(j=3; j <=ncovmodel; j++) {            jk++;
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {            fprintf(ficgp,"\n");
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);          }
                  ij++;        }
                }      }
                else     }
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);  
              }     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
              fprintf(ficgp,")/(1");       for(jk=1; jk <=m; jk++) {
                       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
              for(k1=1; k1 <=nlstate; k1++){            if (ng==2)
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                ij=1;         else
                for(j=3; j <=ncovmodel; j++){           fprintf(ficgp,"\nset title \"Probability\"\n");
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);         i=1;
                    ij++;         for(k2=1; k2<=nlstate; k2++) {
                  }           k3=i;
                  else           for(k=1; k<=(nlstate+ndeath); k++) {
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);             if (k != k2){
                }               if(ng==2)
                fprintf(ficgp,")");                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
              }               else
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");               ij=1;
              i=i+ncovmodel;               for(j=3; j <=ncovmodel; j++) {
            }                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
          } /* end k */                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
        } /* end k2 */                   ij++;
      } /* end jk */                 }
    } /* end ng */                 else
    fflush(ficgp);                    fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 }  /* end gnuplot */               }
                fprintf(ficgp,")/(1");
                
 /*************** Moving average **************/               for(k1=1; k1 <=nlstate; k1++){  
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                  ij=1;
   int i, cpt, cptcod;                 for(j=3; j <=ncovmodel; j++){
   int modcovmax =1;                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
   int mobilavrange, mob;                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
   double age;                     ij++;
                    }
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose                    else
                            a covariate has 2 modalities */                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */                 }
                  fprintf(ficgp,")");
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){               }
     if(mobilav==1) mobilavrange=5; /* default */               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
     else mobilavrange=mobilav;               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
     for (age=bage; age<=fage; age++)               i=i+ncovmodel;
       for (i=1; i<=nlstate;i++)             }
         for (cptcod=1;cptcod<=modcovmax;cptcod++)           } /* end k */
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];         } /* end k2 */
     /* We keep the original values on the extreme ages bage, fage and for        } /* end jk */
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2     } /* end ng */
        we use a 5 terms etc. until the borders are no more concerned.      fflush(ficgp);
     */   }  /* end gnuplot */
     for (mob=3;mob <=mobilavrange;mob=mob+2){  
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){  
         for (i=1; i<=nlstate;i++){  /*************** Moving average **************/
           for (cptcod=1;cptcod<=modcovmax;cptcod++){  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];  
               for (cpt=1;cpt<=(mob-1)/2;cpt++){    int i, cpt, cptcod;
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];    int modcovmax =1;
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];    int mobilavrange, mob;
               }    double age;
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;  
           }    modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
         }                             a covariate has 2 modalities */
       }/* end age */    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
     }/* end mob */  
   }else return -1;    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
   return 0;      if(mobilav==1) mobilavrange=5; /* default */
 }/* End movingaverage */      else mobilavrange=mobilav;
       for (age=bage; age<=fage; age++)
         for (i=1; i<=nlstate;i++)
 /************** Forecasting ******************/          for (cptcod=1;cptcod<=modcovmax;cptcod++)
 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){            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
   /* proj1, year, month, day of starting projection       /* We keep the original values on the extreme ages bage, fage and for
      agemin, agemax range of age         fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
      dateprev1 dateprev2 range of dates during which prevalence is computed         we use a 5 terms etc. until the borders are no more concerned.
      anproj2 year of en of projection (same day and month as proj1).      */
   */      for (mob=3;mob <=mobilavrange;mob=mob+2){
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
   int *popage;          for (i=1; i<=nlstate;i++){
   double agec; /* generic age */            for (cptcod=1;cptcod<=modcovmax;cptcod++){
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
   double *popeffectif,*popcount;                for (cpt=1;cpt<=(mob-1)/2;cpt++){
   double ***p3mat;                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
   double ***mobaverage;                  mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
   char fileresf[FILENAMELENGTH];                }
               mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
   agelim=AGESUP;            }
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);          }
          }/* end age */
   strcpy(fileresf,"f");       }/* end mob */
   strcat(fileresf,fileres);    }else return -1;
   if((ficresf=fopen(fileresf,"w"))==NULL) {    return 0;
     printf("Problem with forecast resultfile: %s\n", fileresf);  }/* End movingaverage */
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);  
   }  
   printf("Computing forecasting: result on file '%s' \n", fileresf);  /************** Forecasting ******************/
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);  prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
     /* proj1, year, month, day of starting projection
   if (cptcoveff==0) ncodemax[cptcoveff]=1;       agemin, agemax range of age
        dateprev1 dateprev2 range of dates during which prevalence is computed
   if (mobilav!=0) {       anproj2 year of en of projection (same day and month as proj1).
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    */
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    int *popage;
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    double agec; /* generic age */
     }    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
   }    double *popeffectif,*popcount;
     double ***p3mat;
   stepsize=(int) (stepm+YEARM-1)/YEARM;    double ***mobaverage;
   if (stepm<=12) stepsize=1;    char fileresf[FILENAMELENGTH];
   if(estepm < stepm){  
     printf ("Problem %d lower than %d\n",estepm, stepm);    agelim=AGESUP;
   }    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
   else  hstepm=estepm;      
     strcpy(fileresf,"f");
   hstepm=hstepm/stepm;     strcat(fileresf,fileres);
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and    if((ficresf=fopen(fileresf,"w"))==NULL) {
                                fractional in yp1 */      printf("Problem with forecast resultfile: %s\n", fileresf);
   anprojmean=yp;      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
   yp2=modf((yp1*12),&yp);    }
   mprojmean=yp;    printf("Computing forecasting: result on file '%s' \n", fileresf);
   yp1=modf((yp2*30.5),&yp);    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
   jprojmean=yp;  
   if(jprojmean==0) jprojmean=1;    if (cptcoveff==0) ncodemax[cptcoveff]=1;
   if(mprojmean==0) jprojmean=1;  
     if (mobilav!=0) {
   i1=cptcoveff;      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if (cptcovn < 1){i1=1;}      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
           fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);         printf(" Error in movingaverage mobilav=%d\n",mobilav);
         }
   fprintf(ficresf,"#****** Routine prevforecast **\n");    }
   
 /*            if (h==(int)(YEARM*yearp)){ */    stepsize=(int) (stepm+YEARM-1)/YEARM;
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){    if (stepm<=12) stepsize=1;
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    if(estepm < stepm){
       k=k+1;      printf ("Problem %d lower than %d\n",estepm, stepm);
       fprintf(ficresf,"\n#******");    }
       for(j=1;j<=cptcoveff;j++) {    else  hstepm=estepm;  
         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]]);  
       }    hstepm=hstepm/stepm;
       fprintf(ficresf,"******\n");    yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");                                 fractional in yp1 */
       for(j=1; j<=nlstate+ndeath;j++){     anprojmean=yp;
         for(i=1; i<=nlstate;i++)                  yp2=modf((yp1*12),&yp);
           fprintf(ficresf," p%d%d",i,j);    mprojmean=yp;
         fprintf(ficresf," p.%d",j);    yp1=modf((yp2*30.5),&yp);
       }    jprojmean=yp;
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {     if(jprojmean==0) jprojmean=1;
         fprintf(ficresf,"\n");    if(mprojmean==0) jprojmean=1;
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);     
     i1=cptcoveff;
         for (agec=fage; agec>=(ageminpar-1); agec--){     if (cptcovn < 1){i1=1;}
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);    
           nhstepm = nhstepm/hstepm;     fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);   
           oldm=oldms;savm=savms;    fprintf(ficresf,"#****** Routine prevforecast **\n");
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);    
           /*            if (h==(int)(YEARM*yearp)){ */
           for (h=0; h<=nhstepm; h++){    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
             if (h*hstepm/YEARM*stepm ==yearp) {      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
               fprintf(ficresf,"\n");        k=k+1;
               for(j=1;j<=cptcoveff;j++)         fprintf(ficresf,"\n#******");
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        for(j=1;j<=cptcoveff;j++) {
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);          fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
             }         }
             for(j=1; j<=nlstate+ndeath;j++) {        fprintf(ficresf,"******\n");
               ppij=0.;        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
               for(i=1; i<=nlstate;i++) {        for(j=1; j<=nlstate+ndeath;j++){
                 if (mobilav==1)           for(i=1; i<=nlstate;i++)              
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];            fprintf(ficresf," p%d%d",i,j);
                 else {          fprintf(ficresf," p.%d",j);
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];        }
                 }        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                 if (h*hstepm/YEARM*stepm== yearp) {          fprintf(ficresf,"\n");
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
                 }  
               } /* end i */          for (agec=fage; agec>=(ageminpar-1); agec--){
               if (h*hstepm/YEARM*stepm==yearp) {            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
                 fprintf(ficresf," %.3f", ppij);            nhstepm = nhstepm/hstepm;
               }            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             }/* end j */            oldm=oldms;savm=savms;
           } /* end h */            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);         
         } /* end agec */            for (h=0; h<=nhstepm; h++){
       } /* end yearp */              if (h*hstepm/YEARM*stepm ==yearp) {
     } /* end cptcod */                fprintf(ficresf,"\n");
   } /* end  cptcov */                for(j=1;j<=cptcoveff;j++)
                          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
               }
   fclose(ficresf);              for(j=1; j<=nlstate+ndeath;j++) {
 }                ppij=0.;
                 for(i=1; i<=nlstate;i++) {
 /************** Forecasting *****not tested NB*************/                  if (mobilav==1)
 populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                     else {
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
   int *popage;                  }
   double calagedatem, agelim, kk1, kk2;                  if (h*hstepm/YEARM*stepm== yearp) {
   double *popeffectif,*popcount;                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
   double ***p3mat,***tabpop,***tabpopprev;                  }
   double ***mobaverage;                } /* end i */
   char filerespop[FILENAMELENGTH];                if (h*hstepm/YEARM*stepm==yearp) {
                   fprintf(ficresf," %.3f", ppij);
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                }
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);              }/* end j */
   agelim=AGESUP;            } /* end h */
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             } /* end agec */
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);        } /* end yearp */
         } /* end cptcod */
       } /* end  cptcov */
   strcpy(filerespop,"pop");          
   strcat(filerespop,fileres);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if((ficrespop=fopen(filerespop,"w"))==NULL) {  
     printf("Problem with forecast resultfile: %s\n", filerespop);    fclose(ficresf);
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);  }
   }  
   printf("Computing forecasting: result on file '%s' \n", filerespop);  /************** Forecasting *****not tested NB*************/
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);  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){
    
   if (cptcoveff==0) ncodemax[cptcoveff]=1;    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
     int *popage;
   if (mobilav!=0) {    double calagedatem, agelim, kk1, kk2;
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    double *popeffectif,*popcount;
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){    double ***p3mat,***tabpop,***tabpopprev;
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    double ***mobaverage;
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    char filerespop[FILENAMELENGTH];
     }  
   }    tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   stepsize=(int) (stepm+YEARM-1)/YEARM;    agelim=AGESUP;
   if (stepm<=12) stepsize=1;    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
      
   agelim=AGESUP;    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
      
   hstepm=1;   
   hstepm=hstepm/stepm;     strcpy(filerespop,"pop");
       strcat(filerespop,fileres);
   if (popforecast==1) {    if((ficrespop=fopen(filerespop,"w"))==NULL) {
     if((ficpop=fopen(popfile,"r"))==NULL) {      printf("Problem with forecast resultfile: %s\n", filerespop);
       printf("Problem with population file : %s\n",popfile);exit(0);      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);    }
     }     printf("Computing forecasting: result on file '%s' \n", filerespop);
     popage=ivector(0,AGESUP);    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
     popeffectif=vector(0,AGESUP);  
     popcount=vector(0,AGESUP);    if (cptcoveff==0) ncodemax[cptcoveff]=1;
       
     i=1;       if (mobilav!=0) {
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
          if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
     imx=i;        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   }      }
     }
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){  
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    stepsize=(int) (stepm+YEARM-1)/YEARM;
       k=k+1;    if (stepm<=12) stepsize=1;
       fprintf(ficrespop,"\n#******");   
       for(j=1;j<=cptcoveff;j++) {    agelim=AGESUP;
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);   
       }    hstepm=1;
       fprintf(ficrespop,"******\n");    hstepm=hstepm/stepm;
       fprintf(ficrespop,"# Age");   
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);    if (popforecast==1) {
       if (popforecast==1)  fprintf(ficrespop," [Population]");      if((ficpop=fopen(popfile,"r"))==NULL) {
               printf("Problem with population file : %s\n",popfile);exit(0);
       for (cpt=0; cpt<=0;cpt++) {         fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);         }
               popage=ivector(0,AGESUP);
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){       popeffectif=vector(0,AGESUP);
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);       popcount=vector(0,AGESUP);
           nhstepm = nhstepm/hstepm;      
                 i=1;  
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
           oldm=oldms;savm=savms;     
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        imx=i;
               for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
           for (h=0; h<=nhstepm; h++){    }
             if (h==(int) (calagedatem+YEARM*cpt)) {  
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);    for(cptcov=1,k=0;cptcov<=i2;cptcov++){
             }      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
             for(j=1; j<=nlstate+ndeath;j++) {        k=k+1;
               kk1=0.;kk2=0;        fprintf(ficrespop,"\n#******");
               for(i=1; i<=nlstate;i++) {                      for(j=1;j<=cptcoveff;j++) {
                 if (mobilav==1)           fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];        }
                 else {        fprintf(ficrespop,"******\n");
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];        fprintf(ficrespop,"# Age");
                 }        for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
               }        if (popforecast==1)  fprintf(ficrespop," [Population]");
               if (h==(int)(calagedatem+12*cpt)){       
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;        for (cpt=0; cpt<=0;cpt++) {
                   /*fprintf(ficrespop," %.3f", kk1);          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/         
               }          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
             }            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
             for(i=1; i<=nlstate;i++){            nhstepm = nhstepm/hstepm;
               kk1=0.;           
                 for(j=1; j<=nlstate;j++){            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];             oldm=oldms;savm=savms;
                 }            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];         
             }            for (h=0; h<=nhstepm; h++){
               if (h==(int) (calagedatem+YEARM*cpt)) {
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)                 fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);              }
           }              for(j=1; j<=nlstate+ndeath;j++) {
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                kk1=0.;kk2=0;
         }                for(i=1; i<=nlstate;i++) {              
       }                  if (mobilav==1)
                      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];
       for (cpt=1; cpt<=(anpyram1-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--){                 if (h==(int)(calagedatem+12*cpt)){
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);                   tabpop[(int)(agedeb)][j][cptcod]=kk1;
           nhstepm = nhstepm/hstepm;                     /*fprintf(ficrespop," %.3f", kk1);
                                 if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                }
           oldm=oldms;savm=savms;              }
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);                for(i=1; i<=nlstate;i++){
           for (h=0; h<=nhstepm; h++){                kk1=0.;
             if (h==(int) (calagedatem+YEARM*cpt)) {                  for(j=1; j<=nlstate;j++){
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
             }                   }
             for(j=1; j<=nlstate+ndeath;j++) {                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
               kk1=0.;kk2=0;              }
               for(i=1; i<=nlstate;i++) {                
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];                  if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
               }                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                    }
             }            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           }          }
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        }
         }   
       }    /******/
    }   
   }        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
            fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
   if (popforecast==1) {            nhstepm = nhstepm/hstepm;
     free_ivector(popage,0,AGESUP);           
     free_vector(popeffectif,0,AGESUP);            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     free_vector(popcount,0,AGESUP);            oldm=oldms;savm=savms;
   }            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            for (h=0; h<=nhstepm; h++){
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);              if (h==(int) (calagedatem+YEARM*cpt)) {
   fclose(ficrespop);                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 } /* End of popforecast */              }
               for(j=1; j<=nlstate+ndeath;j++) {
 int fileappend(FILE *fichier, char *optionfich)                kk1=0.;kk2=0;
 {                for(i=1; i<=nlstate;i++) {              
   if((fichier=fopen(optionfich,"a"))==NULL) {                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
     printf("Problem with file: %s\n", optionfich);                }
     fprintf(ficlog,"Problem with file: %s\n", optionfich);                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
     return (0);              }
   }            }
   fflush(fichier);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   return (1);          }
 }        }
      }
     }
 /**************** function prwizard **********************/   
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 {  
     if (popforecast==1) {
   /* Wizard to print covariance matrix template */      free_ivector(popage,0,AGESUP);
       free_vector(popeffectif,0,AGESUP);
   char ca[32], cb[32], cc[32];      free_vector(popcount,0,AGESUP);
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;    }
   int numlinepar;    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    fclose(ficrespop);
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");  } /* 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);
       /*ca[0]= k+'a'-1;ca[1]='\0';*/      fprintf(ficlog,"Problem with file: %s\n", optionfich);
       printf("%1d%1d",i,j);      return (0);
       fprintf(ficparo,"%1d%1d",i,j);    }
       for(k=1; k<=ncovmodel;k++){    fflush(fichier);
         /*        printf(" %lf",param[i][j][k]); */    return (1);
         /*        fprintf(ficparo," %lf",param[i][j][k]); */  }
         printf(" 0.");  
         fprintf(ficparo," 0.");  
       }  /**************** function prwizard **********************/
       printf("\n");  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
       fprintf(ficparo,"\n");  {
     }  
   }    /* Wizard to print covariance matrix template */
   printf("# Scales (for hessian or gradient estimation)\n");  
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");    char ca[32], cb[32], cc[32];
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/     int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
   for(i=1; i <=nlstate; i++){    int numlinepar;
     jj=0;  
     for(j=1; j <=nlstate+ndeath; j++){    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       if(j==i) continue;    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       jj++;    for(i=1; i <=nlstate; i++){
       fprintf(ficparo,"%1d%1d",i,j);      jj=0;
       printf("%1d%1d",i,j);      for(j=1; j <=nlstate+ndeath; j++){
       fflush(stdout);        if(j==i) continue;
       for(k=1; k<=ncovmodel;k++){        jj++;
         /*      printf(" %le",delti3[i][j][k]); */        /*ca[0]= k+'a'-1;ca[1]='\0';*/
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */        printf("%1d%1d",i,j);
         printf(" 0.");        fprintf(ficparo,"%1d%1d",i,j);
         fprintf(ficparo," 0.");        for(k=1; k<=ncovmodel;k++){
       }          /*        printf(" %lf",param[i][j][k]); */
       numlinepar++;          /*        fprintf(ficparo," %lf",param[i][j][k]); */
       printf("\n");          printf(" 0.");
       fprintf(ficparo,"\n");          fprintf(ficparo," 0.");
     }        }
   }        printf("\n");
   printf("# Covariance matrix\n");        fprintf(ficparo,"\n");
 /* # 121 Var(a12)\n\ */      }
 /* # 122 Cov(b12,a12) Var(b12)\n\ */    }
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */    printf("# Scales (for hessian or gradient estimation)\n");
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
 /* # 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\ */        fprintf(ficparo,"%1d%1d",i,j);
   /* # 122 Cov(b12,a12) Var(b12)\n\ */        printf("%1d%1d",i,j);
   /* #   ...\n\ */        fflush(stdout);
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */        for(k=1; k<=ncovmodel;k++){
             /*      printf(" %le",delti3[i][j][k]); */
   for(itimes=1;itimes<=2;itimes++){          /*      fprintf(ficparo," %le",delti3[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;        numlinepar++;
         for(k=1; k<=ncovmodel;k++){        printf("\n");
           jj++;        fprintf(ficparo,"\n");
           ca[0]= k+'a'-1;ca[1]='\0';      }
           if(itimes==1){    }
             printf("#%1d%1d%d",i,j,k);    printf("# Covariance matrix\n");
             fprintf(ficparo,"#%1d%1d%d",i,j,k);  /* # 121 Var(a12)\n\ */
           }else{  /* # 122 Cov(b12,a12) Var(b12)\n\ */
             printf("%1d%1d%d",i,j,k);  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
             fprintf(ficparo,"%1d%1d%d",i,j,k);  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
             /*  printf(" %.5le",matcov[i][j]); */  /* # 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\ */
           ll=0;  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
           for(li=1;li <=nlstate; li++){  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
             for(lj=1;lj <=nlstate+ndeath; lj++){    fflush(stdout);
               if(lj==li) continue;    fprintf(ficparo,"# Covariance matrix\n");
               for(lk=1;lk<=ncovmodel;lk++){    /* # 121 Var(a12)\n\ */
                 ll++;    /* # 122 Cov(b12,a12) Var(b12)\n\ */
                 if(ll<=jj){    /* #   ...\n\ */
                   cb[0]= lk +'a'-1;cb[1]='\0';    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   if(ll<jj){   
                     if(itimes==1){    for(itimes=1;itimes<=2;itimes++){
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      jj=0;
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      for(i=1; i <=nlstate; i++){
                     }else{        for(j=1; j <=nlstate+ndeath; j++){
                       printf(" 0.");          if(j==i) continue;
                       fprintf(ficparo," 0.");          for(k=1; k<=ncovmodel;k++){
                     }            jj++;
                   }else{            ca[0]= k+'a'-1;ca[1]='\0';
                     if(itimes==1){            if(itimes==1){
                       printf(" Var(%s%1d%1d)",ca,i,j);              printf("#%1d%1d%d",i,j,k);
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);              fprintf(ficparo,"#%1d%1d%d",i,j,k);
                     }else{            }else{
                       printf(" 0.");              printf("%1d%1d%d",i,j,k);
                       fprintf(ficparo," 0.");              fprintf(ficparo,"%1d%1d%d",i,j,k);
                     }              /*  printf(" %.5le",matcov[i][j]); */
                   }            }
                 }            ll=0;
               } /* end lk */            for(li=1;li <=nlstate; li++){
             } /* end lj */              for(lj=1;lj <=nlstate+ndeath; lj++){
           } /* end li */                if(lj==li) continue;
           printf("\n");                for(lk=1;lk<=ncovmodel;lk++){
           fprintf(ficparo,"\n");                  ll++;
           numlinepar++;                  if(ll<=jj){
         } /* end k*/                    cb[0]= lk +'a'-1;cb[1]='\0';
       } /*end j */                    if(ll<jj){
     } /* end i */                      if(itimes==1){
   } /* end itimes */                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                         fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 } /* end of prwizard */                      }else{
 /******************* Gompertz Likelihood ******************************/                        printf(" 0.");
 double gompertz(double x[])                        fprintf(ficparo," 0.");
 {                       }
   double A,B,L=0.0,sump=0.,num=0.;                    }else{
   int i,n=0; /* n is the size of the sample */                      if(itimes==1){
                         printf(" Var(%s%1d%1d)",ca,i,j);
   for (i=0;i<=imx-1 ; i++) {                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
     sump=sump+weight[i];                      }else{
     /*    sump=sump+1;*/                        printf(" 0.");
     num=num+1;                        fprintf(ficparo," 0.");
   }                      }
                      }
                    }
   /* for (i=0; i<=imx; i++)                 } /* end lk */
      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]);*/              } /* end lj */
             } /* end li */
   for (i=1;i<=imx ; i++)            printf("\n");
     {            fprintf(ficparo,"\n");
       if (cens[i] == 1 && wav[i]>1)            numlinepar++;
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));          } /* end k*/
               } /*end j */
       if (cens[i] == 0 && wav[i]>1)      } /* end i */
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))    } /* end itimes */
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);    
         } /* end of prwizard */
       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */  /******************* Gompertz Likelihood ******************************/
       if (wav[i] > 1 ) { /* ??? */  double gompertz(double x[])
         L=L+A*weight[i];  {
         /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/    double A,B,L=0.0,sump=0.,num=0.;
       }    int i,n=0; /* n is the size of the sample */
     }  
     for (i=0;i<=imx-1 ; i++) {
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/      sump=sump+weight[i];
        /*    sump=sump+1;*/
   return -2*L*num/sump;      num=num+1;
 }    }
    
 /******************* Printing html file ***********/   
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \    /* for (i=0; i<=imx; i++)
                   int lastpass, int stepm, int weightopt, char model[],\       if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
                   int imx,  double p[],double **matcov,double agemortsup){  
   int i,k;    for (i=1;i<=imx ; i++)
       {
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");        if (cens[i] == 1 && wav[i]>1)
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);          A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
   for (i=1;i<=2;i++)        
     fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));        if (cens[i] == 0 && wav[i]>1)
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");          A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
   fprintf(fichtm,"</ul>");               +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
        
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
         if (wav[i] > 1 ) { /* ??? */
  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>");          L=L+A*weight[i];
           /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
  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]);      }
   
     /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
   fflush(fichtm);   
 }    return -2*L*num/sump;
   }
 /******************* Gnuplot file **************/  
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){  /******************* Printing html file ***********/
   void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
   char dirfileres[132],optfileres[132];                    int lastpass, int stepm, int weightopt, char model[],\
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;                    int imx,  double p[],double **matcov,double agemortsup){
   int ng;    int i,k;
   
     fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
   /*#ifdef windows */    fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
   fprintf(ficgp,"cd \"%s\" \n",pathc);    for (i=1;i<=2;i++)
     /*#endif */      fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
     fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
     fprintf(fichtm,"</ul>");
   strcpy(dirfileres,optionfilefiname);  
   strcpy(optfileres,"vpl");  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
   fprintf(ficgp,"set out \"graphmort.png\"\n ");   
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");    fprintf(fichtm,"\nAge   l<inf>x</inf>     q<inf>x</inf> d(x,x+1)    L<inf>x</inf>     T<inf>x</inf>     e<infx</inf><br>");
   fprintf(ficgp, "set ter png small\n set log y\n");   
   fprintf(ficgp, "set size 0.65,0.65\n");   for (k=agegomp;k<(agemortsup-2);k++)
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);     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]);
   
 }    
     fflush(fichtm);
   }
   
   /******************* Gnuplot file **************/
   void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 /***********************************************/  
 /**************** Main Program *****************/    char dirfileres[132],optfileres[132];
 /***********************************************/    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
     int ng;
 int main(int argc, char *argv[])  
 {  
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);    /*#ifdef windows */
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;    fprintf(ficgp,"cd \"%s\" \n",pathc);
   int linei, month, year,iout;      /*#endif */
   int jj, ll, li, lj, lk, imk;  
   int numlinepar=0; /* Current linenumber of parameter file */  
   int itimes;    strcpy(dirfileres,optionfilefiname);
   int NDIM=2;    strcpy(optfileres,"vpl");
     fprintf(ficgp,"set out \"graphmort.png\"\n ");
   char ca[32], cb[32], cc[32];    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
   char dummy[]="                         ";    fprintf(ficgp, "set ter png small\n set log y\n");
   /*  FILE *fichtm; *//* Html File */    fprintf(ficgp, "set size 0.65,0.65\n");
   /* FILE *ficgp;*/ /*Gnuplot File */    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
   struct stat info;  
   double agedeb, agefin,hf;  }
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;  
   
   double fret;  
   double **xi,tmp,delta;  
   
   double dum; /* Dummy variable */  /***********************************************/
   double ***p3mat;  /**************** Main Program *****************/
   double ***mobaverage;  /***********************************************/
   int *indx;  
   char line[MAXLINE], linepar[MAXLINE];  int main(int argc, char *argv[])
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];  {
   char pathr[MAXLINE], pathimach[MAXLINE];     int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
   char **bp, *tok, *val; /* pathtot */    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
   int firstobs=1, lastobs=10;    int linei, month, year,iout;
   int sdeb, sfin; /* Status at beginning and end */    int jj, ll, li, lj, lk, imk;
   int c,  h , cpt,l;    int numlinepar=0; /* Current linenumber of parameter file */
   int ju,jl, mi;    int itimes;
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;    int NDIM=2;
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;   
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */    char ca[32], cb[32], cc[32];
   int mobilav=0,popforecast=0;    char dummy[]="                         ";
   int hstepm, nhstepm;    /*  FILE *fichtm; *//* Html File */
   int agemortsup;    /* FILE *ficgp;*/ /*Gnuplot File */
   float  sumlpop=0.;    struct stat info;
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;    double agedeb, agefin,hf;
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
   
   double bage, fage, age, agelim, agebase;    double fret;
   double ftolpl=FTOL;    double **xi,tmp,delta;
   double **prlim;  
   double *severity;    double dum; /* Dummy variable */
   double ***param; /* Matrix of parameters */    double ***p3mat;
   double  *p;    double ***mobaverage;
   double **matcov; /* Matrix of covariance */    int *indx;
   double ***delti3; /* Scale */    char line[MAXLINE], linepar[MAXLINE];
   double *delti; /* Scale */    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
   double ***eij, ***vareij;    char pathr[MAXLINE], pathimach[MAXLINE];
   double **varpl; /* Variances of prevalence limits by age */    char **bp, *tok, *val; /* pathtot */
   double *epj, vepp;    int firstobs=1, lastobs=10;
   double kk1, kk2;    int sdeb, sfin; /* Status at beginning and end */
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;    int c,  h , cpt,l;
   double **ximort;    int ju,jl, mi;
   char *alph[]={"a","a","b","c","d","e"}, str[4];    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
   int *dcwave;    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
     int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
   char z[1]="c", occ;    int mobilav=0,popforecast=0;
     int hstepm, nhstepm;
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];    int agemortsup;
   char  *strt, strtend[80];    float  sumlpop=0.;
   char *stratrunc;    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
   int lstra;    double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
   
   long total_usecs;    double bage, fage, age, agelim, agebase;
      double ftolpl=FTOL;
 /*   setlocale (LC_ALL, ""); */    double **prlim;
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */    double *severity;
 /*   textdomain (PACKAGE); */    double ***param; /* Matrix of parameters */
 /*   setlocale (LC_CTYPE, ""); */    double  *p;
 /*   setlocale (LC_MESSAGES, ""); */    double **matcov; /* Matrix of covariance */
     double ***delti3; /* Scale */
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */    double *delti; /* Scale */
   (void) gettimeofday(&start_time,&tzp);    double ***eij, ***vareij;
   curr_time=start_time;    double **varpl; /* Variances of prevalence limits by age */
   tm = *localtime(&start_time.tv_sec);    double *epj, vepp;
   tmg = *gmtime(&start_time.tv_sec);    double kk1, kk2;
   strcpy(strstart,asctime(&tm));    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
     double **ximort;
 /*  printf("Localtime (at start)=%s",strstart); */    char *alph[]={"a","a","b","c","d","e"}, str[4];
 /*  tp.tv_sec = tp.tv_sec +86400; */    int *dcwave;
 /*  tm = *localtime(&start_time.tv_sec); */  
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */    char z[1]="c", occ;
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */  
 /*   tmg.tm_hour=tmg.tm_hour + 1; */    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
 /*   tp.tv_sec = mktime(&tmg); */    char  *strt, strtend[80];
 /*   strt=asctime(&tmg); */    char *stratrunc;
 /*   printf("Time(after) =%s",strstart);  */    int lstra;
 /*  (void) time (&time_value);  
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);    long total_usecs;
 *  tm = *localtime(&time_value);   
 *  strstart=asctime(&tm);  /*   setlocale (LC_ALL, ""); */
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);   /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 */  /*   textdomain (PACKAGE); */
   /*   setlocale (LC_CTYPE, ""); */
   nberr=0; /* Number of errors and warnings */  /*   setlocale (LC_MESSAGES, ""); */
   nbwarn=0;  
   getcwd(pathcd, size);    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
     (void) gettimeofday(&start_time,&tzp);
   printf("\n%s\n%s",version,fullversion);    curr_time=start_time;
   if(argc <=1){    tm = *localtime(&start_time.tv_sec);
     printf("\nEnter the parameter file name: ");    tmg = *gmtime(&start_time.tv_sec);
     fgets(pathr,FILENAMELENGTH,stdin);    strcpy(strstart,asctime(&tm));
     i=strlen(pathr);  
     if(pathr[i-1]=='\n')  /*  printf("Localtime (at start)=%s",strstart); */
       pathr[i-1]='\0';  /*  tp.tv_sec = tp.tv_sec +86400; */
    for (tok = pathr; tok != NULL; ){  /*  tm = *localtime(&start_time.tv_sec); */
       printf("Pathr |%s|\n",pathr);  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
       printf("val= |%s| pathr=%s\n",val,pathr);  /*   tmg.tm_hour=tmg.tm_hour + 1; */
       strcpy (pathtot, val);  /*   tp.tv_sec = mktime(&tmg); */
       if(pathr[0] == '\0') break; /* Dirty */  /*   strt=asctime(&tmg); */
     }  /*   printf("Time(after) =%s",strstart);  */
   }  /*  (void) time (&time_value);
   else{  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
     strcpy(pathtot,argv[1]);  *  tm = *localtime(&time_value);
   }  *  strstart=asctime(&tm);
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
   /*cygwin_split_path(pathtot,path,optionfile);  */
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/  
   /* cutv(path,optionfile,pathtot,'\\');*/    nberr=0; /* Number of errors and warnings */
     nbwarn=0;
   /* Split argv[0], imach program to get pathimach */    getcwd(pathcd, size);
   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);  
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);    printf("\n%s\n%s",version,fullversion);
   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);    if(argc <=1){
  /*   strcpy(pathimach,argv[0]); */      printf("\nEnter the parameter file name: ");
   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */      fgets(pathr,FILENAMELENGTH,stdin);
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);      i=strlen(pathr);
   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);      if(pathr[i-1]=='\n')
   chdir(path); /* Can be a relative path */        pathr[i-1]='\0';
   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */     for (tok = pathr; tok != NULL; ){
     printf("Current directory %s!\n",pathcd);        printf("Pathr |%s|\n",pathr);
   strcpy(command,"mkdir ");        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
   strcat(command,optionfilefiname);        printf("val= |%s| pathr=%s\n",val,pathr);
   if((outcmd=system(command)) != 0){        strcpy (pathtot, val);
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);        if(pathr[0] == '\0') break; /* Dirty */
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */      }
     /* fclose(ficlog); */    }
 /*     exit(1); */    else{
   }      strcpy(pathtot,argv[1]);
 /*   if((imk=mkdir(optionfilefiname))<0){ */    }
 /*     perror("mkdir"); */    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 /*   } */    /*cygwin_split_path(pathtot,path,optionfile);
       printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
   /*-------- arguments in the command line --------*/    /* cutv(path,optionfile,pathtot,'\\');*/
   
   /* Log file */    /* Split argv[0], imach program to get pathimach */
   strcat(filelog, optionfilefiname);    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
   strcat(filelog,".log");    /* */    split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   if((ficlog=fopen(filelog,"w"))==NULL)    {    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
     printf("Problem with logfile %s\n",filelog);   /*   strcpy(pathimach,argv[0]); */
     goto end;    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
   }    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
   fprintf(ficlog,"Log filename:%s\n",filelog);    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
   fprintf(ficlog,"\n%s\n%s",version,fullversion);    chdir(path); /* Can be a relative path */
   fprintf(ficlog,"\nEnter the parameter file name: \n");    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\      printf("Current directory %s!\n",pathcd);
  path=%s \n\    strcpy(command,"mkdir ");
  optionfile=%s\n\    strcat(command,optionfilefiname);
  optionfilext=%s\n\    if((outcmd=system(command)) != 0){
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);      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); */
   printf("Local time (at start):%s",strstart);      /* fclose(ficlog); */
   fprintf(ficlog,"Local time (at start): %s",strstart);  /*     exit(1); */
   fflush(ficlog);    }
 /*   (void) gettimeofday(&curr_time,&tzp); */  /*   if((imk=mkdir(optionfilefiname))<0){ */
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */  /*     perror("mkdir"); */
   /*   } */
   /* */  
   strcpy(fileres,"r");    /*-------- arguments in the command line --------*/
   strcat(fileres, optionfilefiname);  
   strcat(fileres,".txt");    /* Other files have txt extension */    /* Log file */
     strcat(filelog, optionfilefiname);
   /*---------arguments file --------*/    strcat(filelog,".log");    /* */
     if((ficlog=fopen(filelog,"w"))==NULL)    {
   if((ficpar=fopen(optionfile,"r"))==NULL)    {      printf("Problem with logfile %s\n",filelog);
     printf("Problem with optionfile %s\n",optionfile);      goto end;
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);    }
     fflush(ficlog);    fprintf(ficlog,"Log filename:%s\n",filelog);
     goto end;    fprintf(ficlog,"\n%s\n%s",version,fullversion);
   }    fprintf(ficlog,"\nEnter the parameter file name: \n");
     fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
    path=%s \n\
    optionfile=%s\n\
   strcpy(filereso,"o");   optionfilext=%s\n\
   strcat(filereso,fileres);   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */  
     printf("Problem with Output resultfile: %s\n", filereso);    printf("Local time (at start):%s",strstart);
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);    fprintf(ficlog,"Local time (at start): %s",strstart);
     fflush(ficlog);    fflush(ficlog);
     goto end;  /*   (void) gettimeofday(&curr_time,&tzp); */
   }  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   
   /* Reads comments: lines beginning with '#' */    /* */
   numlinepar=0;    strcpy(fileres,"r");
   while((c=getc(ficpar))=='#' && c!= EOF){    strcat(fileres, optionfilefiname);
     ungetc(c,ficpar);    strcat(fileres,".txt");    /* Other files have txt extension */
     fgets(line, MAXLINE, ficpar);  
     numlinepar++;    /*---------arguments file --------*/
     puts(line);  
     fputs(line,ficparo);    if((ficpar=fopen(optionfile,"r"))==NULL)    {
     fputs(line,ficlog);      printf("Problem with optionfile %s\n",optionfile);
   }      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
   ungetc(c,ficpar);      fflush(ficlog);
       goto end;
   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);    }
   numlinepar++;  
   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);  
   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);  
   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    strcpy(filereso,"o");
   fflush(ficlog);    strcat(filereso,fileres);
   while((c=getc(ficpar))=='#' && c!= EOF){    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
     ungetc(c,ficpar);      printf("Problem with Output resultfile: %s\n", filereso);
     fgets(line, MAXLINE, ficpar);      fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
     numlinepar++;      fflush(ficlog);
     puts(line);      goto end;
     fputs(line,ficparo);    }
     fputs(line,ficlog);  
   }    /* Reads comments: lines beginning with '#' */
   ungetc(c,ficpar);    numlinepar=0;
     while((c=getc(ficpar))=='#' && c!= EOF){
          ungetc(c,ficpar);
   covar=matrix(0,NCOVMAX,1,n);       fgets(line, MAXLINE, ficpar);
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/      numlinepar++;
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;      puts(line);
       fputs(line,ficparo);
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */      fputs(line,ficlog);
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */    }
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/    ungetc(c,ficpar);
   
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    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);
   delti=delti3[1][1];    numlinepar++;
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/    printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */    fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);    fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
     printf(" You choose mle=-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);    while((c=getc(ficpar))=='#' && c!= EOF){
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);       ungetc(c,ficpar);
     fclose (ficparo);      fgets(line, MAXLINE, ficpar);
     fclose (ficlog);      numlinepar++;
     exit(0);      puts(line);
   }      fputs(line,ficparo);
   else if(mle==-3) {      fputs(line,ficlog);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);    }
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    ungetc(c,ficpar);
     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);    covar=matrix(0,NCOVMAX,1,n);
   }    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
   else{    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
     /* Read guess parameters */  
     /* Reads comments: lines beginning with '#' */    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
     while((c=getc(ficpar))=='#' && c!= EOF){    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
       ungetc(c,ficpar);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
       fgets(line, MAXLINE, ficpar);  
       numlinepar++;    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
       puts(line);    delti=delti3[1][1];
       fputs(line,ficparo);    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
       fputs(line,ficlog);    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
     }      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
     ungetc(c,ficpar);      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);
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
     for(i=1; i <=nlstate; i++){      fclose (ficparo);
       j=0;      fclose (ficlog);
       for(jj=1; jj <=nlstate+ndeath; jj++){      goto end;
         if(jj==i) continue;      exit(0);
         j++;    }
         fscanf(ficpar,"%1d%1d",&i1,&j1);    else if(mle==-3) {
         if ((i1 != i) && (j1 != j)){      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
           exit(1);      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);
         fprintf(ficparo,"%1d%1d",i1,j1);      matcov=matrix(1,npar,1,npar);
         if(mle==1)    }
           printf("%1d%1d",i,j);    else{
         fprintf(ficlog,"%1d%1d",i,j);      /* Read guess parameters */
         for(k=1; k<=ncovmodel;k++){      /* Reads comments: lines beginning with '#' */
           fscanf(ficpar," %lf",&param[i][j][k]);      while((c=getc(ficpar))=='#' && c!= EOF){
           if(mle==1){        ungetc(c,ficpar);
             printf(" %lf",param[i][j][k]);        fgets(line, MAXLINE, ficpar);
             fprintf(ficlog," %lf",param[i][j][k]);        numlinepar++;
           }        puts(line);
           else        fputs(line,ficparo);
             fprintf(ficlog," %lf",param[i][j][k]);        fputs(line,ficlog);
           fprintf(ficparo," %lf",param[i][j][k]);      }
         }      ungetc(c,ficpar);
         fscanf(ficpar,"\n");     
         numlinepar++;      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         if(mle==1)      for(i=1; i <=nlstate; i++){
           printf("\n");        j=0;
         fprintf(ficlog,"\n");        for(jj=1; jj <=nlstate+ndeath; jj++){
         fprintf(ficparo,"\n");          if(jj==i) continue;
       }          j++;
     }            fscanf(ficpar,"%1d%1d",&i1,&j1);
     fflush(ficlog);          if ((i1 != i) && (j1 != j)){
             printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
     p=param[1][1];  It might be a problem of design; if ncovcol and the model are correct\n \
       run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
     /* Reads comments: lines beginning with '#' */            exit(1);
     while((c=getc(ficpar))=='#' && c!= EOF){          }
       ungetc(c,ficpar);          fprintf(ficparo,"%1d%1d",i1,j1);
       fgets(line, MAXLINE, ficpar);          if(mle==1)
       numlinepar++;            printf("%1d%1d",i,j);
       puts(line);          fprintf(ficlog,"%1d%1d",i,j);
       fputs(line,ficparo);          for(k=1; k<=ncovmodel;k++){
       fputs(line,ficlog);            fscanf(ficpar," %lf",&param[i][j][k]);
     }            if(mle==1){
     ungetc(c,ficpar);              printf(" %lf",param[i][j][k]);
               fprintf(ficlog," %lf",param[i][j][k]);
     for(i=1; i <=nlstate; i++){            }
       for(j=1; j <=nlstate+ndeath-1; j++){            else
         fscanf(ficpar,"%1d%1d",&i1,&j1);              fprintf(ficlog," %lf",param[i][j][k]);
         if ((i1-i)*(j1-j)!=0){            fprintf(ficparo," %lf",param[i][j][k]);
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);          }
           exit(1);          fscanf(ficpar,"\n");
         }          numlinepar++;
         printf("%1d%1d",i,j);          if(mle==1)
         fprintf(ficparo,"%1d%1d",i1,j1);            printf("\n");
         fprintf(ficlog,"%1d%1d",i1,j1);          fprintf(ficlog,"\n");
         for(k=1; k<=ncovmodel;k++){          fprintf(ficparo,"\n");
           fscanf(ficpar,"%le",&delti3[i][j][k]);        }
           printf(" %le",delti3[i][j][k]);      }  
           fprintf(ficparo," %le",delti3[i][j][k]);      fflush(ficlog);
           fprintf(ficlog," %le",delti3[i][j][k]);  
         }      p=param[1][1];
         fscanf(ficpar,"\n");     
         numlinepar++;      /* Reads comments: lines beginning with '#' */
         printf("\n");      while((c=getc(ficpar))=='#' && c!= EOF){
         fprintf(ficparo,"\n");        ungetc(c,ficpar);
         fprintf(ficlog,"\n");        fgets(line, MAXLINE, ficpar);
       }        numlinepar++;
     }        puts(line);
     fflush(ficlog);        fputs(line,ficparo);
         fputs(line,ficlog);
     delti=delti3[1][1];      }
       ungetc(c,ficpar);
   
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */      for(i=1; i <=nlstate; i++){
           for(j=1; j <=nlstate+ndeath-1; j++){
     /* Reads comments: lines beginning with '#' */          fscanf(ficpar,"%1d%1d",&i1,&j1);
     while((c=getc(ficpar))=='#' && c!= EOF){          if ((i1-i)*(j1-j)!=0){
       ungetc(c,ficpar);            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
       fgets(line, MAXLINE, ficpar);            exit(1);
       numlinepar++;          }
       puts(line);          printf("%1d%1d",i,j);
       fputs(line,ficparo);          fprintf(ficparo,"%1d%1d",i1,j1);
       fputs(line,ficlog);          fprintf(ficlog,"%1d%1d",i1,j1);
     }          for(k=1; k<=ncovmodel;k++){
     ungetc(c,ficpar);            fscanf(ficpar,"%le",&delti3[i][j][k]);
               printf(" %le",delti3[i][j][k]);
     matcov=matrix(1,npar,1,npar);            fprintf(ficparo," %le",delti3[i][j][k]);
     for(i=1; i <=npar; i++){            fprintf(ficlog," %le",delti3[i][j][k]);
       fscanf(ficpar,"%s",&str);          }
       if(mle==1)          fscanf(ficpar,"\n");
         printf("%s",str);          numlinepar++;
       fprintf(ficlog,"%s",str);          printf("\n");
       fprintf(ficparo,"%s",str);          fprintf(ficparo,"\n");
       for(j=1; j <=i; j++){          fprintf(ficlog,"\n");
         fscanf(ficpar," %le",&matcov[i][j]);        }
         if(mle==1){      }
           printf(" %.5le",matcov[i][j]);      fflush(ficlog);
         }  
         fprintf(ficlog," %.5le",matcov[i][j]);      delti=delti3[1][1];
         fprintf(ficparo," %.5le",matcov[i][j]);  
       }  
       fscanf(ficpar,"\n");      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
       numlinepar++;   
       if(mle==1)      /* Reads comments: lines beginning with '#' */
         printf("\n");      while((c=getc(ficpar))=='#' && c!= EOF){
       fprintf(ficlog,"\n");        ungetc(c,ficpar);
       fprintf(ficparo,"\n");        fgets(line, MAXLINE, ficpar);
     }        numlinepar++;
     for(i=1; i <=npar; i++)        puts(line);
       for(j=i+1;j<=npar;j++)        fputs(line,ficparo);
         matcov[i][j]=matcov[j][i];        fputs(line,ficlog);
           }
     if(mle==1)      ungetc(c,ficpar);
       printf("\n");   
     fprintf(ficlog,"\n");      matcov=matrix(1,npar,1,npar);
           for(i=1; i <=npar; i++){
     fflush(ficlog);        fscanf(ficpar,"%s",&str);
             if(mle==1)
     /*-------- Rewriting parameter file ----------*/          printf("%s",str);
     strcpy(rfileres,"r");    /* "Rparameterfile */        fprintf(ficlog,"%s",str);
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/        fprintf(ficparo,"%s",str);
     strcat(rfileres,".");    /* */        for(j=1; j <=i; j++){
     strcat(rfileres,optionfilext);    /* Other files have txt extension */          fscanf(ficpar," %le",&matcov[i][j]);
     if((ficres =fopen(rfileres,"w"))==NULL) {          if(mle==1){
       printf("Problem writing new parameter file: %s\n", fileres);goto end;            printf(" %.5le",matcov[i][j]);
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;          }
     }          fprintf(ficlog," %.5le",matcov[i][j]);
     fprintf(ficres,"#%s\n",version);          fprintf(ficparo," %.5le",matcov[i][j]);
   }    /* End of mle != -3 */        }
         fscanf(ficpar,"\n");
   /*-------- data file ----------*/        numlinepar++;
   if((fic=fopen(datafile,"r"))==NULL)    {        if(mle==1)
     printf("Problem while opening datafile: %s\n", datafile);goto end;          printf("\n");
     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;        fprintf(ficlog,"\n");
   }        fprintf(ficparo,"\n");
       }
   n= lastobs;      for(i=1; i <=npar; i++)
   severity = vector(1,maxwav);        for(j=i+1;j<=npar;j++)
   outcome=imatrix(1,maxwav+1,1,n);          matcov[i][j]=matcov[j][i];
   num=lvector(1,n);     
   moisnais=vector(1,n);      if(mle==1)
   annais=vector(1,n);        printf("\n");
   moisdc=vector(1,n);      fprintf(ficlog,"\n");
   andc=vector(1,n);     
   agedc=vector(1,n);      fflush(ficlog);
   cod=ivector(1,n);     
   weight=vector(1,n);      /*-------- Rewriting parameter file ----------*/
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */      strcpy(rfileres,"r");    /* "Rparameterfile */
   mint=matrix(1,maxwav,1,n);      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
   anint=matrix(1,maxwav,1,n);      strcat(rfileres,".");    /* */
   s=imatrix(1,maxwav+1,1,n);      strcat(rfileres,optionfilext);    /* Other files have txt extension */
   tab=ivector(1,NCOVMAX);      if((ficres =fopen(rfileres,"w"))==NULL) {
   ncodemax=ivector(1,8);        printf("Problem writing new parameter file: %s\n", fileres);goto end;
         fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
   i=1;      }
   linei=0;      fprintf(ficres,"#%s\n",version);
   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {    }    /* End of mle != -3 */
     linei=linei+1;  
     for(j=strlen(line); j>=0;j--){  /* Untabifies line */    /*-------- data file ----------*/
       if(line[j] == '\t')    if((fic=fopen(datafile,"r"))==NULL)    {
         line[j] = ' ';      printf("Problem while opening datafile: %s\n", datafile);goto end;
     }      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){    }
       ;  
     };    n= lastobs;
     line[j+1]=0;  /* Trims blanks at end of line */    severity = vector(1,maxwav);
     if(line[0]=='#'){    outcome=imatrix(1,maxwav+1,1,n);
       fprintf(ficlog,"Comment line\n%s\n",line);    num=lvector(1,n);
       printf("Comment line\n%s\n",line);    moisnais=vector(1,n);
       continue;    annais=vector(1,n);
     }    moisdc=vector(1,n);
     andc=vector(1,n);
     for (j=maxwav;j>=1;j--){    agedc=vector(1,n);
       cutv(stra, strb,line,' ');     cod=ivector(1,n);
       errno=0;    weight=vector(1,n);
       lval=strtol(strb,&endptr,10);     for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
       /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/    mint=matrix(1,maxwav,1,n);
       if( strb[0]=='\0' || (*endptr != '\0')){    anint=matrix(1,maxwav,1,n);
         printf("Error reading data around '%d' at line number %d %s for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);    s=imatrix(1,maxwav+1,1,n);
         exit(1);    tab=ivector(1,NCOVMAX);
       }    ncodemax=ivector(1,8);
       s[j][i]=lval;  
           i=1;
       strcpy(line,stra);    linei=0;
       cutv(stra, strb,line,' ');    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){      linei=linei+1;
       }      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
       else  if(iout=sscanf(strb,"%s.") != 0){        if(line[j] == '\t')
         month=99;          line[j] = ' ';
         year=9999;      }
       }else{      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
         printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);        ;
         exit(1);      };
       }      line[j+1]=0;  /* Trims blanks at end of line */
       anint[j][i]= (double) year;       if(line[0]=='#'){
       mint[j][i]= (double)month;         fprintf(ficlog,"Comment line\n%s\n",line);
       strcpy(line,stra);        printf("Comment line\n%s\n",line);
     } /* ENd Waves */        continue;
           }
     cutv(stra, strb,line,' ');   
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){      for (j=maxwav;j>=1;j--){
     }        cutv(stra, strb,line,' ');
     else  if(iout=sscanf(strb,"%s.",dummy) != 0){        errno=0;
       month=99;        lval=strtol(strb,&endptr,10);
       year=9999;        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
     }else{        if( strb[0]=='\0' || (*endptr != '\0')){
       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);          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);          exit(1);
     }        }
     andc[i]=(double) year;         s[j][i]=lval;
     moisdc[i]=(double) month;        
     strcpy(line,stra);        strcpy(line,stra);
             cutv(stra, strb,line,' ');
     cutv(stra, strb,line,' ');         if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){        }
     }        else  if(iout=sscanf(strb,"%s.") != 0){
     else  if(iout=sscanf(strb,"%s.") != 0){          month=99;
       month=99;          year=9999;
       year=9999;        }else{
     }else{          printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
       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);
       exit(1);        }
     }        anint[j][i]= (double) year;
     annais[i]=(double)(year);        mint[j][i]= (double)month;
     moisnais[i]=(double)(month);         strcpy(line,stra);
     strcpy(line,stra);      } /* ENd Waves */
          
     cutv(stra, strb,line,' ');       cutv(stra, strb,line,' ');
     errno=0;      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     dval=strtod(strb,&endptr);       }
     if( strb[0]=='\0' || (*endptr != '\0')){      else  if(iout=sscanf(strb,"%s.",dummy) != 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);        month=99;
       exit(1);        year=9999;
     }      }else{
     weight[i]=dval;         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);
     strcpy(line,stra);        exit(1);
           }
     for (j=ncovcol;j>=1;j--){      andc[i]=(double) year;
       cutv(stra, strb,line,' ');       moisdc[i]=(double) month;
       errno=0;      strcpy(line,stra);
       lval=strtol(strb,&endptr,10);      
       if( strb[0]=='\0' || (*endptr != '\0')){      cutv(stra, strb,line,' ');
         printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a covar (meaning 0 for the reference or 1).  Exiting.\n",lval, linei,i, line);      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
         exit(1);      }
       }      else  if(iout=sscanf(strb,"%s.") != 0){
       if(lval <-1 || lval >1){        month=99;
         printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \        year=9999;
  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \      }else{
  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \        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 example, for multinomial values like 1, 2 and 3,\n \        exit(1);
  build V1=0 V2=0 for the reference value (1),\n \      }
         V1=1 V2=0 for (2) \n \      annais[i]=(double)(year);
  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \      moisnais[i]=(double)(month);
  output of IMaCh is often meaningless.\n \      strcpy(line,stra);
  Exiting.\n",lval,linei, i,line,j);     
         exit(1);      cutv(stra, strb,line,' ');
       }      errno=0;
       covar[j][i]=(double)(lval);      dval=strtod(strb,&endptr);
       strcpy(line,stra);      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);
     lstra=strlen(stra);        exit(1);
           }
     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */      weight[i]=dval;
       stratrunc = &(stra[lstra-9]);      strcpy(line,stra);
       num[i]=atol(stratrunc);     
     }      for (j=ncovcol;j>=1;j--){
     else        cutv(stra, strb,line,' ');
       num[i]=atol(stra);        errno=0;
     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){        lval=strtol(strb,&endptr,10);
       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;}*/        if( strb[0]=='\0' || (*endptr != '\0')){
               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);
     i=i+1;          exit(1);
   } /* End loop reading  data */        }
   fclose(fic);        if(lval <-1 || lval >1){
   /* printf("ii=%d", ij);          printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
      scanf("%d",i);*/   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
   imx=i-1; /* Number of individuals */   for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
    For example, for multinomial values like 1, 2 and 3,\n \
   /* for (i=1; i<=imx; i++){   build V1=0 V2=0 for the reference value (1),\n \
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;          V1=1 V2=0 for (2) \n \
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;   output of IMaCh is often meaningless.\n \
     }*/   Exiting.\n",lval,linei, i,line,j);
    /*  for (i=1; i<=imx; i++){          exit(1);
      if (s[4][i]==9)  s[4][i]=-1;         }
      printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/        covar[j][i]=(double)(lval);
           strcpy(line,stra);
   /* for (i=1; i<=imx; i++) */      }
        lstra=strlen(stra);
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;     
      else weight[i]=1;*/      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
         stratrunc = &(stra[lstra-9]);
   /* Calculation of the number of parameters from char model */        num[i]=atol(stratrunc);
   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
   Tvaraff=ivector(1,15);         num[i]=atol(stra);
   Tvard=imatrix(1,15,1,2);      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
   Tage=ivector(1,15);              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;}*/
         
   if (strlen(model) >1){ /* If there is at least 1 covariate */      i=i+1;
     j=0, j1=0, k1=1, k2=1;    } /* End loop reading  data */
     j=nbocc(model,'+'); /* j=Number of '+' */    fclose(fic);
     j1=nbocc(model,'*'); /* j1=Number of '*' */    /* printf("ii=%d", ij);
     cptcovn=j+1;        scanf("%d",i);*/
     cptcovprod=j1; /*Number of products */    imx=i-1; /* Number of individuals */
       
     strcpy(modelsav,model);     /* for (i=1; i<=imx; i++){
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
       printf("Error. Non available option model=%s ",model);      if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
       fprintf(ficlog,"Error. Non available option model=%s ",model);      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
       goto end;      }*/
     }     /*  for (i=1; i<=imx; i++){
            if (s[4][i]==9)  s[4][i]=-1;
     /* This loop fills the array Tvar from the string 'model'.*/       printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/
    
     for(i=(j+1); i>=1;i--){    /* for (i=1; i<=imx; i++) */
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */    
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/       else weight[i]=1;*/
       /*scanf("%d",i);*/  
       if (strchr(strb,'*')) {  /* Model includes a product */    /* Calculation of the number of parameters from char model */
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
         if (strcmp(strc,"age")==0) { /* Vn*age */    Tprod=ivector(1,15);
           cptcovprod--;    Tvaraff=ivector(1,15);
           cutv(strb,stre,strd,'V');    Tvard=imatrix(1,15,1,2);
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/    Tage=ivector(1,15);      
           cptcovage++;     
             Tage[cptcovage]=i;    if (strlen(model) >1){ /* If there is at least 1 covariate */
             /*printf("stre=%s ", stre);*/      j=0, j1=0, k1=1, k2=1;
         }      j=nbocc(model,'+'); /* j=Number of '+' */
         else if (strcmp(strd,"age")==0) { /* or age*Vn */      j1=nbocc(model,'*'); /* j1=Number of '*' */
           cptcovprod--;      cptcovn=j+1;
           cutv(strb,stre,strc,'V');      cptcovprod=j1; /*Number of products */
           Tvar[i]=atoi(stre);     
           cptcovage++;      strcpy(modelsav,model);
           Tage[cptcovage]=i;      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
         }        printf("Error. Non available option model=%s ",model);
         else {  /* Age is not in the model */        fprintf(ficlog,"Error. Non available option model=%s ",model);
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/        goto end;
           Tvar[i]=ncovcol+k1;      }
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */     
           Tprod[k1]=i;      /* This loop fills the array Tvar from the string 'model'.*/
           Tvard[k1][1]=atoi(strc); /* m*/  
           Tvard[k1][2]=atoi(stre); /* n */      for(i=(j+1); i>=1;i--){
           Tvar[cptcovn+k2]=Tvard[k1][1];        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
           Tvar[cptcovn+k2+1]=Tvard[k1][2];         if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
           for (k=1; k<=lastobs;k++)         /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];        /*scanf("%d",i);*/
           k1++;        if (strchr(strb,'*')) {  /* Model includes a product */
           k2=k2+2;          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
         }          if (strcmp(strc,"age")==0) { /* Vn*age */
       }            cptcovprod--;
       else { /* no more sum */            cutv(strb,stre,strd,'V');
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
        /*  scanf("%d",i);*/            cptcovage++;
       cutv(strd,strc,strb,'V');              Tage[cptcovage]=i;
       Tvar[i]=atoi(strc);              /*printf("stre=%s ", stre);*/
       }          }
       strcpy(modelsav,stra);            else if (strcmp(strd,"age")==0) { /* or age*Vn */
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);            cptcovprod--;
         scanf("%d",i);*/            cutv(strb,stre,strc,'V');
     } /* end of loop + */            Tvar[i]=atoi(stre);
   } /* end model */            cptcovage++;
               Tage[cptcovage]=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 model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/          else {  /* Age is not in the model */
             cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);            Tvar[i]=ncovcol+k1;
   printf("cptcovprod=%d ", cptcovprod);            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);            Tprod[k1]=i;
             Tvard[k1][1]=atoi(strc); /* m*/
   scanf("%d ",i);*/            Tvard[k1][2]=atoi(stre); /* n */
             Tvar[cptcovn+k2]=Tvard[k1][1];
     /*  if(mle==1){*/            Tvar[cptcovn+k2+1]=Tvard[k1][2];
   if (weightopt != 1) { /* Maximisation without weights*/            for (k=1; k<=lastobs;k++)
     for(i=1;i<=n;i++) weight[i]=1.0;              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
   }            k1++;
     /*-calculation of age at interview from date of interview and age at death -*/            k2=k2+2;
   agev=matrix(1,maxwav,1,imx);          }
         }
   for (i=1; i<=imx; i++) {        else { /* no more sum */
     for(m=2; (m<= maxwav); m++) {          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){         /*  scanf("%d",i);*/
         anint[m][i]=9999;        cutv(strd,strc,strb,'V');
         s[m][i]=-1;        Tvar[i]=atoi(strc);
       }        }
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){        strcpy(modelsav,stra);  
         nberr++;        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
         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);          scanf("%d",i);*/
         fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);      } /* end of loop + */
         s[m][i]=-1;    } /* end model */
       }   
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
         nberr++;      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
         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]);     /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */    printf("cptcovprod=%d ", cptcovprod);
       }    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
     }  
   }    scanf("%d ",i);*/
   
   for (i=1; i<=imx; i++)  {      /*  if(mle==1){*/
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);    if (weightopt != 1) { /* Maximisation without weights*/
     for(m=firstpass; (m<= lastpass); m++){      for(i=1;i<=n;i++) weight[i]=1.0;
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){    }
         if (s[m][i] >= nlstate+1) {      /*-calculation of age at interview from date of interview and age at death -*/
           if(agedc[i]>0)    agev=matrix(1,maxwav,1,imx);
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)  
               agev[m][i]=agedc[i];    for (i=1; i<=imx; i++) {
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/      for(m=2; (m<= maxwav); m++) {
             else {        if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
               if ((int)andc[i]!=9999){          anint[m][i]=9999;
                 nbwarn++;          s[m][i]=-1;
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);        }
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
                 agev[m][i]=-1;          nberr++;
               }          printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
             }          fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
         }          s[m][i]=-1;
         else if(s[m][i] !=9){ /* Standard case, age in fractional        }
                                  years but with the precision of a month */        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);          nberr++;
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)          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]);
             agev[m][i]=1;          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]);
           else if(agev[m][i] <agemin){           s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
             agemin=agev[m][i];        }
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/      }
           }    }
           else if(agev[m][i] >agemax){  
             agemax=agev[m][i];    for (i=1; i<=imx; i++)  {
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
           }      for(m=firstpass; (m<= lastpass); m++){
           /*agev[m][i]=anint[m][i]-annais[i];*/        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
           /*     agev[m][i] = age[i]+2*m;*/          if (s[m][i] >= nlstate+1) {
         }            if(agedc[i]>0)
         else { /* =9 */              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
           agev[m][i]=1;                agev[m][i]=agedc[i];
           s[m][i]=-1;            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
         }              else {
       }                if ((int)andc[i]!=9999){
       else /*= 0 Unknown */                  nbwarn++;
         agev[m][i]=1;                  printf("Warning negative age at death: %ld line:%d\n",num[i],i);
     }                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                       agev[m][i]=-1;
   }                }
   for (i=1; i<=imx; i++)  {              }
     for(m=firstpass; (m<=lastpass); m++){          }
       if (s[m][i] > (nlstate+ndeath)) {          else if(s[m][i] !=9){ /* Standard case, age in fractional
         nberr++;                                   years but with the precision of a month */
         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);                 agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
         fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);                 if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
         goto end;              agev[m][i]=1;
       }            else if(agev[m][i] <agemin){
     }              agemin=agev[m][i];
   }              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
             }
   /*for (i=1; i<=imx; i++){            else if(agev[m][i] >agemax){
   for (m=firstpass; (m<lastpass); m++){              agemax=agev[m][i];
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
 }            }
             /*agev[m][i]=anint[m][i]-annais[i];*/
 }*/            /*     agev[m][i] = age[i]+2*m;*/
           }
           else { /* =9 */
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);            agev[m][i]=1;
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);             s[m][i]=-1;
           }
   agegomp=(int)agemin;        }
   free_vector(severity,1,maxwav);        else /*= 0 Unknown */
   free_imatrix(outcome,1,maxwav+1,1,n);          agev[m][i]=1;
   free_vector(moisnais,1,n);      }
   free_vector(annais,1,n);     
   /* free_matrix(mint,1,maxwav,1,n);    }
      free_matrix(anint,1,maxwav,1,n);*/    for (i=1; i<=imx; i++)  {
   free_vector(moisdc,1,n);      for(m=firstpass; (m<=lastpass); m++){
   free_vector(andc,1,n);        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);    
   wav=ivector(1,imx);          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);    
   dh=imatrix(1,lastpass-firstpass+1,1,imx);          goto end;
   bh=imatrix(1,lastpass-firstpass+1,1,imx);        }
   mw=imatrix(1,lastpass-firstpass+1,1,imx);      }
        }
   /* Concatenates waves */  
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);    /*for (i=1; i<=imx; i++){
     for (m=firstpass; (m<lastpass); m++){
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
   }
   Tcode=ivector(1,100);  
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);   }*/
   ncodemax[1]=1;  
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);  
           printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of     fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
                                  the estimations*/  
   h=0;    agegomp=(int)agemin;
   m=pow(2,cptcoveff);    free_vector(severity,1,maxwav);
      free_imatrix(outcome,1,maxwav+1,1,n);
   for(k=1;k<=cptcoveff; k++){    free_vector(moisnais,1,n);
     for(i=1; i <=(m/pow(2,k));i++){    free_vector(annais,1,n);
       for(j=1; j <= ncodemax[k]; j++){    /* free_matrix(mint,1,maxwav,1,n);
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){       free_matrix(anint,1,maxwav,1,n);*/
           h++;    free_vector(moisdc,1,n);
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;    free_vector(andc,1,n);
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/  
         }      
       }    wav=ivector(1,imx);
     }    dh=imatrix(1,lastpass-firstpass+1,1,imx);
   }     bh=imatrix(1,lastpass-firstpass+1,1,imx);
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);     mw=imatrix(1,lastpass-firstpass+1,1,imx);
      codtab[1][2]=1;codtab[2][2]=2; */     
   /* for(i=1; i <=m ;i++){     /* Concatenates waves */
      for(k=1; k <=cptcovn; k++){    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);  
      }    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
      printf("\n");  
      }    Tcode=ivector(1,100);
      scanf("%d",i);*/    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
         ncodemax[1]=1;
   /*------------ gnuplot -------------*/    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
   strcpy(optionfilegnuplot,optionfilefiname);       
   if(mle==-3)    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
     strcat(optionfilegnuplot,"-mort");                                   the estimations*/
   strcat(optionfilegnuplot,".gp");    h=0;
     m=pow(2,cptcoveff);
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {   
     printf("Problem with file %s",optionfilegnuplot);    for(k=1;k<=cptcoveff; k++){
   }      for(i=1; i <=(m/pow(2,k));i++){
   else{        for(j=1; j <= ncodemax[k]; j++){
     fprintf(ficgp,"\n# %s\n", version);           for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
     fprintf(ficgp,"# %s\n", optionfilegnuplot);             h++;
     fprintf(ficgp,"set missing 'NaNq'\n");            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
   }            /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
   /*  fclose(ficgp);*/          }
   /*--------- index.htm --------*/        }
       }
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */    }
   if(mle==-3)    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
     strcat(optionfilehtm,"-mort");       codtab[1][2]=1;codtab[2][2]=2; */
   strcat(optionfilehtm,".htm");    /* for(i=1; i <=m ;i++){
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {       for(k=1; k <=cptcovn; k++){
     printf("Problem with %s \n",optionfilehtm), exit(0);       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
   }       }
        printf("\n");
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */       }
   strcat(optionfilehtmcov,"-cov.htm");       scanf("%d",i);*/
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {     
     printf("Problem with %s \n",optionfilehtmcov), exit(0);    /*------------ gnuplot -------------*/
   }    strcpy(optionfilegnuplot,optionfilefiname);
   else{    if(mle==-3)
   fprintf(fichtmcov,"<body>\n<title>IMaCh Cov %s</title>\n <font size=\"2\">%s <br> %s</font> \      strcat(optionfilegnuplot,"-mort");
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    strcat(optionfilegnuplot,".gp");
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\  
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
   }      printf("Problem with file %s",optionfilegnuplot);
     }
   fprintf(fichtm,"<body>\n<title>IMaCh %s</title>\n <font size=\"2\">%s <br> %s</font> \    else{
 <hr size=\"2\" color=\"#EC5E5E\"> \n\      fprintf(ficgp,"\n# %s\n", version);
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\      fprintf(ficgp,"# %s\n", optionfilegnuplot);
 \n\      fprintf(ficgp,"set missing 'NaNq'\n");
 <hr  size=\"2\" color=\"#EC5E5E\">\    }
  <ul><li><h4>Parameter files</h4>\n\    /*  fclose(ficgp);*/
  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\    /*--------- index.htm --------*/
  - 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\    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\    if(mle==-3)
  - Date and time at start: %s</ul>\n",\      strcat(optionfilehtm,"-mort");
           fileres,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\    strcat(optionfilehtm,".htm");
           optionfilefiname,optionfilext,optionfilefiname,optionfilext,\    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
           fileres,fileres,\      printf("Problem with %s \n",optionfilehtm), exit(0);
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);    }
   fflush(fichtm);  
     strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
   strcpy(pathr,path);    strcat(optionfilehtmcov,"-cov.htm");
   strcat(pathr,optionfilefiname);    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
   chdir(optionfilefiname); /* Move to directory named optionfile */      printf("Problem with %s \n",optionfilehtmcov), exit(0);
       }
   /* Calculates basic frequencies. Computes observed prevalence at single age    else{
      and prints on file fileres'p'. */    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);  <hr size=\"2\" color=\"#EC5E5E\"> \n\
   Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
   fprintf(fichtm,"\n");            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
   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",\    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
           imx,agemin,agemax,jmin,jmax,jmean);  <hr size=\"2\" color=\"#EC5E5E\"> \n\
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  \n\
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  <hr  size=\"2\" color=\"#EC5E5E\">\
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */   <ul><li><h4>Parameter files</h4>\n\
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */   - 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\
   /* For Powell, parameters are in a vector p[] starting at p[1]   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */   - Date and time at start: %s</ul>\n",\
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
             optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/            fileres,fileres,\
             filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
   if (mle==-3){    fflush(fichtm);
     ximort=matrix(1,NDIM,1,NDIM);  
     cens=ivector(1,n);    strcpy(pathr,path);
     ageexmed=vector(1,n);    strcat(pathr,optionfilefiname);
     agecens=vector(1,n);    chdir(optionfilefiname); /* Move to directory named optionfile */
     dcwave=ivector(1,n);   
      /* Calculates basic frequencies. Computes observed prevalence at single age
     for (i=1; i<=imx; i++){       and prints on file fileres'p'. */
       dcwave[i]=-1;    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
       for (m=firstpass; m<=lastpass; m++)  
         if (s[m][i]>nlstate) {    fprintf(fichtm,"\n");
           dcwave[i]=m;    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/  Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
           break;  Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
         }            imx,agemin,agemax,jmin,jmax,jmean);
     }    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     for (i=1; i<=imx; i++) {      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       if (wav[i]>0){      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
         ageexmed[i]=agev[mw[1][i]][i];      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
         j=wav[i];     
         agecens[i]=1.;      
     /* For Powell, parameters are in a vector p[] starting at p[1]
         if (ageexmed[i]> 1 && wav[i] > 0){       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
           agecens[i]=agev[mw[j][i]][i];    p=param[1][1]; /* *(*(*(param +1)+1)+0) */
           cens[i]= 1;  
         }else if (ageexmed[i]< 1)     globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
           cens[i]= -1;  
         if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)    if (mle==-3){
           cens[i]=0 ;      ximort=matrix(1,NDIM,1,NDIM);
       }      cens=ivector(1,n);
       else cens[i]=-1;      ageexmed=vector(1,n);
     }      agecens=vector(1,n);
           dcwave=ivector(1,n);
     for (i=1;i<=NDIM;i++) {   
       for (j=1;j<=NDIM;j++)      for (i=1; i<=imx; i++){
         ximort[i][j]=(i == j ? 1.0 : 0.0);        dcwave[i]=-1;
     }        for (m=firstpass; m<=lastpass; m++)
               if (s[m][i]>nlstate) {
     p[1]=0.0268; p[NDIM]=0.083;            dcwave[i]=m;
     /*printf("%lf %lf", p[1], p[2]);*/            /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                 break;
               }
     printf("Powell\n");  fprintf(ficlog,"Powell\n");      }
     strcpy(filerespow,"pow-mort");   
     strcat(filerespow,fileres);      for (i=1; i<=imx; i++) {
     if((ficrespow=fopen(filerespow,"w"))==NULL) {        if (wav[i]>0){
       printf("Problem with resultfile: %s\n", filerespow);          ageexmed[i]=agev[mw[1][i]][i];
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);          j=wav[i];
     }          agecens[i]=1.;
     fprintf(ficrespow,"# Powell\n# iter -2*LL");  
     /*  for (i=1;i<=nlstate;i++)          if (ageexmed[i]> 1 && wav[i] > 0){
         for(j=1;j<=nlstate+ndeath;j++)            agecens[i]=agev[mw[j][i]][i];
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);            cens[i]= 1;
     */          }else if (ageexmed[i]< 1)
     fprintf(ficrespow,"\n");            cens[i]= -1;
               if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);            cens[i]=0 ;
     fclose(ficrespow);        }
             else cens[i]=-1;
     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);       }
      
     for(i=1; i <=NDIM; i++)      for (i=1;i<=NDIM;i++) {
       for(j=i+1;j<=NDIM;j++)        for (j=1;j<=NDIM;j++)
         matcov[i][j]=matcov[j][i];          ximort[i][j]=(i == j ? 1.0 : 0.0);
           }
     printf("\nCovariance matrix\n ");     
     for(i=1; i <=NDIM; i++) {      p[1]=0.0268; p[NDIM]=0.083;
       for(j=1;j<=NDIM;j++){       /*printf("%lf %lf", p[1], p[2]);*/
         printf("%f ",matcov[i][j]);     
       }     
       printf("\n ");      printf("Powell\n");  fprintf(ficlog,"Powell\n");
     }      strcpy(filerespow,"pow-mort");
           strcat(filerespow,fileres);
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);      if((ficrespow=fopen(filerespow,"w"))==NULL) {
     for (i=1;i<=NDIM;i++)         printf("Problem with resultfile: %s\n", filerespow);
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
       }
     lsurv=vector(1,AGESUP);      fprintf(ficrespow,"# Powell\n# iter -2*LL");
     lpop=vector(1,AGESUP);      /*  for (i=1;i<=nlstate;i++)
     tpop=vector(1,AGESUP);          for(j=1;j<=nlstate+ndeath;j++)
     lsurv[agegomp]=100000;          if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
           */
     for (k=agegomp;k<=AGESUP;k++) {      fprintf(ficrespow,"\n");
       agemortsup=k;     
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
     }      fclose(ficrespow);
          
     for (k=agegomp;k<agemortsup;k++)      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));  
           for(i=1; i <=NDIM; i++)
     for (k=agegomp;k<agemortsup;k++){        for(j=i+1;j<=NDIM;j++)
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;          matcov[i][j]=matcov[j][i];
       sumlpop=sumlpop+lpop[k];     
     }      printf("\nCovariance matrix\n ");
           for(i=1; i <=NDIM; i++) {
     tpop[agegomp]=sumlpop;        for(j=1;j<=NDIM;j++){
     for (k=agegomp;k<(agemortsup-3);k++){          printf("%f ",matcov[i][j]);
       /*  tpop[k+1]=2;*/        }
       tpop[k+1]=tpop[k]-lpop[k];        printf("\n ");
     }      }
          
           printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");      for (i=1;i<=NDIM;i++)
     for (k=agegomp;k<(agemortsup-2);k++)         printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
       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]);  
           lsurv=vector(1,AGESUP);
           lpop=vector(1,AGESUP);
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      tpop=vector(1,AGESUP);
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);      lsurv[agegomp]=100000;
          
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \      for (k=agegomp;k<=AGESUP;k++) {
                      stepm, weightopt,\        agemortsup=k;
                      model,imx,p,matcov,agemortsup);        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
           }
     free_vector(lsurv,1,AGESUP);     
     free_vector(lpop,1,AGESUP);      for (k=agegomp;k<agemortsup;k++)
     free_vector(tpop,1,AGESUP);        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
   } /* Endof if mle==-3 */     
         for (k=agegomp;k<agemortsup;k++){
   else{ /* For mle >=1 */        lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
           sumlpop=sumlpop+lpop[k];
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */      }
     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);     
     for (k=1; k<=npar;k++)      tpop[agegomp]=sumlpop;
       printf(" %d %8.5f",k,p[k]);      for (k=agegomp;k<(agemortsup-3);k++){
     printf("\n");        /*  tpop[k+1]=2;*/
     globpr=1; /* to print the contributions */        tpop[k+1]=tpop[k]-lpop[k];
     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]);      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
     printf("\n");      for (k=agegomp;k<(agemortsup-2);k++)
     if(mle>=1){ /* Could be 1 or 2 */        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]);
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);     
     }     
           replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     /*--------- results files --------------*/      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     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);     
           printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                            stepm, weightopt,\
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");                       model,imx,p,matcov,agemortsup);
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");     
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      free_vector(lsurv,1,AGESUP);
     for(i=1,jk=1; i <=nlstate; i++){      free_vector(lpop,1,AGESUP);
       for(k=1; k <=(nlstate+ndeath); k++){      free_vector(tpop,1,AGESUP);
         if (k != i) {    } /* Endof if mle==-3 */
           printf("%d%d ",i,k);   
           fprintf(ficlog,"%d%d ",i,k);    else{ /* For mle >=1 */
           fprintf(ficres,"%1d%1d ",i,k);   
           for(j=1; j <=ncovmodel; j++){      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
             printf("%f ",p[jk]);      printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
             fprintf(ficlog,"%f ",p[jk]);      for (k=1; k<=npar;k++)
             fprintf(ficres,"%f ",p[jk]);        printf(" %d %8.5f",k,p[k]);
             jk++;       printf("\n");
           }      globpr=1; /* to print the contributions */
           printf("\n");      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
           fprintf(ficlog,"\n");      printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
           fprintf(ficres,"\n");      for (k=1; k<=npar;k++)
         }        printf(" %d %8.5f",k,p[k]);
       }      printf("\n");
     }      if(mle>=1){ /* Could be 1 or 2 */
     if(mle!=0){        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
       /* Computing hessian and covariance matrix */      }
       ftolhess=ftol; /* Usually correct */     
       hesscov(matcov, p, npar, delti, ftolhess, func);      /*--------- results files --------------*/
     }      fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");     
     printf("# Scales (for hessian or gradient estimation)\n");     
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");      fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
     for(i=1,jk=1; i <=nlstate; i++){      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       for(j=1; j <=nlstate+ndeath; j++){      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
         if (j!=i) {      for(i=1,jk=1; i <=nlstate; i++){
           fprintf(ficres,"%1d%1d",i,j);        for(k=1; k <=(nlstate+ndeath); k++){
           printf("%1d%1d",i,j);          if (k != i) {
           fprintf(ficlog,"%1d%1d",i,j);            printf("%d%d ",i,k);
           for(k=1; k<=ncovmodel;k++){            fprintf(ficlog,"%d%d ",i,k);
             printf(" %.5e",delti[jk]);            fprintf(ficres,"%1d%1d ",i,k);
             fprintf(ficlog," %.5e",delti[jk]);            for(j=1; j <=ncovmodel; j++){
             fprintf(ficres," %.5e",delti[jk]);              printf("%lf ",p[jk]);
             jk++;              fprintf(ficlog,"%lf ",p[jk]);
           }              fprintf(ficres,"%lf ",p[jk]);
           printf("\n");              jk++;
           fprintf(ficlog,"\n");            }
           fprintf(ficres,"\n");            printf("\n");
         }            fprintf(ficlog,"\n");
       }            fprintf(ficres,"\n");
     }          }
             }
     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");      }
     if(mle>=1)      if(mle!=0){
       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");        /* Computing hessian and covariance matrix */
     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");        ftolhess=ftol; /* Usually correct */
     /* # 121 Var(a12)\n\ */        hesscov(matcov, p, npar, delti, ftolhess, func);
     /* # 122 Cov(b12,a12) Var(b12)\n\ */      }
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */      printf("# Scales (for hessian or gradient estimation)\n");
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */      for(i=1,jk=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\ */        for(j=1; j <=nlstate+ndeath; j++){
     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */          if (j!=i) {
                 fprintf(ficres,"%1d%1d",i,j);
                 printf("%1d%1d",i,j);
     /* Just to have a covariance matrix which will be more understandable            fprintf(ficlog,"%1d%1d",i,j);
        even is we still don't want to manage dictionary of variables            for(k=1; k<=ncovmodel;k++){
     */              printf(" %.5e",delti[jk]);
     for(itimes=1;itimes<=2;itimes++){              fprintf(ficlog," %.5e",delti[jk]);
       jj=0;              fprintf(ficres," %.5e",delti[jk]);
       for(i=1; i <=nlstate; i++){              jk++;
         for(j=1; j <=nlstate+ndeath; j++){            }
           if(j==i) continue;            printf("\n");
           for(k=1; k<=ncovmodel;k++){            fprintf(ficlog,"\n");
             jj++;            fprintf(ficres,"\n");
             ca[0]= k+'a'-1;ca[1]='\0';          }
             if(itimes==1){        }
               if(mle>=1)      }
                 printf("#%1d%1d%d",i,j,k);     
               fprintf(ficlog,"#%1d%1d%d",i,j,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");
               fprintf(ficres,"#%1d%1d%d",i,j,k);      if(mle>=1)
             }else{        printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
               if(mle>=1)      fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                 printf("%1d%1d%d",i,j,k);      /* # 121 Var(a12)\n\ */
               fprintf(ficlog,"%1d%1d%d",i,j,k);      /* # 122 Cov(b12,a12) Var(b12)\n\ */
               fprintf(ficres,"%1d%1d%d",i,j,k);      /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
             }      /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
             ll=0;      /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
             for(li=1;li <=nlstate; li++){      /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
               for(lj=1;lj <=nlstate+ndeath; lj++){      /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                 if(lj==li) continue;      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                 for(lk=1;lk<=ncovmodel;lk++){     
                   ll++;     
                   if(ll<=jj){      /* Just to have a covariance matrix which will be more understandable
                     cb[0]= lk +'a'-1;cb[1]='\0';         even is we still don't want to manage dictionary of variables
                     if(ll<jj){      */
                       if(itimes==1){      for(itimes=1;itimes<=2;itimes++){
                         if(mle>=1)        jj=0;
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);        for(i=1; i <=nlstate; i++){
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);          for(j=1; j <=nlstate+ndeath; j++){
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);            if(j==i) continue;
                       }else{            for(k=1; k<=ncovmodel;k++){
                         if(mle>=1)              jj++;
                           printf(" %.5e",matcov[jj][ll]);               ca[0]= k+'a'-1;ca[1]='\0';
                         fprintf(ficlog," %.5e",matcov[jj][ll]);               if(itimes==1){
                         fprintf(ficres," %.5e",matcov[jj][ll]);                 if(mle>=1)
                       }                  printf("#%1d%1d%d",i,j,k);
                     }else{                fprintf(ficlog,"#%1d%1d%d",i,j,k);
                       if(itimes==1){                fprintf(ficres,"#%1d%1d%d",i,j,k);
                         if(mle>=1)              }else{
                           printf(" Var(%s%1d%1d)",ca,i,j);                if(mle>=1)
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);                  printf("%1d%1d%d",i,j,k);
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);                fprintf(ficlog,"%1d%1d%d",i,j,k);
                       }else{                fprintf(ficres,"%1d%1d%d",i,j,k);
                         if(mle>=1)              }
                           printf(" %.5e",matcov[jj][ll]);               ll=0;
                         fprintf(ficlog," %.5e",matcov[jj][ll]);               for(li=1;li <=nlstate; li++){
                         fprintf(ficres," %.5e",matcov[jj][ll]);                 for(lj=1;lj <=nlstate+ndeath; lj++){
                       }                  if(lj==li) continue;
                     }                  for(lk=1;lk<=ncovmodel;lk++){
                   }                    ll++;
                 } /* end lk */                    if(ll<=jj){
               } /* end lj */                      cb[0]= lk +'a'-1;cb[1]='\0';
             } /* end li */                      if(ll<jj){
             if(mle>=1)                        if(itimes==1){
               printf("\n");                          if(mle>=1)
             fprintf(ficlog,"\n");                            printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
             fprintf(ficres,"\n");                          fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
             numlinepar++;                          fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
           } /* end k*/                        }else{
         } /*end j */                          if(mle>=1)
       } /* end i */                            printf(" %.5e",matcov[jj][ll]);
     } /* end itimes */                          fprintf(ficlog," %.5e",matcov[jj][ll]);
                               fprintf(ficres," %.5e",matcov[jj][ll]);
     fflush(ficlog);                        }
     fflush(ficres);                      }else{
                             if(itimes==1){
     while((c=getc(ficpar))=='#' && c!= EOF){                          if(mle>=1)
       ungetc(c,ficpar);                            printf(" Var(%s%1d%1d)",ca,i,j);
       fgets(line, MAXLINE, ficpar);                          fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
       puts(line);                          fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
       fputs(line,ficparo);                        }else{
     }                          if(mle>=1)
     ungetc(c,ficpar);                            printf(" %.5e",matcov[jj][ll]);
                               fprintf(ficlog," %.5e",matcov[jj][ll]);
     estepm=0;                          fprintf(ficres," %.5e",matcov[jj][ll]);
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);                        }
     if (estepm==0 || estepm < stepm) estepm=stepm;                      }
     if (fage <= 2) {                    }
       bage = ageminpar;                  } /* end lk */
       fage = agemaxpar;                } /* end lj */
     }              } /* end li */
                   if(mle>=1)
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");                printf("\n");
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);              fprintf(ficlog,"\n");
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);              fprintf(ficres,"\n");
                   numlinepar++;
     while((c=getc(ficpar))=='#' && c!= EOF){            } /* end k*/
       ungetc(c,ficpar);          } /*end j */
       fgets(line, MAXLINE, ficpar);        } /* end i */
       puts(line);      } /* end itimes */
       fputs(line,ficparo);     
     }      fflush(ficlog);
     ungetc(c,ficpar);      fflush(ficres);
          
     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);      while((c=getc(ficpar))=='#' && c!= EOF){
     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);        ungetc(c,ficpar);
     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);        fgets(line, MAXLINE, ficpar);
     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);        puts(line);
     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);        fputs(line,ficparo);
           }
     while((c=getc(ficpar))=='#' && c!= EOF){      ungetc(c,ficpar);
       ungetc(c,ficpar);     
       fgets(line, MAXLINE, ficpar);      estepm=0;
       puts(line);      fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
       fputs(line,ficparo);      if (estepm==0 || estepm < stepm) estepm=stepm;
     }      if (fage <= 2) {
     ungetc(c,ficpar);        bage = ageminpar;
             fage = agemaxpar;
           }
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;     
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
           fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
     fscanf(ficpar,"pop_based=%d\n",&popbased);      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
     fprintf(ficparo,"pop_based=%d\n",popbased);        
     fprintf(ficres,"pop_based=%d\n",popbased);         while((c=getc(ficpar))=='#' && c!= EOF){
             ungetc(c,ficpar);
     while((c=getc(ficpar))=='#' && c!= EOF){        fgets(line, MAXLINE, ficpar);
       ungetc(c,ficpar);        puts(line);
       fgets(line, MAXLINE, ficpar);        fputs(line,ficparo);
       puts(line);      }
       fputs(line,ficparo);      ungetc(c,ficpar);
     }     
     ungetc(c,ficpar);      fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
           fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
     fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);      fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
     fprintf(ficparo,"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("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
     printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      fprintf(ficlog,"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,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);     
     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      while((c=getc(ficpar))=='#' && c!= EOF){
     /* day and month of proj2 are not used but only year anproj2.*/        ungetc(c,ficpar);
             fgets(line, MAXLINE, ficpar);
             puts(line);
             fputs(line,ficparo);
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/      }
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/      ungetc(c,ficpar);
          
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */     
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);      dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
           dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\     
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\      fscanf(ficpar,"pop_based=%d\n",&popbased);
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);      fprintf(ficparo,"pop_based=%d\n",popbased);  
             fprintf(ficres,"pop_based=%d\n",popbased);  
    /*------------ free_vector  -------------*/     
    /*  chdir(path); */      while((c=getc(ficpar))=='#' && c!= EOF){
          ungetc(c,ficpar);
     free_ivector(wav,1,imx);        fgets(line, MAXLINE, ficpar);
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);        puts(line);
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);        fputs(line,ficparo);
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);         }
     free_lvector(num,1,n);      ungetc(c,ficpar);
     free_vector(agedc,1,n);     
     /*free_matrix(covar,0,NCOVMAX,1,n);*/      fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);
     /*free_matrix(covar,1,NCOVMAX,1,n);*/      fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
     fclose(ficparo);      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);
     fclose(ficres);      fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
       fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
       /* day and month of proj2 are not used but only year anproj2.*/
     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/     
        
     strcpy(filerespl,"pl");     
     strcat(filerespl,fileres);      /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
     if((ficrespl=fopen(filerespl,"w"))==NULL) {      /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;     
       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     }      printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);     
     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);      printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
     pstamp(ficrespl);                   model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
     fprintf(ficrespl,"# Period (stable) prevalence \n");                   jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
     fprintf(ficrespl,"#Age ");       
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);     /*------------ free_vector  -------------*/
     fprintf(ficrespl,"\n");     /*  chdir(path); */
      
     prlim=matrix(1,nlstate,1,nlstate);      free_ivector(wav,1,imx);
       free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
     agebase=ageminpar;      free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
     agelim=agemaxpar;      free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
     ftolpl=1.e-10;      free_lvector(num,1,n);
     i1=cptcoveff;      free_vector(agedc,1,n);
     if (cptcovn < 1){i1=1;}      /*free_matrix(covar,0,NCOVMAX,1,n);*/
       /*free_matrix(covar,1,NCOVMAX,1,n);*/
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      fclose(ficparo);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      fclose(ficres);
         k=k+1;  
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/  
         fprintf(ficrespl,"\n#******");      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
         printf("\n#******");   
         fprintf(ficlog,"\n#******");      strcpy(filerespl,"pl");
         for(j=1;j<=cptcoveff;j++) {      strcat(filerespl,fileres);
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      if((ficrespl=fopen(filerespl,"w"))==NULL) {
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
         }      }
         fprintf(ficrespl,"******\n");      printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
         printf("******\n");      fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
         fprintf(ficlog,"******\n");      pstamp(ficrespl);
               fprintf(ficrespl,"# Period (stable) prevalence \n");
         for (age=agebase; age<=agelim; age++){      fprintf(ficrespl,"#Age ");
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
           fprintf(ficrespl,"%.0f ",age );      fprintf(ficrespl,"\n");
           for(j=1;j<=cptcoveff;j++)   
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      prlim=matrix(1,nlstate,1,nlstate);
           for(i=1; i<=nlstate;i++)  
             fprintf(ficrespl," %.5f", prlim[i][i]);      agebase=ageminpar;
           fprintf(ficrespl,"\n");      agelim=agemaxpar;
         }      ftolpl=1.e-10;
       }      i1=cptcoveff;
     }      if (cptcovn < 1){i1=1;}
     fclose(ficrespl);  
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
     /*------------- h Pij x at various ages ------------*/        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
             k=k+1;
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);          /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
     if((ficrespij=fopen(filerespij,"w"))==NULL) {          fprintf(ficrespl,"\n#******");
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;          printf("\n#******");
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;          fprintf(ficlog,"\n#******");
     }          for(j=1;j<=cptcoveff;j++) {
     printf("Computing pij: result on file '%s' \n", filerespij);            fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);            printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
               fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     stepsize=(int) (stepm+YEARM-1)/YEARM;          }
     /*if (stepm<=24) stepsize=2;*/          fprintf(ficrespl,"******\n");
           printf("******\n");
     agelim=AGESUP;          fprintf(ficlog,"******\n");
     hstepm=stepsize*YEARM; /* Every year of age */         
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */           for (age=agebase; age<=agelim; age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
     /* hstepm=1;   aff par mois*/            fprintf(ficrespl,"%.0f ",age );
     pstamp(ficrespij);            for(j=1;j<=cptcoveff;j++)
     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");              fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){            for(i=1; i<=nlstate;i++)
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){              fprintf(ficrespl," %.5f", prlim[i][i]);
         k=k+1;            fprintf(ficrespl,"\n");
         fprintf(ficrespij,"\n#****** ");          }
         for(j=1;j<=cptcoveff;j++)         }
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      }
         fprintf(ficrespij,"******\n");      fclose(ficrespl);
           
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */      /*------------- h Pij x at various ages ------------*/
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */    
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */      strcpy(filerespij,"pij");  strcat(filerespij,fileres);
       if((ficrespij=fopen(filerespij,"w"))==NULL) {
           /*      nhstepm=nhstepm*YEARM; aff par mois*/        printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
         fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      }
           oldm=oldms;savm=savms;      printf("Computing pij: result on file '%s' \n", filerespij);
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");   
           for(i=1; i<=nlstate;i++)      stepsize=(int) (stepm+YEARM-1)/YEARM;
             for(j=1; j<=nlstate+ndeath;j++)      /*if (stepm<=24) stepsize=2;*/
               fprintf(ficrespij," %1d-%1d",i,j);  
           fprintf(ficrespij,"\n");      agelim=AGESUP;
           for (h=0; h<=nhstepm; h++){      hstepm=stepsize*YEARM; /* Every year of age */
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );      hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
             for(i=1; i<=nlstate;i++)  
               for(j=1; j<=nlstate+ndeath;j++)      /* hstepm=1;   aff par mois*/
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);      pstamp(ficrespij);
             fprintf(ficrespij,"\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++){
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           fprintf(ficrespij,"\n");          k=k+1;
         }          fprintf(ficrespij,"\n#****** ");
       }          for(j=1;j<=cptcoveff;j++)
     }            fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrespij,"******\n");
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);         
           for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
     fclose(ficrespij);            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
             nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);  
     for(i=1;i<=AGESUP;i++)            /*      nhstepm=nhstepm*YEARM; aff par mois*/
       for(j=1;j<=NCOVMAX;j++)  
         for(k=1;k<=NCOVMAX;k++)            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           probs[i][j][k]=0.;            oldm=oldms;savm=savms;
             hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
     /*---------- Forecasting ------------------*/            fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/            for(i=1; i<=nlstate;i++)
     if(prevfcast==1){              for(j=1; j<=nlstate+ndeath;j++)
       /*    if(stepm ==1){*/                fprintf(ficrespij," %1d-%1d",i,j);
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);            fprintf(ficrespij,"\n");
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/            for (h=0; h<=nhstepm; h++){
       /*      }  */              fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
       /*      else{ */              for(i=1; i<=nlstate;i++)
       /*        erreur=108; */                for(j=1; j<=nlstate+ndeath;j++)
       /*        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(ficrespij," %.5f", p3mat[i][j][h]);
       /*        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); */              fprintf(ficrespij,"\n");
       /*      } */            }
     }            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
               fprintf(ficrespij,"\n");
           }
     /*---------- Health expectancies and variances ------------*/        }
       }
     strcpy(filerest,"t");  
     strcat(filerest,fileres);      varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
     if((ficrest=fopen(filerest,"w"))==NULL) {  
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;      fclose(ficrespij);
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;  
     }      probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);       for(i=1;i<=AGESUP;i++)
     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);         for(j=1;j<=NCOVMAX;j++)
           for(k=1;k<=NCOVMAX;k++)
             probs[i][j][k]=0.;
     strcpy(filerese,"e");  
     strcat(filerese,fileres);      /*---------- Forecasting ------------------*/
     if((ficreseij=fopen(filerese,"w"))==NULL) {      /*if((stepm == 1) && (strcmp(model,".")==0)){*/
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);      if(prevfcast==1){
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);        /*    if(stepm ==1){*/
     }        prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);        /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);        /*      }  */
         /*      else{ */
     strcpy(fileresstde,"stde");        /*        erreur=108; */
     strcat(fileresstde,fileres);        /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {        /*        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); */
       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);        /*      } */
       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);      }
     }   
     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);  
     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);      /*---------- Health expectancies and variances ------------*/
   
     strcpy(filerescve,"cve");      strcpy(filerest,"t");
     strcat(filerescve,fileres);      strcat(filerest,fileres);
     if((ficrescveij=fopen(filerescve,"w"))==NULL) {      if((ficrest=fopen(filerest,"w"))==NULL) {
       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);        printf("Problem with total LE resultfile: %s\n", filerest);goto end;
       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);        fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
     }      }
     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
   
     strcpy(fileresv,"v");  
     strcat(fileresv,fileres);      strcpy(filerese,"e");
     if((ficresvij=fopen(fileresv,"w"))==NULL) {      strcat(filerese,fileres);
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);      if((ficreseij=fopen(filerese,"w"))==NULL) {
       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);        printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
     }        fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);      }
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);      printf("Computing Health Expectancies: result on file '%s' \n", filerese);
       fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
     /* 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);      strcpy(fileresstde,"stde");
     /*  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",\      strcat(fileresstde,fileres);
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);      if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
     */        printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
         fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
     if (mobilav!=0) {      }
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){      fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);  
         printf(" Error in movingaverage mobilav=%d\n",mobilav);      strcpy(filerescve,"cve");
       }      strcat(filerescve,fileres);
     }      if((ficrescveij=fopen(filerescve,"w"))==NULL) {
         printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){        fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      }
         k=k+1;       printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
         fprintf(ficrest,"\n#****** ");      fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
         for(j=1;j<=cptcoveff;j++)   
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      strcpy(fileresv,"v");
         fprintf(ficrest,"******\n");      strcat(fileresv,fileres);
       if((ficresvij=fopen(fileresv,"w"))==NULL) {
         fprintf(ficreseij,"\n#****** ");        printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
         fprintf(ficresstdeij,"\n#****** ");        fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
         fprintf(ficrescveij,"\n#****** ");      }
         for(j=1;j<=cptcoveff;j++) {      printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
           fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
           fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
           fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      /* 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);
         fprintf(ficreseij,"******\n");      /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
         fprintf(ficresstdeij,"******\n");          ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
         fprintf(ficrescveij,"******\n");      */
   
         fprintf(ficresvij,"\n#****** ");      if (mobilav!=0) {
         for(j=1;j<=cptcoveff;j++)         mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
         fprintf(ficresvij,"******\n");          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
           printf(" Error in movingaverage mobilav=%d\n",mobilav);
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);        }
         oldm=oldms;savm=savms;      }
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);    
         cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);        for(cptcov=1,k=0;cptcov<=i1;cptcov++){
          for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);          k=k+1;
         oldm=oldms;savm=savms;          fprintf(ficrest,"\n#****** ");
         varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);          for(j=1;j<=cptcoveff;j++)
         if(popbased==1){            fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);          fprintf(ficrest,"******\n");
         }  
           fprintf(ficreseij,"\n#****** ");
         pstamp(ficrest);          fprintf(ficresstdeij,"\n#****** ");
         fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");          fprintf(ficrescveij,"\n#****** ");
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);          for(j=1;j<=cptcoveff;j++) {
         fprintf(ficrest,"\n");            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]]);
         epj=vector(1,nlstate+1);            fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         for(age=bage; age <=fage ;age++){          }
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);          fprintf(ficreseij,"******\n");
           if (popbased==1) {          fprintf(ficresstdeij,"******\n");
             if(mobilav ==0){          fprintf(ficrescveij,"******\n");
               for(i=1; i<=nlstate;i++)  
                 prlim[i][i]=probs[(int)age][i][k];          fprintf(ficresvij,"\n#****** ");
             }else{ /* mobilav */           for(j=1;j<=cptcoveff;j++)
               for(i=1; i<=nlstate;i++)            fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                 prlim[i][i]=mobaverage[(int)age][i][k];          fprintf(ficresvij,"******\n");
             }  
           }          eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   oldm=oldms;savm=savms;
           fprintf(ficrest," %4.0f",age);          evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){          cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
             for(i=1, epj[j]=0.;i <=nlstate;i++) {   
               epj[j] += prlim[i][i]*eij[i][j][(int)age];          vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/          oldm=oldms;savm=savms;
             }          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);
             epj[nlstate+1] +=epj[j];          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);
           }
           for(i=1, vepp=0.;i <=nlstate;i++)  
             for(j=1;j <=nlstate;j++)          pstamp(ficrest);
               vepp += vareij[i][j][(int)age];          fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
           for(j=1;j <=nlstate;j++){          fprintf(ficrest,"\n");
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));  
           }          epj=vector(1,nlstate+1);
           fprintf(ficrest,"\n");          for(age=bage; age <=fage ;age++){
         }            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);            if (popbased==1) {
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);              if(mobilav ==0){
         free_vector(epj,1,nlstate+1);                for(i=1; i<=nlstate;i++)
       }                  prlim[i][i]=probs[(int)age][i][k];
     }              }else{ /* mobilav */
     free_vector(weight,1,n);                for(i=1; i<=nlstate;i++)
     free_imatrix(Tvard,1,15,1,2);                  prlim[i][i]=mobaverage[(int)age][i][k];
     free_imatrix(s,1,maxwav+1,1,n);              }
     free_matrix(anint,1,maxwav,1,n);             }
     free_matrix(mint,1,maxwav,1,n);         
     free_ivector(cod,1,n);            fprintf(ficrest," %4.0f",age);
     free_ivector(tab,1,NCOVMAX);            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
     fclose(ficreseij);              for(i=1, epj[j]=0.;i <=nlstate;i++) {
     fclose(ficresstdeij);                epj[j] += prlim[i][i]*eij[i][j][(int)age];
     fclose(ficrescveij);                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
     fclose(ficresvij);              }
     fclose(ficrest);              epj[nlstate+1] +=epj[j];
     fclose(ficpar);            }
     
     /*------- Variance of period (stable) prevalence------*/               for(i=1, vepp=0.;i <=nlstate;i++)
               for(j=1;j <=nlstate;j++)
     strcpy(fileresvpl,"vpl");                vepp += vareij[i][j][(int)age];
     strcat(fileresvpl,fileres);            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {            for(j=1;j <=nlstate;j++){
       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
       exit(0);            }
     }            fprintf(ficrest,"\n");
     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);          }
           free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){          free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){          free_vector(epj,1,nlstate+1);
         k=k+1;        }
         fprintf(ficresvpl,"\n#****** ");      }
         for(j=1;j<=cptcoveff;j++)       free_vector(weight,1,n);
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      free_imatrix(Tvard,1,15,1,2);
         fprintf(ficresvpl,"******\n");      free_imatrix(s,1,maxwav+1,1,n);
             free_matrix(anint,1,maxwav,1,n);
         varpl=matrix(1,nlstate,(int) bage, (int) fage);      free_matrix(mint,1,maxwav,1,n);
         oldm=oldms;savm=savms;      free_ivector(cod,1,n);
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);      free_ivector(tab,1,NCOVMAX);
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);      fclose(ficreseij);
       }      fclose(ficresstdeij);
     }      fclose(ficrescveij);
       fclose(ficresvij);
     fclose(ficresvpl);      fclose(ficrest);
       fclose(ficpar);
     /*---------- End : free ----------------*/   
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      /*------- Variance of period (stable) prevalence------*/  
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);  
       strcpy(fileresvpl,"vpl");
   }  /* mle==-3 arrives here for freeing */      strcat(fileresvpl,fileres);
   free_matrix(prlim,1,nlstate,1,nlstate);      if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);        printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);        exit(0);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);      }
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);      printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
     free_matrix(covar,0,NCOVMAX,1,n);  
     free_matrix(matcov,1,npar,1,npar);      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
     /*free_vector(delti,1,npar);*/        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);           k=k+1;
     free_matrix(agev,1,maxwav,1,imx);          fprintf(ficresvpl,"\n#****** ");
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);          for(j=1;j<=cptcoveff;j++)
             fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_ivector(ncodemax,1,8);          fprintf(ficresvpl,"******\n");
     free_ivector(Tvar,1,15);       
     free_ivector(Tprod,1,15);          varpl=matrix(1,nlstate,(int) bage, (int) fage);
     free_ivector(Tvaraff,1,15);          oldm=oldms;savm=savms;
     free_ivector(Tage,1,15);          varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
     free_ivector(Tcode,1,100);          free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
         }
     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);      }
     free_imatrix(codtab,1,100,1,10);  
   fflush(fichtm);      fclose(ficresvpl);
   fflush(ficgp);  
         /*---------- End : free ----------------*/
       if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if((nberr >0) || (nbwarn>0)){      free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
     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);    }  /* mle==-3 arrives here for freeing */
   }else{    free_matrix(prlim,1,nlstate,1,nlstate);
     printf("End of Imach\n");      free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
     fprintf(ficlog,"End of Imach\n");      free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
   }      free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
   printf("See log file on %s\n",filelog);      free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */      free_matrix(covar,0,NCOVMAX,1,n);
   (void) gettimeofday(&end_time,&tzp);      free_matrix(matcov,1,npar,1,npar);
   tm = *localtime(&end_time.tv_sec);      /*free_vector(delti,1,npar);*/
   tmg = *gmtime(&end_time.tv_sec);      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
   strcpy(strtend,asctime(&tm));      free_matrix(agev,1,maxwav,1,imx);
   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);       free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);   
   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));      free_ivector(ncodemax,1,8);
       free_ivector(Tvar,1,15);
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      free_ivector(Tprod,1,15);
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));      free_ivector(Tvaraff,1,15);
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      free_ivector(Tage,1,15);
   /*  printf("Total time was %d uSec.\n", total_usecs);*/      free_ivector(Tcode,1,100);
 /*   if(fileappend(fichtm,optionfilehtm)){ */  
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>",strstart, strtend);      free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
   fclose(fichtm);      free_imatrix(codtab,1,100,1,10);
   fclose(fichtmcov);    fflush(fichtm);
   fclose(ficgp);    fflush(ficgp);
   fclose(ficlog);   
   /*------ End -----------*/  
     if((nberr >0) || (nbwarn>0)){
       printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
    printf("Before Current directory %s!\n",pathcd);      fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
    if(chdir(pathcd) != 0)    }else{
     printf("Can't move to directory %s!\n",path);      printf("End of Imach\n");
   if(getcwd(pathcd,MAXLINE) > 0)      fprintf(ficlog,"End of Imach\n");
     printf("Current directory %s!\n",pathcd);    }
   /*strcat(plotcmd,CHARSEPARATOR);*/    printf("See log file on %s\n",filelog);
   sprintf(plotcmd,"gnuplot");    /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 #ifndef UNIX    (void) gettimeofday(&end_time,&tzp);
   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);    tm = *localtime(&end_time.tv_sec);
 #endif    tmg = *gmtime(&end_time.tv_sec);
   if(!stat(plotcmd,&info)){    strcpy(strtend,asctime(&tm));
     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);    printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);
     if(!stat(getenv("GNUPLOTBIN"),&info)){    fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend);
       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);    printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     }else  
       strcpy(pplotcmd,plotcmd);    printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
 #ifdef UNIX    fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     strcpy(plotcmd,GNUPLOTPROGRAM);    fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     if(!stat(plotcmd,&info)){    /*  printf("Total time was %d uSec.\n", total_usecs);*/
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);  /*   if(fileappend(fichtm,optionfilehtm)){ */
     }else    fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
       strcpy(pplotcmd,plotcmd);    fclose(fichtm);
 #endif    fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
   }else    fclose(fichtmcov);
     strcpy(pplotcmd,plotcmd);    fclose(ficgp);
       fclose(ficlog);
   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);    /*------ End -----------*/
   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);  
   
   if((outcmd=system(plotcmd)) != 0){     printf("Before Current directory %s!\n",pathcd);
     printf("\n Problem with gnuplot\n");     if(chdir(pathcd) != 0)
   }      printf("Can't move to directory %s!\n",path);
   printf(" Wait...");    if(getcwd(pathcd,MAXLINE) > 0)
   while (z[0] != 'q') {      printf("Current directory %s!\n",pathcd);
     /* chdir(path); */    /*strcat(plotcmd,CHARSEPARATOR);*/
     printf("\nType e to edit output files, g to graph again and q for exiting: ");    sprintf(plotcmd,"gnuplot");
     scanf("%s",z);  #ifndef UNIX
 /*     if (z[0] == 'c') system("./imach"); */    sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
     if (z[0] == 'e') {  #endif
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);    if(!stat(plotcmd,&info)){
       system(optionfilehtm);      printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
     }      if(!stat(getenv("GNUPLOTBIN"),&info)){
     else if (z[0] == 'g') system(plotcmd);        printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
     else if (z[0] == 'q') exit(0);      }else
   }        strcpy(pplotcmd,plotcmd);
   end:  #ifdef UNIX
   while (z[0] != 'q') {      strcpy(plotcmd,GNUPLOTPROGRAM);
     printf("\nType  q for exiting: ");      if(!stat(plotcmd,&info)){
     scanf("%s",z);        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.122  
changed lines
  Added in v.1.125


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