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

version 1.125, 2006/04/04 15:20:31 version 1.135, 2009/10/29 15:33:14
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
     Revision 1.135  2009/10/29 15:33:14  brouard
     (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
   
     Revision 1.134  2009/10/29 13:18:53  brouard
     (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
   
     Revision 1.133  2009/07/06 10:21:25  brouard
     just nforces
   
     Revision 1.132  2009/07/06 08:22:05  brouard
     Many tings
   
     Revision 1.131  2009/06/20 16:22:47  brouard
     Some dimensions resccaled
   
     Revision 1.130  2009/05/26 06:44:34  brouard
     (Module): Max Covariate is now set to 20 instead of 8. A
     lot of cleaning with variables initialized to 0. Trying to make
     V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
   
     Revision 1.129  2007/08/31 13:49:27  lievre
     Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
   
     Revision 1.128  2006/06/30 13:02:05  brouard
     (Module): Clarifications on computing e.j
   
     Revision 1.127  2006/04/28 18:11:50  brouard
     (Module): Yes the sum of survivors was wrong since
     imach-114 because nhstepm was no more computed in the age
     loop. Now we define nhstepma in the age loop.
     (Module): In order to speed up (in case of numerous covariates) we
     compute health expectancies (without variances) in a first step
     and then all the health expectancies with variances or standard
     deviation (needs data from the Hessian matrices) which slows the
     computation.
     In the future we should be able to stop the program is only health
     expectancies and graph are needed without standard deviations.
   
     Revision 1.126  2006/04/28 17:23:28  brouard
     (Module): Yes the sum of survivors was wrong since
     imach-114 because nhstepm was no more computed in the age
     loop. Now we define nhstepma in the age loop.
     Version 0.98h
   
   Revision 1.125  2006/04/04 15:20:31  lievre    Revision 1.125  2006/04/04 15:20:31  lievre
   Errors in calculation of health expectancies. Age was not initialized.    Errors in calculation of health expectancies. Age was not initialized.
   Forecasting file added.    Forecasting file added.
   
   Revision 1.124  2006/03/22 17:13:53  lievre    Revision 1.124  2006/03/22 17:13:53  lievre
   Parameters are printed with %lf instead of %f (more numbers after the comma).    Parameters are printed with %lf instead of %f (more numbers after the comma).
   The log-likelihood is printed in the log file    The log-likelihood is printed in the log file
   
   Revision 1.123  2006/03/20 10:52:43  brouard    Revision 1.123  2006/03/20 10:52:43  brouard
   * imach.c (Module): <title> changed, corresponds to .htm file    * imach.c (Module): <title> changed, corresponds to .htm file
   name. <head> headers where missing.    name. <head> headers where missing.
   
   * imach.c (Module): Weights can have a decimal point as for    * imach.c (Module): Weights can have a decimal point as for
   English (a comma might work with a correct LC_NUMERIC environment,    English (a comma might work with a correct LC_NUMERIC environment,
   otherwise the weight is truncated).    otherwise the weight is truncated).
   Modification of warning when the covariates values are not 0 or    Modification of warning when the covariates values are not 0 or
   1.    1.
   Version 0.98g    Version 0.98g
   
   Revision 1.122  2006/03/20 09:45:41  brouard    Revision 1.122  2006/03/20 09:45:41  brouard
   (Module): Weights can have a decimal point as for    (Module): Weights can have a decimal point as for
   English (a comma might work with a correct LC_NUMERIC environment,    English (a comma might work with a correct LC_NUMERIC environment,
   otherwise the weight is truncated).    otherwise the weight is truncated).
   Modification of warning when the covariates values are not 0 or    Modification of warning when the covariates values are not 0 or
   1.    1.
   Version 0.98g    Version 0.98g
   
   Revision 1.121  2006/03/16 17:45:01  lievre    Revision 1.121  2006/03/16 17:45:01  lievre
   * imach.c (Module): Comments concerning covariates added    * imach.c (Module): Comments concerning covariates added
   
   * imach.c (Module): refinements in the computation of lli if    * imach.c (Module): refinements in the computation of lli if
   status=-2 in order to have more reliable computation if stepm is    status=-2 in order to have more reliable computation if stepm is
   not 1 month. Version 0.98f    not 1 month. Version 0.98f
   
   Revision 1.120  2006/03/16 15:10:38  lievre    Revision 1.120  2006/03/16 15:10:38  lievre
   (Module): refinements in the computation of lli if    (Module): refinements in the computation of lli if
   status=-2 in order to have more reliable computation if stepm is    status=-2 in order to have more reliable computation if stepm is
   not 1 month. Version 0.98f    not 1 month. Version 0.98f
   
   Revision 1.119  2006/03/15 17:42:26  brouard    Revision 1.119  2006/03/15 17:42:26  brouard
   (Module): Bug if status = -2, the loglikelihood was    (Module): Bug if status = -2, the loglikelihood was
   computed as likelihood omitting the logarithm. Version O.98e    computed as likelihood omitting the logarithm. Version O.98e
   
   Revision 1.118  2006/03/14 18:20:07  brouard    Revision 1.118  2006/03/14 18:20:07  brouard
   (Module): varevsij Comments added explaining the second    (Module): varevsij Comments added explaining the second
   table of variances if popbased=1 .    table of variances if popbased=1 .
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   (Module): Function pstamp added    (Module): Function pstamp added
   (Module): Version 0.98d    (Module): Version 0.98d
   
   Revision 1.117  2006/03/14 17:16:22  brouard    Revision 1.117  2006/03/14 17:16:22  brouard
   (Module): varevsij Comments added explaining the second    (Module): varevsij Comments added explaining the second
   table of variances if popbased=1 .    table of variances if popbased=1 .
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   (Module): Function pstamp added    (Module): Function pstamp added
   (Module): Version 0.98d    (Module): Version 0.98d
   
   Revision 1.116  2006/03/06 10:29:27  brouard    Revision 1.116  2006/03/06 10:29:27  brouard
   (Module): Variance-covariance wrong links and    (Module): Variance-covariance wrong links and
   varian-covariance of ej. is needed (Saito).    varian-covariance of ej. is needed (Saito).
   
   Revision 1.115  2006/02/27 12:17:45  brouard    Revision 1.115  2006/02/27 12:17:45  brouard
   (Module): One freematrix added in mlikeli! 0.98c    (Module): One freematrix added in mlikeli! 0.98c
   
   Revision 1.114  2006/02/26 12:57:58  brouard    Revision 1.114  2006/02/26 12:57:58  brouard
   (Module): Some improvements in processing parameter    (Module): Some improvements in processing parameter
   filename with strsep.    filename with strsep.
   
   Revision 1.113  2006/02/24 14:20:24  brouard    Revision 1.113  2006/02/24 14:20:24  brouard
   (Module): Memory leaks checks with valgrind and:    (Module): Memory leaks checks with valgrind and:
   datafile was not closed, some imatrix were not freed and on matrix    datafile was not closed, some imatrix were not freed and on matrix
   allocation too.    allocation too.
   
   Revision 1.112  2006/01/30 09:55:26  brouard    Revision 1.112  2006/01/30 09:55:26  brouard
   (Module): Back to gnuplot.exe instead of wgnuplot.exe    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   
   Revision 1.111  2006/01/25 20:38:18  brouard    Revision 1.111  2006/01/25 20:38:18  brouard
   (Module): Lots of cleaning and bugs added (Gompertz)    (Module): Lots of cleaning and bugs added (Gompertz)
   (Module): Comments can be added in data file. Missing date values    (Module): Comments can be added in data file. Missing date values
   can be a simple dot '.'.    can be a simple dot '.'.
   
   Revision 1.110  2006/01/25 00:51:50  brouard    Revision 1.110  2006/01/25 00:51:50  brouard
   (Module): Lots of cleaning and bugs added (Gompertz)    (Module): Lots of cleaning and bugs added (Gompertz)
   
   Revision 1.109  2006/01/24 19:37:15  brouard    Revision 1.109  2006/01/24 19:37:15  brouard
   (Module): Comments (lines starting with a #) are allowed in data.    (Module): Comments (lines starting with a #) are allowed in data.
   
   Revision 1.108  2006/01/19 18:05:42  lievre    Revision 1.108  2006/01/19 18:05:42  lievre
   Gnuplot problem appeared...    Gnuplot problem appeared...
   To be fixed    To be fixed
   
   Revision 1.107  2006/01/19 16:20:37  brouard    Revision 1.107  2006/01/19 16:20:37  brouard
   Test existence of gnuplot in imach path    Test existence of gnuplot in imach path
   
   Revision 1.106  2006/01/19 13:24:36  brouard    Revision 1.106  2006/01/19 13:24:36  brouard
   Some cleaning and links added in html output    Some cleaning and links added in html output
   
   Revision 1.105  2006/01/05 20:23:19  lievre    Revision 1.105  2006/01/05 20:23:19  lievre
   *** empty log message ***    *** empty log message ***
   
   Revision 1.104  2005/09/30 16:11:43  lievre    Revision 1.104  2005/09/30 16:11:43  lievre
   (Module): sump fixed, loop imx fixed, and simplifications.    (Module): sump fixed, loop imx fixed, and simplifications.
   (Module): If the status is missing at the last wave but we know    (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    that the person is alive, then we can code his/her status as -2
   (instead of missing=-1 in earlier versions) and his/her    (instead of missing=-1 in earlier versions) and his/her
   contributions to the likelihood is 1 - Prob of dying from last    contributions to the likelihood is 1 - Prob of dying from last
   health status (= 1-p13= p11+p12 in the easiest case of somebody in    health status (= 1-p13= p11+p12 in the easiest case of somebody in
   the healthy state at last known wave). Version is 0.98    the healthy state at last known wave). Version is 0.98
   
   Revision 1.103  2005/09/30 15:54:49  lievre    Revision 1.103  2005/09/30 15:54:49  lievre
   (Module): sump fixed, loop imx fixed, and simplifications.    (Module): sump fixed, loop imx fixed, and simplifications.
   
   Revision 1.102  2004/09/15 17:31:30  brouard    Revision 1.102  2004/09/15 17:31:30  brouard
   Add the possibility to read data file including tab characters.    Add the possibility to read data file including tab characters.
   
   Revision 1.101  2004/09/15 10:38:38  brouard    Revision 1.101  2004/09/15 10:38:38  brouard
   Fix on curr_time    Fix on curr_time
   
   Revision 1.100  2004/07/12 18:29:06  brouard    Revision 1.100  2004/07/12 18:29:06  brouard
   Add version for Mac OS X. Just define UNIX in Makefile    Add version for Mac OS X. Just define UNIX in Makefile
   
   Revision 1.99  2004/06/05 08:57:40  brouard    Revision 1.99  2004/06/05 08:57:40  brouard
   *** empty log message ***    *** empty log message ***
   
   Revision 1.98  2004/05/16 15:05:56  brouard    Revision 1.98  2004/05/16 15:05:56  brouard
   New version 0.97 . First attempt to estimate force of mortality    New version 0.97 . First attempt to estimate force of mortality
   directly from the data i.e. without the need of knowing the health    directly from the data i.e. without the need of knowing the health
   state at each age, but using a Gompertz model: log u =a + b*age .    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    This is the basic analysis of mortality and should be done before any
   other analysis, in order to test if the mortality estimated from the    other analysis, in order to test if the mortality estimated from the
   cross-longitudinal survey is different from the mortality estimated    cross-longitudinal survey is different from the mortality estimated
   from other sources like vital statistic data.    from other sources like vital statistic data.
   
   The same imach parameter file can be used but the option for mle should be -3.    The same imach parameter file can be used but the option for mle should be -3.
   
   Agnès, who wrote this part of the code, tried to keep most of the    Agnès, who wrote this part of the code, tried to keep most of the
   former routines in order to include the new code within the former code.    former routines in order to include the new code within the former code.
   
   The output is very simple: only an estimate of the intercept and of    The output is very simple: only an estimate of the intercept and of
   the slope with 95% confident intervals.    the slope with 95% confident intervals.
   
   Current limitations:    Current limitations:
   A) Even if you enter covariates, i.e. with the    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.    model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   B) There is no computation of Life Expectancy nor Life Table.    B) There is no computation of Life Expectancy nor Life Table.
   
   Revision 1.97  2004/02/20 13:25:42  lievre    Revision 1.97  2004/02/20 13:25:42  lievre
   Version 0.96d. Population forecasting command line is (temporarily)    Version 0.96d. Population forecasting command line is (temporarily)
   suppressed.    suppressed.
   
   Revision 1.96  2003/07/15 15:38:55  brouard    Revision 1.96  2003/07/15 15:38:55  brouard
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   rewritten within the same printf. Workaround: many printfs.    rewritten within the same printf. Workaround: many printfs.
   
   Revision 1.95  2003/07/08 07:54:34  brouard    Revision 1.95  2003/07/08 07:54:34  brouard
   * imach.c (Repository):    * imach.c (Repository):
   (Repository): Using imachwizard code to output a more meaningful covariance    (Repository): Using imachwizard code to output a more meaningful covariance
   matrix (cov(a12,c31) instead of numbers.    matrix (cov(a12,c31) instead of numbers.
   
   Revision 1.94  2003/06/27 13:00:02  brouard    Revision 1.94  2003/06/27 13:00:02  brouard
   Just cleaning    Just cleaning
   
   Revision 1.93  2003/06/25 16:33:55  brouard    Revision 1.93  2003/06/25 16:33:55  brouard
   (Module): On windows (cygwin) function asctime_r doesn't    (Module): On windows (cygwin) function asctime_r doesn't
   exist so I changed back to asctime which exists.    exist so I changed back to asctime which exists.
   (Module): Version 0.96b    (Module): Version 0.96b
   
   Revision 1.92  2003/06/25 16:30:45  brouard    Revision 1.92  2003/06/25 16:30:45  brouard
   (Module): On windows (cygwin) function asctime_r doesn't    (Module): On windows (cygwin) function asctime_r doesn't
   exist so I changed back to asctime which exists.    exist so I changed back to asctime which exists.
   
   Revision 1.91  2003/06/25 15:30:29  brouard    Revision 1.91  2003/06/25 15:30:29  brouard
   * imach.c (Repository): Duplicated warning errors corrected.    * imach.c (Repository): Duplicated warning errors corrected.
   (Repository): Elapsed time after each iteration is now output. It    (Repository): Elapsed time after each iteration is now output. It
   helps to forecast when convergence will be reached. Elapsed time    helps to forecast when convergence will be reached. Elapsed time
   is stamped in powell.  We created a new html file for the graphs    is stamped in powell.  We created a new html file for the graphs
   concerning matrix of covariance. It has extension -cov.htm.    concerning matrix of covariance. It has extension -cov.htm.
   
   Revision 1.90  2003/06/24 12:34:15  brouard    Revision 1.90  2003/06/24 12:34:15  brouard
   (Module): Some bugs corrected for windows. Also, when    (Module): Some bugs corrected for windows. Also, when
   mle=-1 a template is output in file "or"mypar.txt with the design    mle=-1 a template is output in file "or"mypar.txt with the design
   of the covariance matrix to be input.    of the covariance matrix to be input.
   
   Revision 1.89  2003/06/24 12:30:52  brouard    Revision 1.89  2003/06/24 12:30:52  brouard
   (Module): Some bugs corrected for windows. Also, when    (Module): Some bugs corrected for windows. Also, when
   mle=-1 a template is output in file "or"mypar.txt with the design    mle=-1 a template is output in file "or"mypar.txt with the design
   of the covariance matrix to be input.    of the covariance matrix to be input.
   
   Revision 1.88  2003/06/23 17:54:56  brouard    Revision 1.88  2003/06/23 17:54:56  brouard
   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.    * 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.87  2003/06/18 12:26:01  brouard    Revision 1.87  2003/06/18 12:26:01  brouard
   Version 0.96    Version 0.96
   
   Revision 1.86  2003/06/17 20:04:08  brouard    Revision 1.86  2003/06/17 20:04:08  brouard
   (Module): Change position of html and gnuplot routines and added    (Module): Change position of html and gnuplot routines and added
   routine fileappend.    routine fileappend.
   
   Revision 1.85  2003/06/17 13:12:43  brouard    Revision 1.85  2003/06/17 13:12:43  brouard
   * imach.c (Repository): Check when date of death was earlier that    * imach.c (Repository): Check when date of death was earlier that
   current date of interview. It may happen when the death was just    current date of interview. It may happen when the death was just
   prior to the death. In this case, dh was negative and likelihood    prior to the death. In this case, dh was negative and likelihood
   was wrong (infinity). We still send an "Error" but patch by    was wrong (infinity). We still send an "Error" but patch by
   assuming that the date of death was just one stepm after the    assuming that the date of death was just one stepm after the
   interview.    interview.
   (Repository): Because some people have very long ID (first column)    (Repository): Because some people have very long ID (first column)
   we changed int to long in num[] and we added a new lvector for    we changed int to long in num[] and we added a new lvector for
   memory allocation. But we also truncated to 8 characters (left    memory allocation. But we also truncated to 8 characters (left
   truncation)    truncation)
   (Repository): No more line truncation errors.    (Repository): No more line truncation errors.
   
   Revision 1.84  2003/06/13 21:44:43  brouard    Revision 1.84  2003/06/13 21:44:43  brouard
   * imach.c (Repository): Replace "freqsummary" at a correct    * imach.c (Repository): Replace "freqsummary" at a correct
   place. It differs from routine "prevalence" which may be called    place. It differs from routine "prevalence" which may be called
   many times. Probs is memory consuming and must be used with    many times. Probs is memory consuming and must be used with
   parcimony.    parcimony.
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
   
   Revision 1.83  2003/06/10 13:39:11  lievre    Revision 1.83  2003/06/10 13:39:11  lievre
   *** empty log message ***    *** empty log message ***
   
   Revision 1.82  2003/06/05 15:57:20  brouard    Revision 1.82  2003/06/05 15:57:20  brouard
   Add log in  imach.c and  fullversion number is now printed.    Add log in  imach.c and  fullversion number is now printed.
   
 */  */
 /*  /*
    Interpolated Markov Chain     Interpolated Markov Chain
   
   Short summary of the programme:    Short summary of the programme:
      
   This program computes Healthy Life Expectancies from    This program computes Healthy Life Expectancies from
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
   first survey ("cross") where individuals from different ages are    first survey ("cross") where individuals from different ages are
   interviewed on their health status or degree of disability (in the    interviewed on their health status or degree of disability (in the
   case of a health survey which is our main interest) -2- at least a    case of a health survey which is our main interest) -2- at least a
   second wave of interviews ("longitudinal") which measure each change    second wave of interviews ("longitudinal") which measure each change
   (if any) in individual health status.  Health expectancies are    (if any) in individual health status.  Health expectancies are
   computed from the time spent in each health state according to a    computed from the time spent in each health state according to a
   model. More health states you consider, more time is necessary to reach the    model. More health states you consider, more time is necessary to reach the
   Maximum Likelihood of the parameters involved in the model.  The    Maximum Likelihood of the parameters involved in the model.  The
   simplest model is the multinomial logistic model where pij is the    simplest model is the multinomial logistic model where pij is the
   probability to be observed in state j at the second wave    probability to be observed in state j at the second wave
   conditional to be observed in state i at the first wave. Therefore    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    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    '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    complex model than "constant and age", you should modify the program
   where the markup *Covariates have to be included here again* invites    where the markup *Covariates have to be included here again* invites
   you to do it.  More covariates you add, slower the    you to do it.  More covariates you add, slower the
   convergence.    convergence.
   
   The advantage of this computer programme, compared to a simple    The advantage of this computer programme, compared to a simple
   multinomial logistic model, is clear when the delay between waves is not    multinomial logistic model, is clear when the delay between waves is not
   identical for each individual. Also, if a individual missed an    identical for each individual. Also, if a individual missed an
   intermediate interview, the information is lost, but taken into    intermediate interview, the information is lost, but taken into
   account using an interpolation or extrapolation.      account using an interpolation or extrapolation.  
   
   hPijx is the probability to be observed in state i at age x+h    hPijx is the probability to be observed in state i at age x+h
   conditional to the observed state i at age x. The delay 'h' can be    conditional to the observed state i at age x. The delay 'h' can be
   split into an exact number (nh*stepm) of unobserved intermediate    split into an exact number (nh*stepm) of unobserved intermediate
   states. This elementary transition (by month, quarter,    states. This elementary transition (by month, quarter,
   semester or year) is modelled as a multinomial logistic.  The hPx    semester or year) is modelled as a multinomial logistic.  The hPx
   matrix is simply the matrix product of nh*stepm elementary matrices    matrix is simply the matrix product of nh*stepm elementary matrices
   and the contribution of each individual to the likelihood is simply    and the contribution of each individual to the likelihood is simply
   hPijx.    hPijx.
   
   Also this programme outputs the covariance matrix of the parameters but also    Also this programme outputs the covariance matrix of the parameters but also
   of the life expectancies. It also computes the period (stable) prevalence.    of the life expectancies. It also computes the period (stable) prevalence. 
      
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
            Institut national d'études démographiques, Paris.             Institut national d'études démographiques, Paris.
   This software have been partly granted by Euro-REVES, a concerted action    This software have been partly granted by Euro-REVES, a concerted action
   from the European Union.    from the European Union.
   It is copyrighted identically to a GNU software product, ie programme and    It is copyrighted identically to a GNU software product, ie programme and
   software can be distributed freely for non commercial use. Latest version    software can be distributed freely for non commercial use. Latest version
   can be accessed at http://euroreves.ined.fr/imach .    can be accessed at http://euroreves.ined.fr/imach .
   
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
      
   **********************************************************************/    **********************************************************************/
 /*  /*
   main    main
   read parameterfile    read parameterfile
   read datafile    read datafile
   concatwav    concatwav
   freqsummary    freqsummary
   if (mle >= 1)    if (mle >= 1)
     mlikeli      mlikeli
   print results files    print results files
   if mle==1    if mle==1 
      computes hessian       computes hessian
   read end of parameter file: agemin, agemax, bage, fage, estepm    read end of parameter file: agemin, agemax, bage, fage, estepm
       begin-prev-date,...        begin-prev-date,...
   open gnuplot file    open gnuplot file
   open html file    open html file
   period (stable) prevalence    period (stable) prevalence
    for age prevalim()     for age prevalim()
   h Pij x    h Pij x
   variance of p varprob    variance of p varprob
   forecasting if prevfcast==1 prevforecast call prevalence()    forecasting if prevfcast==1 prevforecast call prevalence()
   health expectancies    health expectancies
   Variance-covariance of DFLE    Variance-covariance of DFLE
   prevalence()    prevalence()
    movingaverage()     movingaverage()
   varevsij()    varevsij() 
   if popbased==1 varevsij(,popbased)    if popbased==1 varevsij(,popbased)
   total life expectancies    total life expectancies
   Variance of period (stable) prevalence    Variance of period (stable) prevalence
  end   end
 */  */
   
   
   
     
 #include <math.h>  #include <math.h>
 #include <stdio.h>  #include <stdio.h>
 #include <stdlib.h>  #include <stdlib.h>
 #include <string.h>  #include <string.h>
 #include <unistd.h>  #include <unistd.h>
   
 #include <limits.h>  #include <limits.h>
 #include <sys/types.h>  #include <sys/types.h>
 #include <sys/stat.h>  #include <sys/stat.h>
 #include <errno.h>  #include <errno.h>
 extern int errno;  extern int errno;
   
 /* #include <sys/time.h> */  /* #include <sys/time.h> */
 #include <time.h>  #include <time.h>
 #include "timeval.h"  #include "timeval.h"
   
 /* #include <libintl.h> */  /* #include <libintl.h> */
 /* #define _(String) gettext (String) */  /* #define _(String) gettext (String) */
   
 #define MAXLINE 256  #define MAXLINE 256
   
 #define GNUPLOTPROGRAM "gnuplot"  #define GNUPLOTPROGRAM "gnuplot"
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/  /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 #define FILENAMELENGTH 132  #define FILENAMELENGTH 132
   
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
   
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */  #define MAXPARM 128 /* Maximum number of parameters for the optimization */
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
   
 #define NINTERVMAX 8  #define NINTERVMAX 8
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 #define NCOVMAX 8 /* Maximum number of covariates */  #define NCOVMAX 20 /* Maximum number of covariates */
 #define MAXN 20000  #define MAXN 20000
 #define YEARM 12. /* Number of months per year */  #define YEARM 12. /* Number of months per year */
 #define AGESUP 130  #define AGESUP 130
 #define AGEBASE 40  #define AGEBASE 40
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 #ifdef UNIX  #ifdef UNIX
 #define DIRSEPARATOR '/'  #define DIRSEPARATOR '/'
 #define CHARSEPARATOR "/"  #define CHARSEPARATOR "/"
 #define ODIRSEPARATOR '\\'  #define ODIRSEPARATOR '\\'
 #else  #else
 #define DIRSEPARATOR '\\'  #define DIRSEPARATOR '\\'
 #define CHARSEPARATOR "\\"  #define CHARSEPARATOR "\\"
 #define ODIRSEPARATOR '/'  #define ODIRSEPARATOR '/'
 #endif  #endif
   
 /* $Id$ */  /* $Id$ */
 /* $State$ */  /* $State$ */
   
 char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";  char version[]="Imach version 0.98l, October 2009, INED-EUROREVES-Institut de longevite ";
 char fullversion[]="$Revision$ $Date$";  char fullversion[]="$Revision$ $Date$"; 
 char strstart[80];  char strstart[80];
 char optionfilext[10], optionfilefiname[FILENAMELENGTH];  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */  int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 int nvar;  int nvar=0, nforce=0; /* Number of variables, number of forces */
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov=0; /* Number of covariates, of covariates with '*age' */
 int npar=NPARMAX;  int npar=NPARMAX;
 int nlstate=2; /* Number of live states */  int nlstate=2; /* Number of live states */
 int ndeath=1; /* Number of dead states */  int ndeath=1; /* Number of dead states */
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */  int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 int popbased=0;  int popbased=0;
   
 int *wav; /* Number of waves for this individuual 0 is possible */  int *wav; /* Number of waves for this individuual 0 is possible */
 int maxwav; /* Maxim number of waves */  int maxwav=0; /* Maxim number of waves */
 int jmin, jmax; /* min, max spacing between 2 waves */  int jmin=0, jmax=0; /* min, max spacing between 2 waves */
 int ijmin, ijmax; /* Individuals having jmin and jmax */  int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
 int gipmx, gsw; /* Global variables on the number of contributions  int gipmx=0, gsw=0; /* Global variables on the number of contributions 
                    to the likelihood and the sum of weights (done by funcone)*/                     to the likelihood and the sum of weights (done by funcone)*/
 int mle, weightopt;  int mle=1, weightopt=0;
 int **mw; /* mw[mi][i] is number of the mi wave for this individual */  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
            * wave mi and wave mi+1 is not an exact multiple of stepm. */             * wave mi and wave mi+1 is not an exact multiple of stepm. */
 double jmean; /* Mean space between 2 waves */  double jmean=1; /* Mean space between 2 waves */
 double **oldm, **newm, **savm; /* Working pointers to matrices */  double **oldm, **newm, **savm; /* Working pointers to matrices */
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
 FILE *ficlog, *ficrespow;  FILE *ficlog, *ficrespow;
 int globpr; /* Global variable for printing or not */  int globpr=0; /* Global variable for printing or not */
 double fretone; /* Only one call to likelihood */  double fretone; /* Only one call to likelihood */
 long ipmx; /* Number of contributions */  long ipmx=0; /* Number of contributions */
 double sw; /* Sum of weights */  double sw; /* Sum of weights */
 char filerespow[FILENAMELENGTH];  char filerespow[FILENAMELENGTH];
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 FILE *ficresilk;  FILE *ficresilk;
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;  FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 FILE *ficresprobmorprev;  FILE *ficresprobmorprev;
 FILE *fichtm, *fichtmcov; /* Html File */  FILE *fichtm, *fichtmcov; /* Html File */
 FILE *ficreseij;  FILE *ficreseij;
 char filerese[FILENAMELENGTH];  char filerese[FILENAMELENGTH];
 FILE *ficresstdeij;  FILE *ficresstdeij;
 char fileresstde[FILENAMELENGTH];  char fileresstde[FILENAMELENGTH];
 FILE *ficrescveij;  FILE *ficrescveij;
 char filerescve[FILENAMELENGTH];  char filerescve[FILENAMELENGTH];
 FILE  *ficresvij;  FILE  *ficresvij;
 char fileresv[FILENAMELENGTH];  char fileresv[FILENAMELENGTH];
 FILE  *ficresvpl;  FILE  *ficresvpl;
 char fileresvpl[FILENAMELENGTH];  char fileresvpl[FILENAMELENGTH];
 char title[MAXLINE];  char title[MAXLINE];
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
 char command[FILENAMELENGTH];  char command[FILENAMELENGTH];
 int  outcmd=0;  int  outcmd=0;
   
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
   
 char filelog[FILENAMELENGTH]; /* Log file */  char filelog[FILENAMELENGTH]; /* Log file */
 char filerest[FILENAMELENGTH];  char filerest[FILENAMELENGTH];
 char fileregp[FILENAMELENGTH];  char fileregp[FILENAMELENGTH];
 char popfile[FILENAMELENGTH];  char popfile[FILENAMELENGTH];
   
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
   
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  struct timeval start_time, end_time, curr_time, last_time, forecast_time;
 struct timezone tzp;  struct timezone tzp;
 extern int gettimeofday();  extern int gettimeofday();
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  struct tm tmg, tm, tmf, *gmtime(), *localtime();
 long time_value;  long time_value;
 extern long time();  extern long time();
 char strcurr[80], strfor[80];  char strcurr[80], strfor[80];
   
 char *endptr;  char *endptr;
 long lval;  long lval;
 double dval;  double dval;
   
 #define NR_END 1  #define NR_END 1
 #define FREE_ARG char*  #define FREE_ARG char*
 #define FTOL 1.0e-10  #define FTOL 1.0e-10
   
 #define NRANSI  #define NRANSI 
 #define ITMAX 200  #define ITMAX 200 
   
 #define TOL 2.0e-4  #define TOL 2.0e-4 
   
 #define CGOLD 0.3819660  #define CGOLD 0.3819660 
 #define ZEPS 1.0e-10  #define ZEPS 1.0e-10 
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
   
 #define GOLD 1.618034  #define GOLD 1.618034 
 #define GLIMIT 100.0  #define GLIMIT 100.0 
 #define TINY 1.0e-20  #define TINY 1.0e-20 
   
 static double maxarg1,maxarg2;  static double maxarg1,maxarg2;
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  #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 FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
      
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 #define rint(a) floor(a+0.5)  #define rint(a) floor(a+0.5)
   
 static double sqrarg;  static double sqrarg;
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
 int agegomp= AGEGOMP;  int agegomp= AGEGOMP;
   
 int imx;  int imx; 
 int stepm=1;  int stepm=1;
 /* Stepm, step in month: minimum step interpolation*/  /* Stepm, step in month: minimum step interpolation*/
   
 int estepm;  int estepm;
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   
 int m,nb;  int m,nb;
 long *num;  long *num;
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 double **pmmij, ***probs;  double **pmmij, ***probs;
 double *ageexmed,*agecens;  double *ageexmed,*agecens;
 double dateintmean=0;  double dateintmean=0;
   
 double *weight;  double *weight;
 int **s; /* Status */  int **s; /* Status */
 double *agedc, **covar, idx;  double *agedc, **covar, idx;
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  int **nbcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
 double *lsurv, *lpop, *tpop;  double *lsurv, *lpop, *tpop;
   
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  double ftol=FTOL; /* Tolerance for computing Max Likelihood */
 double ftolhess; /* Tolerance for computing hessian */  double ftolhess; /* Tolerance for computing hessian */
   
 /**************** split *************************/  /**************** split *************************/
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
 {  {
   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
      the name of the file (name), its extension only (ext) and its first part of the name (finame)       the name of the file (name), its extension only (ext) and its first part of the name (finame)
   */    */ 
   char  *ss;                            /* pointer */    char  *ss;                            /* pointer */
   int   l1, l2;                         /* length counters */    int   l1, l2;                         /* length counters */
   
   l1 = strlen(path );                   /* length of path */    l1 = strlen(path );                   /* length of path */
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
   if ( ss == NULL ) {                   /* no directory, so determine current directory */    if ( ss == NULL ) {                   /* no directory, so determine current directory */
     strcpy( name, path );               /* we got the fullname name because no directory */      strcpy( name, path );               /* we got the fullname name because no directory */
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
     /* get current working directory */      /* get current working directory */
     /*    extern  char* getcwd ( char *buf , int len);*/      /*    extern  char* getcwd ( char *buf , int len);*/
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
       return( GLOCK_ERROR_GETCWD );        return( GLOCK_ERROR_GETCWD );
     }      }
     /* got dirc from getcwd*/      /* got dirc from getcwd*/
     printf(" DIRC = %s \n",dirc);      printf(" DIRC = %s \n",dirc);
   } else {                              /* strip direcotry from path */    } else {                              /* strip direcotry from path */
     ss++;                               /* after this, the filename */      ss++;                               /* after this, the filename */
     l2 = strlen( ss );                  /* length of filename */      l2 = strlen( ss );                  /* length of filename */
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );      if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
     strcpy( name, ss );         /* save file name */      strcpy( name, ss );         /* save file name */
     strncpy( dirc, path, l1 - l2 );     /* now the directory */      strncpy( dirc, path, l1 - l2 );     /* now the directory */
     dirc[l1-l2] = 0;                    /* add zero */      dirc[l1-l2] = 0;                    /* add zero */
     printf(" DIRC2 = %s \n",dirc);      printf(" DIRC2 = %s \n",dirc);
   }    }
   /* We add a separator at the end of dirc if not exists */    /* We add a separator at the end of dirc if not exists */
   l1 = strlen( dirc );                  /* length of directory */    l1 = strlen( dirc );                  /* length of directory */
   if( dirc[l1-1] != DIRSEPARATOR ){    if( dirc[l1-1] != DIRSEPARATOR ){
     dirc[l1] =  DIRSEPARATOR;      dirc[l1] =  DIRSEPARATOR;
     dirc[l1+1] = 0;      dirc[l1+1] = 0; 
     printf(" DIRC3 = %s \n",dirc);      printf(" DIRC3 = %s \n",dirc);
   }    }
   ss = strrchr( name, '.' );            /* find last / */    ss = strrchr( name, '.' );            /* find last / */
   if (ss >0){    if (ss >0){
     ss++;      ss++;
     strcpy(ext,ss);                     /* save extension */      strcpy(ext,ss);                     /* save extension */
     l1= strlen( name);      l1= strlen( name);
     l2= strlen(ss)+1;      l2= strlen(ss)+1;
     strncpy( finame, name, l1-l2);      strncpy( finame, name, l1-l2);
     finame[l1-l2]= 0;      finame[l1-l2]= 0;
   }    }
   
   return( 0 );                          /* we're done */    return( 0 );                          /* we're done */
 }  }
   
   
 /******************************************/  /******************************************/
   
 void replace_back_to_slash(char *s, char*t)  void replace_back_to_slash(char *s, char*t)
 {  {
   int i;    int i;
   int lg=0;    int lg=0;
   i=0;    i=0;
   lg=strlen(t);    lg=strlen(t);
   for(i=0; i<= lg; i++) {    for(i=0; i<= lg; i++) {
     (s[i] = t[i]);      (s[i] = t[i]);
     if (t[i]== '\\') s[i]='/';      if (t[i]== '\\') s[i]='/';
   }    }
 }  }
   
 int nbocc(char *s, char occ)  char *trimbb(char *out, char *in)
 {  { /* Trim multiple blanks in line */
   int i,j=0;    char *s;
   int lg=20;    s=out;
   i=0;    while (*in != '\0'){
   lg=strlen(s);      while( *in == ' ' && *(in+1) == ' ' && *(in+1) != '\0'){
   for(i=0; i<= lg; i++) {        in++;
   if  (s[i] == occ ) j++;      }
   }      *out++ = *in++;
   return j;    }
 }    *out='\0';
     return s;
 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'  int nbocc(char *s, char occ)
      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')  {
      gives u="abcedf" and v="ghi2j" */    int i,j=0;
   int i,lg,j,p=0;    int lg=20;
   i=0;    i=0;
   for(j=0; j<=strlen(t)-1; j++) {    lg=strlen(s);
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;    for(i=0; i<= lg; i++) {
   }    if  (s[i] == occ ) j++;
     }
   lg=strlen(t);    return j;
   for(j=0; j<p; j++) {  }
     (u[j] = t[j]);  
   }  void cutv(char *u,char *v, char*t, char occ)
      u[p]='\0';  {
     /* cuts string t into u and v where u ends before first occurence of char 'occ' 
    for(j=0; j<= lg; j++) {       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
     if (j>=(p+1))(v[j-p-1] = t[j]);       gives u="abcedf" and v="ghi2j" */
   }    int i,lg,j,p=0;
 }    i=0;
     for(j=0; j<=strlen(t)-1; j++) {
 /********************** nrerror ********************/      if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
     }
 void nrerror(char error_text[])  
 {    lg=strlen(t);
   fprintf(stderr,"ERREUR ...\n");    for(j=0; j<p; j++) {
   fprintf(stderr,"%s\n",error_text);      (u[j] = t[j]);
   exit(EXIT_FAILURE);    }
 }       u[p]='\0';
 /*********************** vector *******************/  
 double *vector(int nl, int nh)     for(j=0; j<= lg; j++) {
 {      if (j>=(p+1))(v[j-p-1] = t[j]);
   double *v;    }
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));  }
   if (!v) nrerror("allocation failure in vector");  
   return v-nl+NR_END;  /********************** nrerror ********************/
 }  
   void nrerror(char error_text[])
 /************************ free vector ******************/  {
 void free_vector(double*v, int nl, int nh)    fprintf(stderr,"ERREUR ...\n");
 {    fprintf(stderr,"%s\n",error_text);
   free((FREE_ARG)(v+nl-NR_END));    exit(EXIT_FAILURE);
 }  }
   /*********************** vector *******************/
 /************************ivector *******************************/  double *vector(int nl, int nh)
 int *ivector(long nl,long nh)  {
 {    double *v;
   int *v;    v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));    if (!v) nrerror("allocation failure in vector");
   if (!v) nrerror("allocation failure in ivector");    return v-nl+NR_END;
   return v-nl+NR_END;  }
 }  
   /************************ free vector ******************/
 /******************free ivector **************************/  void free_vector(double*v, int nl, int nh)
 void free_ivector(int *v, long nl, long nh)  {
 {    free((FREE_ARG)(v+nl-NR_END));
   free((FREE_ARG)(v+nl-NR_END));  }
 }  
   /************************ivector *******************************/
 /************************lvector *******************************/  int *ivector(long nl,long nh)
 long *lvector(long nl,long nh)  {
 {    int *v;
   long *v;    v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));    if (!v) nrerror("allocation failure in ivector");
   if (!v) nrerror("allocation failure in ivector");    return v-nl+NR_END;
   return v-nl+NR_END;  }
 }  
   /******************free ivector **************************/
 /******************free lvector **************************/  void free_ivector(int *v, long nl, long nh)
 void free_lvector(long *v, long nl, long nh)  {
 {    free((FREE_ARG)(v+nl-NR_END));
   free((FREE_ARG)(v+nl-NR_END));  }
 }  
   /************************lvector *******************************/
 /******************* imatrix *******************************/  long *lvector(long nl,long nh)
 int **imatrix(long nrl, long nrh, long ncl, long nch)  {
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */    long *v;
 {    v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;    if (!v) nrerror("allocation failure in ivector");
   int **m;    return v-nl+NR_END;
    }
   /* allocate pointers to rows */  
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));  /******************free lvector **************************/
   if (!m) nrerror("allocation failure 1 in matrix()");  void free_lvector(long *v, long nl, long nh)
   m += NR_END;  {
   m -= nrl;    free((FREE_ARG)(v+nl-NR_END));
    }
    
   /* allocate rows and set pointers to them */  /******************* imatrix *******************************/
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));  int **imatrix(long nrl, long nrh, long ncl, long nch) 
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");       /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
   m[nrl] += NR_END;  { 
   m[nrl] -= ncl;    long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
      int **m; 
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;    
      /* allocate pointers to rows */ 
   /* return pointer to array of pointers to rows */    m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
   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)    
       int **m;    /* allocate rows and set pointers to them */ 
       long nch,ncl,nrh,nrl;    m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
      /* free an int matrix allocated by imatrix() */    if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 {    m[nrl] += NR_END; 
   free((FREE_ARG) (m[nrl]+ncl-NR_END));    m[nrl] -= ncl; 
   free((FREE_ARG) (m+nrl-NR_END));    
 }    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
     
 /******************* matrix *******************************/    /* return pointer to array of pointers to rows */ 
 double **matrix(long nrl, long nrh, long ncl, long nch)    return m; 
 {  } 
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;  
   double **m;  /****************** free_imatrix *************************/
   void free_imatrix(m,nrl,nrh,ncl,nch)
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));        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)); 
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));    free((FREE_ARG) (m+nrl-NR_END)); 
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  } 
   m[nrl] += NR_END;  
   m[nrl] -= ncl;  /******************* matrix *******************************/
   double **matrix(long nrl, long nrh, long ncl, long nch)
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;  {
   return m;    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])    double **m;
    */  
 }    m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
     if (!m) nrerror("allocation failure 1 in matrix()");
 /*************************free matrix ************************/    m += NR_END;
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)    m -= nrl;
 {  
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   free((FREE_ARG)(m+nrl-NR_END));    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 }    m[nrl] += NR_END;
     m[nrl] -= ncl;
 /******************* ma3x *******************************/  
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 {    return m;
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;    /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) 
   double ***m;     */
   }
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  
   if (!m) nrerror("allocation failure 1 in matrix()");  /*************************free matrix ************************/
   m += NR_END;  void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   m -= nrl;  {
     free((FREE_ARG)(m[nrl]+ncl-NR_END));
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));    free((FREE_ARG)(m+nrl-NR_END));
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");  }
   m[nrl] += NR_END;  
   m[nrl] -= ncl;  /******************* ma3x *******************************/
   double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;  {
     long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));    double ***m;
   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");  
   m[nrl][ncl] += NR_END;    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
   m[nrl][ncl] -= nll;    if (!m) nrerror("allocation failure 1 in matrix()");
   for (j=ncl+1; j<=nch; j++)    m += NR_END;
     m[nrl][j]=m[nrl][j-1]+nlay;    m -= nrl;
    
   for (i=nrl+1; i<=nrh; i++) {    m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     for (j=ncl+1; j<=nch; j++)    m[nrl] += NR_END;
       m[i][j]=m[i][j-1]+nlay;    m[nrl] -= ncl;
   }  
   return m;    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])  
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
   */    if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 }    m[nrl][ncl] += NR_END;
     m[nrl][ncl] -= nll;
 /*************************free ma3x ************************/    for (j=ncl+1; j<=nch; j++) 
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)      m[nrl][j]=m[nrl][j-1]+nlay;
 {    
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    for (i=nrl+1; i<=nrh; i++) {
   free((FREE_ARG)(m[nrl]+ncl-NR_END));      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
   free((FREE_ARG)(m+nrl-NR_END));      for (j=ncl+1; j<=nch; j++) 
 }        m[i][j]=m[i][j-1]+nlay;
     }
 /*************** function subdirf ***********/    return m; 
 char *subdirf(char fileres[])    /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 {             &(m[i][j][k]) <=> *((*(m+i) + j)+k)
   /* Caution optionfilefiname is hidden */    */
   strcpy(tmpout,optionfilefiname);  }
   strcat(tmpout,"/"); /* Add to the right */  
   strcat(tmpout,fileres);  /*************************free ma3x ************************/
   return tmpout;  void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 }  {
     free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 /*************** function subdirf2 ***********/    free((FREE_ARG)(m[nrl]+ncl-NR_END));
 char *subdirf2(char fileres[], char *preop)    free((FREE_ARG)(m+nrl-NR_END));
 {  }
    
   /* Caution optionfilefiname is hidden */  /*************** function subdirf ***********/
   strcpy(tmpout,optionfilefiname);  char *subdirf(char fileres[])
   strcat(tmpout,"/");  {
   strcat(tmpout,preop);    /* Caution optionfilefiname is hidden */
   strcat(tmpout,fileres);    strcpy(tmpout,optionfilefiname);
   return tmpout;    strcat(tmpout,"/"); /* Add to the right */
 }    strcat(tmpout,fileres);
     return tmpout;
 /*************** function subdirf3 ***********/  }
 char *subdirf3(char fileres[], char *preop, char *preop2)  
 {  /*************** function subdirf2 ***********/
    char *subdirf2(char fileres[], char *preop)
   /* Caution optionfilefiname is hidden */  {
   strcpy(tmpout,optionfilefiname);    
   strcat(tmpout,"/");    /* Caution optionfilefiname is hidden */
   strcat(tmpout,preop);    strcpy(tmpout,optionfilefiname);
   strcat(tmpout,preop2);    strcat(tmpout,"/");
   strcat(tmpout,fileres);    strcat(tmpout,preop);
   return tmpout;    strcat(tmpout,fileres);
 }    return tmpout;
   }
 /***************** f1dim *************************/  
 extern int ncom;  /*************** function subdirf3 ***********/
 extern double *pcom,*xicom;  char *subdirf3(char fileres[], char *preop, char *preop2)
 extern double (*nrfunc)(double []);  {
      
 double f1dim(double x)    /* Caution optionfilefiname is hidden */
 {    strcpy(tmpout,optionfilefiname);
   int j;    strcat(tmpout,"/");
   double f;    strcat(tmpout,preop);
   double *xt;    strcat(tmpout,preop2);
      strcat(tmpout,fileres);
   xt=vector(1,ncom);    return tmpout;
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];  }
   f=(*nrfunc)(xt);  
   free_vector(xt,1,ncom);  /***************** f1dim *************************/
   return f;  extern int ncom; 
 }  extern double *pcom,*xicom;
   extern double (*nrfunc)(double []); 
 /*****************brent *************************/   
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)  double f1dim(double x) 
 {  { 
   int iter;    int j; 
   double a,b,d,etemp;    double f;
   double fu,fv,fw,fx;    double *xt; 
   double ftemp;   
   double p,q,r,tol1,tol2,u,v,w,x,xm;    xt=vector(1,ncom); 
   double e=0.0;    for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
      f=(*nrfunc)(xt); 
   a=(ax < cx ? ax : cx);    free_vector(xt,1,ncom); 
   b=(ax > cx ? ax : cx);    return f; 
   x=w=v=bx;  } 
   fw=fv=fx=(*f)(x);  
   for (iter=1;iter<=ITMAX;iter++) {  /*****************brent *************************/
     xm=0.5*(a+b);  double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin) 
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);  { 
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/    int iter; 
     printf(".");fflush(stdout);    double a,b,d,etemp;
     fprintf(ficlog,".");fflush(ficlog);    double fu,fv,fw,fx;
 #ifdef DEBUG    double ftemp;
     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);    double p,q,r,tol1,tol2,u,v,w,x,xm; 
     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);    double e=0.0; 
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */   
 #endif    a=(ax < cx ? ax : cx); 
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){    b=(ax > cx ? ax : cx); 
       *xmin=x;    x=w=v=bx; 
       return fx;    fw=fv=fx=(*f)(x); 
     }    for (iter=1;iter<=ITMAX;iter++) { 
     ftemp=fu;      xm=0.5*(a+b); 
     if (fabs(e) > tol1) {      tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
       r=(x-w)*(fx-fv);      /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
       q=(x-v)*(fx-fw);      printf(".");fflush(stdout);
       p=(x-v)*q-(x-w)*r;      fprintf(ficlog,".");fflush(ficlog);
       q=2.0*(q-r);  #ifdef DEBUG
       if (q > 0.0) p = -p;      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);
       q=fabs(q);      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);
       etemp=e;      /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
       e=d;  #endif
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))      if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
         d=CGOLD*(e=(x >= xm ? a-x : b-x));        *xmin=x; 
       else {        return fx; 
         d=p/q;      } 
         u=x+d;      ftemp=fu;
         if (u-a < tol2 || b-u < tol2)      if (fabs(e) > tol1) { 
           d=SIGN(tol1,xm-x);        r=(x-w)*(fx-fv); 
       }        q=(x-v)*(fx-fw); 
     } else {        p=(x-v)*q-(x-w)*r; 
       d=CGOLD*(e=(x >= xm ? a-x : b-x));        q=2.0*(q-r); 
     }        if (q > 0.0) p = -p; 
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));        q=fabs(q); 
     fu=(*f)(u);        etemp=e; 
     if (fu <= fx) {        e=d; 
       if (u >= x) a=x; else b=x;        if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
       SHFT(v,w,x,u)          d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
         SHFT(fv,fw,fx,fu)        else { 
         } else {          d=p/q; 
           if (u < x) a=u; else b=u;          u=x+d; 
           if (fu <= fw || w == x) {          if (u-a < tol2 || b-u < tol2) 
             v=w;            d=SIGN(tol1,xm-x); 
             w=u;        } 
             fv=fw;      } else { 
             fw=fu;        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
           } else if (fu <= fv || v == x || v == w) {      } 
             v=u;      u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
             fv=fu;      fu=(*f)(u); 
           }      if (fu <= fx) { 
         }        if (u >= x) a=x; else b=x; 
   }        SHFT(v,w,x,u) 
   nrerror("Too many iterations in brent");          SHFT(fv,fw,fx,fu) 
   *xmin=x;          } else { 
   return fx;            if (u < x) a=u; else b=u; 
 }            if (fu <= fw || w == x) { 
               v=w; 
 /****************** mnbrak ***********************/              w=u; 
               fv=fw; 
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,              fw=fu; 
             double (*func)(double))            } else if (fu <= fv || v == x || v == w) { 
 {              v=u; 
   double ulim,u,r,q, dum;              fv=fu; 
   double fu;            } 
            } 
   *fa=(*func)(*ax);    } 
   *fb=(*func)(*bx);    nrerror("Too many iterations in brent"); 
   if (*fb > *fa) {    *xmin=x; 
     SHFT(dum,*ax,*bx,dum)    return fx; 
       SHFT(dum,*fb,*fa,dum)  } 
       }  
   *cx=(*bx)+GOLD*(*bx-*ax);  /****************** mnbrak ***********************/
   *fc=(*func)(*cx);  
   while (*fb > *fc) {  void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
     r=(*bx-*ax)*(*fb-*fc);              double (*func)(double)) 
     q=(*bx-*cx)*(*fb-*fa);  { 
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/    double ulim,u,r,q, dum;
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));    double fu; 
     ulim=(*bx)+GLIMIT*(*cx-*bx);   
     if ((*bx-u)*(u-*cx) > 0.0) {    *fa=(*func)(*ax); 
       fu=(*func)(u);    *fb=(*func)(*bx); 
     } else if ((*cx-u)*(u-ulim) > 0.0) {    if (*fb > *fa) { 
       fu=(*func)(u);      SHFT(dum,*ax,*bx,dum) 
       if (fu < *fc) {        SHFT(dum,*fb,*fa,dum) 
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))        } 
           SHFT(*fb,*fc,fu,(*func)(u))    *cx=(*bx)+GOLD*(*bx-*ax); 
           }    *fc=(*func)(*cx); 
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {    while (*fb > *fc) { 
       u=ulim;      r=(*bx-*ax)*(*fb-*fc); 
       fu=(*func)(u);      q=(*bx-*cx)*(*fb-*fa); 
     } else {      u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
       u=(*cx)+GOLD*(*cx-*bx);        (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
       fu=(*func)(u);      ulim=(*bx)+GLIMIT*(*cx-*bx); 
     }      if ((*bx-u)*(u-*cx) > 0.0) { 
     SHFT(*ax,*bx,*cx,u)        fu=(*func)(u); 
       SHFT(*fa,*fb,*fc,fu)      } else if ((*cx-u)*(u-ulim) > 0.0) { 
       }        fu=(*func)(u); 
 }        if (fu < *fc) { 
           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 /*************** linmin ************************/            SHFT(*fb,*fc,fu,(*func)(u)) 
             } 
 int ncom;      } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
 double *pcom,*xicom;        u=ulim; 
 double (*nrfunc)(double []);        fu=(*func)(u); 
        } else { 
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))        u=(*cx)+GOLD*(*cx-*bx); 
 {        fu=(*func)(u); 
   double brent(double ax, double bx, double cx,      } 
                double (*f)(double), double tol, double *xmin);      SHFT(*ax,*bx,*cx,u) 
   double f1dim(double x);        SHFT(*fa,*fb,*fc,fu) 
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,        } 
               double *fc, double (*func)(double));  } 
   int j;  
   double xx,xmin,bx,ax;  /*************** linmin ************************/
   double fx,fb,fa;  
    int ncom; 
   ncom=n;  double *pcom,*xicom;
   pcom=vector(1,n);  double (*nrfunc)(double []); 
   xicom=vector(1,n);   
   nrfunc=func;  void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
   for (j=1;j<=n;j++) {  { 
     pcom[j]=p[j];    double brent(double ax, double bx, double cx, 
     xicom[j]=xi[j];                 double (*f)(double), double tol, double *xmin); 
   }    double f1dim(double x); 
   ax=0.0;    void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
   xx=1.0;                double *fc, double (*func)(double)); 
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);    int j; 
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);    double xx,xmin,bx,ax; 
 #ifdef DEBUG    double fx,fb,fa;
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);   
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);    ncom=n; 
 #endif    pcom=vector(1,n); 
   for (j=1;j<=n;j++) {    xicom=vector(1,n); 
     xi[j] *= xmin;    nrfunc=func; 
     p[j] += xi[j];    for (j=1;j<=n;j++) { 
   }      pcom[j]=p[j]; 
   free_vector(xicom,1,n);      xicom[j]=xi[j]; 
   free_vector(pcom,1,n);    } 
 }    ax=0.0; 
     xx=1.0; 
 char *asc_diff_time(long time_sec, char ascdiff[])    mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
 {    *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
   long sec_left, days, hours, minutes;  #ifdef DEBUG
   days = (time_sec) / (60*60*24);    printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   sec_left = (time_sec) % (60*60*24);    fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   hours = (sec_left) / (60*60) ;  #endif
   sec_left = (sec_left) %(60*60);    for (j=1;j<=n;j++) { 
   minutes = (sec_left) /60;      xi[j] *= xmin; 
   sec_left = (sec_left) % (60);      p[j] += xi[j]; 
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);      } 
   return ascdiff;    free_vector(xicom,1,n); 
 }    free_vector(pcom,1,n); 
   } 
 /*************** powell ************************/  
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,  char *asc_diff_time(long time_sec, char ascdiff[])
             double (*func)(double []))  {
 {    long sec_left, days, hours, minutes;
   void linmin(double p[], double xi[], int n, double *fret,    days = (time_sec) / (60*60*24);
               double (*func)(double []));    sec_left = (time_sec) % (60*60*24);
   int i,ibig,j;    hours = (sec_left) / (60*60) ;
   double del,t,*pt,*ptt,*xit;    sec_left = (sec_left) %(60*60);
   double fp,fptt;    minutes = (sec_left) /60;
   double *xits;    sec_left = (sec_left) % (60);
   int niterf, itmp;    sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
     return ascdiff;
   pt=vector(1,n);  }
   ptt=vector(1,n);  
   xit=vector(1,n);  /*************** powell ************************/
   xits=vector(1,n);  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
   *fret=(*func)(p);              double (*func)(double [])) 
   for (j=1;j<=n;j++) pt[j]=p[j];  { 
   for (*iter=1;;++(*iter)) {    void linmin(double p[], double xi[], int n, double *fret, 
     fp=(*fret);                double (*func)(double [])); 
     ibig=0;    int i,ibig,j; 
     del=0.0;    double del,t,*pt,*ptt,*xit;
     last_time=curr_time;    double fp,fptt;
     (void) gettimeofday(&curr_time,&tzp);    double *xits;
     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);    int niterf, itmp;
     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);  
 /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */    pt=vector(1,n); 
    for (i=1;i<=n;i++) {    ptt=vector(1,n); 
       printf(" %d %.12f",i, p[i]);    xit=vector(1,n); 
       fprintf(ficlog," %d %.12lf",i, p[i]);    xits=vector(1,n); 
       fprintf(ficrespow," %.12lf", p[i]);    *fret=(*func)(p); 
     }    for (j=1;j<=n;j++) pt[j]=p[j]; 
     printf("\n");    for (*iter=1;;++(*iter)) { 
     fprintf(ficlog,"\n");      fp=(*fret); 
     fprintf(ficrespow,"\n");fflush(ficrespow);      ibig=0; 
     if(*iter <=3){      del=0.0; 
       tm = *localtime(&curr_time.tv_sec);      last_time=curr_time;
       strcpy(strcurr,asctime(&tm));      (void) gettimeofday(&curr_time,&tzp);
 /*       asctime_r(&tm,strcurr); */      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);
       forecast_time=curr_time;      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);
       itmp = strlen(strcurr);  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */     for (i=1;i<=n;i++) {
         strcurr[itmp-1]='\0';        printf(" %d %.12f",i, p[i]);
       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);        fprintf(ficlog," %d %.12lf",i, p[i]);
       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," %.12lf", p[i]);
       for(niterf=10;niterf<=30;niterf+=10){      }
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);      printf("\n");
         tmf = *localtime(&forecast_time.tv_sec);      fprintf(ficlog,"\n");
 /*      asctime_r(&tmf,strfor); */      fprintf(ficrespow,"\n");fflush(ficrespow);
         strcpy(strfor,asctime(&tmf));      if(*iter <=3){
         itmp = strlen(strfor);        tm = *localtime(&curr_time.tv_sec);
         if(strfor[itmp-1]=='\n')        strcpy(strcurr,asctime(&tm));
         strfor[itmp-1]='\0';  /*       asctime_r(&tm,strcurr); */
         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);        forecast_time=curr_time; 
         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);        itmp = strlen(strcurr);
       }        if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
     }          strcurr[itmp-1]='\0';
     for (i=1;i<=n;i++) {        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       for (j=1;j<=n;j++) xit[j]=xi[j][i];        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
       fptt=(*fret);        for(niterf=10;niterf<=30;niterf+=10){
 #ifdef DEBUG          forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
       printf("fret=%lf \n",*fret);          tmf = *localtime(&forecast_time.tv_sec);
       fprintf(ficlog,"fret=%lf \n",*fret);  /*      asctime_r(&tmf,strfor); */
 #endif          strcpy(strfor,asctime(&tmf));
       printf("%d",i);fflush(stdout);          itmp = strlen(strfor);
       fprintf(ficlog,"%d",i);fflush(ficlog);          if(strfor[itmp-1]=='\n')
       linmin(p,xit,n,fret,func);          strfor[itmp-1]='\0';
       if (fabs(fptt-(*fret)) > del) {          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);
         del=fabs(fptt-(*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);
         ibig=i;        }
       }      }
 #ifdef DEBUG      for (i=1;i<=n;i++) { 
       printf("%d %.12e",i,(*fret));        for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
       fprintf(ficlog,"%d %.12e",i,(*fret));        fptt=(*fret); 
       for (j=1;j<=n;j++) {  #ifdef DEBUG
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);        printf("fret=%lf \n",*fret);
         printf(" x(%d)=%.12e",j,xit[j]);        fprintf(ficlog,"fret=%lf \n",*fret);
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);  #endif
       }        printf("%d",i);fflush(stdout);
       for(j=1;j<=n;j++) {        fprintf(ficlog,"%d",i);fflush(ficlog);
         printf(" p=%.12e",p[j]);        linmin(p,xit,n,fret,func); 
         fprintf(ficlog," p=%.12e",p[j]);        if (fabs(fptt-(*fret)) > del) { 
       }          del=fabs(fptt-(*fret)); 
       printf("\n");          ibig=i; 
       fprintf(ficlog,"\n");        } 
 #endif  #ifdef DEBUG
     }        printf("%d %.12e",i,(*fret));
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {        fprintf(ficlog,"%d %.12e",i,(*fret));
 #ifdef DEBUG        for (j=1;j<=n;j++) {
       int k[2],l;          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
       k[0]=1;          printf(" x(%d)=%.12e",j,xit[j]);
       k[1]=-1;          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
       printf("Max: %.12e",(*func)(p));        }
       fprintf(ficlog,"Max: %.12e",(*func)(p));        for(j=1;j<=n;j++) {
       for (j=1;j<=n;j++) {          printf(" p=%.12e",p[j]);
         printf(" %.12e",p[j]);          fprintf(ficlog," p=%.12e",p[j]);
         fprintf(ficlog," %.12e",p[j]);        }
       }        printf("\n");
       printf("\n");        fprintf(ficlog,"\n");
       fprintf(ficlog,"\n");  #endif
       for(l=0;l<=1;l++) {      } 
         for (j=1;j<=n;j++) {      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];  #ifdef DEBUG
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        int k[2],l;
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        k[0]=1;
         }        k[1]=-1;
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        printf("Max: %.12e",(*func)(p));
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        fprintf(ficlog,"Max: %.12e",(*func)(p));
       }        for (j=1;j<=n;j++) {
 #endif          printf(" %.12e",p[j]);
           fprintf(ficlog," %.12e",p[j]);
         }
       free_vector(xit,1,n);        printf("\n");
       free_vector(xits,1,n);        fprintf(ficlog,"\n");
       free_vector(ptt,1,n);        for(l=0;l<=1;l++) {
       free_vector(pt,1,n);          for (j=1;j<=n;j++) {
       return;            ptt[j]=p[j]+(p[j]-pt[j])*k[l];
     }            printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");            fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
     for (j=1;j<=n;j++) {          }
       ptt[j]=2.0*p[j]-pt[j];          printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       xit[j]=p[j]-pt[j];          fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       pt[j]=p[j];        }
     }  #endif
     fptt=(*func)(ptt);  
     if (fptt < fp) {  
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);        free_vector(xit,1,n); 
       if (t < 0.0) {        free_vector(xits,1,n); 
         linmin(p,xit,n,fret,func);        free_vector(ptt,1,n); 
         for (j=1;j<=n;j++) {        free_vector(pt,1,n); 
           xi[j][ibig]=xi[j][n];        return; 
           xi[j][n]=xit[j];      } 
         }      if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 #ifdef DEBUG      for (j=1;j<=n;j++) { 
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        ptt[j]=2.0*p[j]-pt[j]; 
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        xit[j]=p[j]-pt[j]; 
         for(j=1;j<=n;j++){        pt[j]=p[j]; 
           printf(" %.12e",xit[j]);      } 
           fprintf(ficlog," %.12e",xit[j]);      fptt=(*func)(ptt); 
         }      if (fptt < fp) { 
         printf("\n");        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
         fprintf(ficlog,"\n");        if (t < 0.0) { 
 #endif          linmin(p,xit,n,fret,func); 
       }          for (j=1;j<=n;j++) { 
     }            xi[j][ibig]=xi[j][n]; 
   }            xi[j][n]=xit[j]; 
 }          }
   #ifdef DEBUG
 /**** Prevalence limit (stable or period prevalence)  ****************/          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
           fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)          for(j=1;j<=n;j++){
 {            printf(" %.12e",xit[j]);
   /* Computes the prevalence limit in each live state at age x by left multiplying the unit            fprintf(ficlog," %.12e",xit[j]);
      matrix by transitions matrix until convergence is reached */          }
           printf("\n");
   int i, ii,j,k;          fprintf(ficlog,"\n");
   double min, max, maxmin, maxmax,sumnew=0.;  #endif
   double **matprod2();        }
   double **out, cov[NCOVMAX], **pmij();      } 
   double **newm;    } 
   double agefin, delaymax=50 ; /* Max number of years to converge */  } 
   
   for (ii=1;ii<=nlstate+ndeath;ii++)  /**** Prevalence limit (stable or period prevalence)  ****************/
     for (j=1;j<=nlstate+ndeath;j++){  
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
     }  {
     /* Computes the prevalence limit in each live state at age x by left multiplying the unit
    cov[1]=1.;       matrix by transitions matrix until convergence is reached */
    
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */    int i, ii,j,k;
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){    double min, max, maxmin, maxmax,sumnew=0.;
     newm=savm;    double **matprod2();
     /* Covariates have to be included here again */    double **out, cov[NCOVMAX+1], **pmij();
      cov[2]=agefin;    double **newm;
      double agefin, delaymax=50 ; /* Max number of years to converge */
       for (k=1; k<=cptcovn;k++) {  
         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];    for (ii=1;ii<=nlstate+ndeath;ii++)
         /*      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 (j=1;j<=nlstate+ndeath;j++){
       }        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];      }
       for (k=1; k<=cptcovprod;k++)  
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];     cov[1]=1.;
    
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/    for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/      newm=savm;
     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);      /* Covariates have to be included here again */
        cov[2]=agefin;
     savm=oldm;    
     oldm=newm;        for (k=1; k<=cptcovn;k++) {
     maxmax=0.;          cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
     for(j=1;j<=nlstate;j++){          /*      printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
       min=1.;        }
       max=0.;        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
       for(i=1; i<=nlstate; i++) {        for (k=1; k<=cptcovprod;k++)
         sumnew=0;          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];  
         prlim[i][j]= newm[i][j]/(1-sumnew);        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
         max=FMAX(max,prlim[i][j]);        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
         min=FMIN(min,prlim[i][j]);        /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
       }      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
       maxmin=max-min;  
       maxmax=FMAX(maxmax,maxmin);      savm=oldm;
     }      oldm=newm;
     if(maxmax < ftolpl){      maxmax=0.;
       return prlim;      for(j=1;j<=nlstate;j++){
     }        min=1.;
   }        max=0.;
 }        for(i=1; i<=nlstate; i++) {
           sumnew=0;
 /*************** transition probabilities ***************/          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
           prlim[i][j]= newm[i][j]/(1-sumnew);
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )          max=FMAX(max,prlim[i][j]);
 {          min=FMIN(min,prlim[i][j]);
   double s1, s2;        }
   /*double t34;*/        maxmin=max-min;
   int i,j,j1, nc, ii, jj;        maxmax=FMAX(maxmax,maxmin);
       }
     for(i=1; i<= nlstate; i++){      if(maxmax < ftolpl){
       for(j=1; j<i;j++){        return prlim;
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){      }
           /*s2 += param[i][j][nc]*cov[nc];*/    }
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];  }
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */  
         }  /*************** transition probabilities ***************/ 
         ps[i][j]=s2;  
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
       }  {
       for(j=i+1; j<=nlstate+ndeath;j++){    double s1, s2;
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){    /*double t34;*/
           s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];    int i,j,j1, nc, ii, jj;
 /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */  
         }      for(i=1; i<= nlstate; i++){
         ps[i][j]=s2;        for(j=1; j<i;j++){
       }          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
     }            /*s2 += param[i][j][nc]*cov[nc];*/
     /*ps[3][2]=1;*/            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
      /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
     for(i=1; i<= nlstate; i++){          }
       s1=0;          ps[i][j]=s2;
       for(j=1; j<i; j++)  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
         s1+=exp(ps[i][j]);        }
       for(j=i+1; j<=nlstate+ndeath; j++)        for(j=i+1; j<=nlstate+ndeath;j++){
         s1+=exp(ps[i][j]);          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
       ps[i][i]=1./(s1+1.);            s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
       for(j=1; j<i; j++)  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
         ps[i][j]= exp(ps[i][j])*ps[i][i];          }
       for(j=i+1; j<=nlstate+ndeath; j++)          ps[i][j]=s2;
         ps[i][j]= exp(ps[i][j])*ps[i][i];        }
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */      }
     } /* end i */      /*ps[3][2]=1;*/
          
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){      for(i=1; i<= nlstate; i++){
       for(jj=1; jj<= nlstate+ndeath; jj++){        s1=0;
         ps[ii][jj]=0;        for(j=1; j<i; j++){
         ps[ii][ii]=1;          s1+=exp(ps[i][j]);
       }          /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
     }        }
            for(j=i+1; j<=nlstate+ndeath; j++){
           s1+=exp(ps[i][j]);
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */          /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */        }
 /*         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+1];
       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]]];
   } /* end h */        for (k=1; k<=cptcovage;k++)
   return po;          cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 }        for (k=1; k<=cptcovprod;k++)
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
   
 /*************** log-likelihood *************/  
 double func( double *x)        /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 {        /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
   int i, ii, j, k, mi, d, kk;        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
   double l, ll[NLSTATEMAX], cov[NCOVMAX];                     pmij(pmmij,cov,ncovmodel,x,nlstate));
   double **out;        savm=oldm;
   double sw; /* Sum of weights */        oldm=newm;
   double lli; /* Individual log likelihood */      }
   int s1, s2;      for(i=1; i<=nlstate+ndeath; i++)
   double bbh, survp;        for(j=1;j<=nlstate+ndeath;j++) {
   long ipmx;          po[i][j][h]=newm[i][j];
   /*extern weight */          /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
   /* We are differentiating ll according to initial status */        }
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/      /*printf("h=%d ",h);*/
   /*for(i=1;i<imx;i++)    } /* end h */
     printf(" %d\n",s[4][i]);  /*     printf("\n H=%d \n",h); */
   */    return po;
   cov[1]=1.;  }
   
   for(k=1; k<=nlstate; k++) ll[k]=0.;  
   /*************** log-likelihood *************/
   if(mle==1){  double func( double *x)
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  {
       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+1], cov[NCOVMAX+1];
         for (ii=1;ii<=nlstate+ndeath;ii++)    double **out;
           for (j=1;j<=nlstate+ndeath;j++){    double sw; /* Sum of weights */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);    double lli; /* Individual log likelihood */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    int s1, s2;
           }    double bbh, survp;
         for(d=0; d<dh[mi][i]; d++){    long ipmx;
           newm=savm;    /*extern weight */
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    /* We are differentiating ll according to initial status */
           for (kk=1; kk<=cptcovage;kk++) {    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    /*for(i=1;i<imx;i++) 
           }      printf(" %d\n",s[4][i]);
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,    */
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    cov[1]=1.;
           savm=oldm;  
           oldm=newm;    for(k=1; k<=nlstate; k++) ll[k]=0.;
         } /* end mult */  
          if(mle==1){
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         /* But now since version 0.9 we anticipate for bias at large stepm.        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
          * If stepm is larger than one month (smallest stepm) and if the exact delay        for(mi=1; mi<= wav[i]-1; mi++){
          * (in months) between two waves is not a multiple of stepm, we rounded to          for (ii=1;ii<=nlstate+ndeath;ii++)
          * the nearest (and in case of equal distance, to the lowest) interval but now            for (j=1;j<=nlstate+ndeath;j++){
          * we keep into memory the bias bh[mi][i] and also the previous matrix product              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the              savm[ii][j]=(ii==j ? 1.0 : 0.0);
          * probability in order to take into account the bias as a fraction of the way            }
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies          for(d=0; d<dh[mi][i]; d++){
          * -stepm/2 to stepm/2 .            newm=savm;
          * For stepm=1 the results are the same as for previous versions of Imach.            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
          * For stepm > 1 the results are less biased than in previous versions.            for (kk=1; kk<=cptcovage;kk++) {
          */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         s1=s[mw[mi][i]][i];            }
         s2=s[mw[mi+1][i]][i];            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         bbh=(double)bh[mi][i]/(double)stepm;                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         /* bias bh is positive if real duration            savm=oldm;
          * is higher than the multiple of stepm and negative otherwise.            oldm=newm;
          */          } /* end mult */
         /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/        
         if( s2 > nlstate){          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
           /* i.e. if s2 is a death state and if the date of death is known          /* But now since version 0.9 we anticipate for bias at large stepm.
              then the contribution to the likelihood is the probability to           * If stepm is larger than one month (smallest stepm) and if the exact delay 
              die between last step unit time and current  step unit time,           * (in months) between two waves is not a multiple of stepm, we rounded to 
              which is also equal to probability to die before dh           * the nearest (and in case of equal distance, to the lowest) interval but now
              minus probability to die before dh-stepm .           * we keep into memory the bias bh[mi][i] and also the previous matrix product
              In version up to 0.92 likelihood was computed           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
         as if date of death was unknown. Death was treated as any other           * probability in order to take into account the bias as a fraction of the way
         health state: the date of the interview describes the actual state           * from savm to out if bh is negative or even beyond if bh is positive. bh varies
         and not the date of a change in health state. The former idea was           * -stepm/2 to stepm/2 .
         to consider that at each interview the state was recorded           * For stepm=1 the results are the same as for previous versions of Imach.
         (healthy, disable or death) and IMaCh was corrected; but when we           * For stepm > 1 the results are less biased than in previous versions. 
         introduced the exact date of death then we should have modified           */
         the contribution of an exact death to the likelihood. This new          s1=s[mw[mi][i]][i];
         contribution is smaller and very dependent of the step unit          s2=s[mw[mi+1][i]][i];
         stepm. It is no more the probability to die between last interview          bbh=(double)bh[mi][i]/(double)stepm; 
         and month of death but the probability to survive from last          /* bias bh is positive if real duration
         interview up to one month before death multiplied by the           * is higher than the multiple of stepm and negative otherwise.
         probability to die within a month. Thanks to Chris           */
         Jackson for correcting this bug.  Former versions increased          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
         mortality artificially. The bad side is that we add another loop          if( s2 > nlstate){ 
         which slows down the processing. The difference can be up to 10%            /* i.e. if s2 is a death state and if the date of death is known 
         lower mortality.               then the contribution to the likelihood is the probability to 
           */               die between last step unit time and current  step unit time, 
           lli=log(out[s1][s2] - savm[s1][s2]);               which is also equal to probability to die before dh 
                minus probability to die before dh-stepm . 
                In version up to 0.92 likelihood was computed
         } else if  (s2==-2) {          as if date of death was unknown. Death was treated as any other
           for (j=1,survp=0. ; j<=nlstate; j++)          health state: the date of the interview describes the actual state
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          and not the date of a change in health state. The former idea was
           /*survp += out[s1][j]; */          to consider that at each interview the state was recorded
           lli= log(survp);          (healthy, disable or death) and IMaCh was corrected; but when we
         }          introduced the exact date of death then we should have modified
                  the contribution of an exact death to the likelihood. This new
         else if  (s2==-4) {          contribution is smaller and very dependent of the step unit
           for (j=3,survp=0. ; j<=nlstate; j++)            stepm. It is no more the probability to die between last interview
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          and month of death but the probability to survive from last
           lli= log(survp);          interview up to one month before death multiplied by the
         }          probability to die within a month. Thanks to Chris
           Jackson for correcting this bug.  Former versions increased
         else if  (s2==-5) {          mortality artificially. The bad side is that we add another loop
           for (j=1,survp=0. ; j<=2; j++)            which slows down the processing. The difference can be up to 10%
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          lower mortality.
           lli= log(survp);            */
         }            lli=log(out[s1][s2] - savm[s1][s2]);
          
         else{  
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */          } else if  (s2==-2) {
           /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */            for (j=1,survp=0. ; j<=nlstate; j++) 
         }              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/            /*survp += out[s1][j]; */
         /*if(lli ==000.0)*/            lli= log(survp);
         /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */          }
         ipmx +=1;          
         sw += weight[i];          else if  (s2==-4) { 
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            for (j=3,survp=0. ; j<=nlstate; j++)  
       } /* end of wave */              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
     } /* end of individual */            lli= log(survp); 
   }  else if(mle==2){          } 
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){  
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          else if  (s2==-5) { 
       for(mi=1; mi<= wav[i]-1; mi++){            for (j=1,survp=0. ; j<=2; j++)  
         for (ii=1;ii<=nlstate+ndeath;ii++)              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           for (j=1;j<=nlstate+ndeath;j++){            lli= log(survp); 
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);          } 
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          
           }          else{
         for(d=0; d<=dh[mi][i]; d++){            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
           newm=savm;            /*  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[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          } 
           for (kk=1; kk<=cptcovage;kk++) {          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          /*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); */
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          ipmx +=1;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          sw += weight[i];
           savm=oldm;          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           oldm=newm;        } /* end of wave */
         } /* end mult */      } /* end of individual */
          }  else if(mle==2){
         s1=s[mw[mi][i]][i];      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         s2=s[mw[mi+1][i]][i];        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         bbh=(double)bh[mi][i]/(double)stepm;        for(mi=1; mi<= wav[i]-1; mi++){
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */          for (ii=1;ii<=nlstate+ndeath;ii++)
         ipmx +=1;            for (j=1;j<=nlstate+ndeath;j++){
         sw += weight[i];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
       } /* end of wave */            }
     } /* end of individual */          for(d=0; d<=dh[mi][i]; d++){
   }  else if(mle==3){  /* exponential inter-extrapolation */            newm=savm;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            for (kk=1; kk<=cptcovage;kk++) {
       for(mi=1; mi<= wav[i]-1; mi++){              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         for (ii=1;ii<=nlstate+ndeath;ii++)            }
           for (j=1;j<=nlstate+ndeath;j++){            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
             savm[ii][j]=(ii==j ? 1.0 : 0.0);            savm=oldm;
           }            oldm=newm;
         for(d=0; d<dh[mi][i]; d++){          } /* end mult */
           newm=savm;        
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          s1=s[mw[mi][i]][i];
           for (kk=1; kk<=cptcovage;kk++) {          s2=s[mw[mi+1][i]][i];
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          bbh=(double)bh[mi][i]/(double)stepm; 
           }          lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          ipmx +=1;
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          sw += weight[i];
           savm=oldm;          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           oldm=newm;        } /* end of wave */
         } /* end mult */      } /* end of individual */
          }  else if(mle==3){  /* exponential inter-extrapolation */
         s1=s[mw[mi][i]][i];      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         s2=s[mw[mi+1][i]][i];        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         bbh=(double)bh[mi][i]/(double)stepm;        for(mi=1; mi<= wav[i]-1; mi++){
         lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */          for (ii=1;ii<=nlstate+ndeath;ii++)
         ipmx +=1;            for (j=1;j<=nlstate+ndeath;j++){
         sw += weight[i];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
       } /* end of wave */            }
     } /* end of individual */          for(d=0; d<dh[mi][i]; d++){
   }else if (mle==4){  /* ml=4 no inter-extrapolation */            newm=savm;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];            for (kk=1; kk<=cptcovage;kk++) {
       for(mi=1; mi<= wav[i]-1; mi++){              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         for (ii=1;ii<=nlstate+ndeath;ii++)            }
           for (j=1;j<=nlstate+ndeath;j++){            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
             savm[ii][j]=(ii==j ? 1.0 : 0.0);            savm=oldm;
           }            oldm=newm;
         for(d=0; d<dh[mi][i]; d++){          } /* end mult */
           newm=savm;        
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          s1=s[mw[mi][i]][i];
           for (kk=1; kk<=cptcovage;kk++) {          s2=s[mw[mi+1][i]][i];
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          bbh=(double)bh[mi][i]/(double)stepm; 
           }          lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
                  ipmx +=1;
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          sw += weight[i];
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           savm=oldm;        } /* end of wave */
           oldm=newm;      } /* end of individual */
         } /* end mult */    }else if (mle==4){  /* ml=4 no inter-extrapolation */
            for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         s1=s[mw[mi][i]][i];        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         s2=s[mw[mi+1][i]][i];        for(mi=1; mi<= wav[i]-1; mi++){
         if( s2 > nlstate){          for (ii=1;ii<=nlstate+ndeath;ii++)
           lli=log(out[s1][s2] - savm[s1][s2]);            for (j=1;j<=nlstate+ndeath;j++){
         }else{              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */              savm[ii][j]=(ii==j ? 1.0 : 0.0);
         }            }
         ipmx +=1;          for(d=0; d<dh[mi][i]; d++){
         sw += weight[i];            newm=savm;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */            for (kk=1; kk<=cptcovage;kk++) {
       } /* end of wave */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
     } /* end of individual */            }
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */          
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
       for(mi=1; mi<= wav[i]-1; mi++){            savm=oldm;
         for (ii=1;ii<=nlstate+ndeath;ii++)            oldm=newm;
           for (j=1;j<=nlstate+ndeath;j++){          } /* end mult */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);        
             savm[ii][j]=(ii==j ? 1.0 : 0.0);          s1=s[mw[mi][i]][i];
           }          s2=s[mw[mi+1][i]][i];
         for(d=0; d<dh[mi][i]; d++){          if( s2 > nlstate){ 
           newm=savm;            lli=log(out[s1][s2] - savm[s1][s2]);
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          }else{
           for (kk=1; kk<=cptcovage;kk++) {            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];          }
           }          ipmx +=1;
                  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));  /*      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]); */
           savm=oldm;        } /* end of wave */
           oldm=newm;      } /* end of individual */
         } /* end mult */    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
            for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         s1=s[mw[mi][i]][i];        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         s2=s[mw[mi+1][i]][i];        for(mi=1; mi<= wav[i]-1; mi++){
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */          for (ii=1;ii<=nlstate+ndeath;ii++)
         ipmx +=1;            for (j=1;j<=nlstate+ndeath;j++){
         sw += weight[i];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;              savm[ii][j]=(ii==j ? 1.0 : 0.0);
         /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/            }
       } /* end of wave */          for(d=0; d<dh[mi][i]; d++){
     } /* end of individual */            newm=savm;
   } /* End of if */            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];            for (kk=1; kk<=cptcovage;kk++) {
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */            }
   return -l;          
 }            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 /*************** log-likelihood *************/            savm=oldm;
 double funcone( double *x)            oldm=newm;
 {          } /* end mult */
   /* Same as likeli but slower because of a lot of printf and if */        
   int i, ii, j, k, mi, d, kk;          s1=s[mw[mi][i]][i];
   double l, ll[NLSTATEMAX], cov[NCOVMAX];          s2=s[mw[mi+1][i]][i];
   double **out;          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   double lli; /* Individual log likelihood */          ipmx +=1;
   double llt;          sw += weight[i];
   int s1, s2;          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   double bbh, survp;          /*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]);*/
   /*extern weight */        } /* end of wave */
   /* We are differentiating ll according to initial status */      } /* end of individual */
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/    } /* End of if */
   /*for(i=1;i<imx;i++)    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
     printf(" %d\n",s[4][i]);    /* 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 */
   cov[1]=1.;    return -l;
   }
   for(k=1; k<=nlstate; k++) ll[k]=0.;  
   /*************** log-likelihood *************/
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){  double funcone( double *x)
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];  {
     for(mi=1; mi<= wav[i]-1; mi++){    /* Same as likeli but slower because of a lot of printf and if */
       for (ii=1;ii<=nlstate+ndeath;ii++)    int i, ii, j, k, mi, d, kk;
         for (j=1;j<=nlstate+ndeath;j++){    double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);    double **out;
           savm[ii][j]=(ii==j ? 1.0 : 0.0);    double lli; /* Individual log likelihood */
         }    double llt;
       for(d=0; d<dh[mi][i]; d++){    int s1, s2;
         newm=savm;    double bbh, survp;
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;    /*extern weight */
         for (kk=1; kk<=cptcovage;kk++) {    /* We are differentiating ll according to initial status */
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];    /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
         }    /*for(i=1;i<imx;i++) 
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,      printf(" %d\n",s[4][i]);
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));    */
         savm=oldm;    cov[1]=1.;
         oldm=newm;  
       } /* end mult */    for(k=1; k<=nlstate; k++) ll[k]=0.;
        
       s1=s[mw[mi][i]][i];    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       s2=s[mw[mi+1][i]][i];      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
       bbh=(double)bh[mi][i]/(double)stepm;      for(mi=1; mi<= wav[i]-1; mi++){
       /* bias is positive if real duration        for (ii=1;ii<=nlstate+ndeath;ii++)
        * is higher than the multiple of stepm and negative otherwise.          for (j=1;j<=nlstate+ndeath;j++){
        */            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
       if( s2 > nlstate && (mle <5) ){  /* Jackson */            savm[ii][j]=(ii==j ? 1.0 : 0.0);
         lli=log(out[s1][s2] - savm[s1][s2]);          }
       } else if  (s2==-2) {        for(d=0; d<dh[mi][i]; d++){
         for (j=1,survp=0. ; j<=nlstate; j++)          newm=savm;
           survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         lli= log(survp);          for (kk=1; kk<=cptcovage;kk++) {
       }else if (mle==1){            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */          }
       } else if(mle==2){          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         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 */                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
       } else if(mle==3){  /* exponential inter-extrapolation */          savm=oldm;
         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 */          oldm=newm;
       } else if (mle==4){  /* mle=4 no inter-extrapolation */        } /* end mult */
         lli=log(out[s1][s2]); /* Original formula */        
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */        s1=s[mw[mi][i]][i];
         lli=log(out[s1][s2]); /* Original formula */        s2=s[mw[mi+1][i]][i];
       } /* End of if */        bbh=(double)bh[mi][i]/(double)stepm; 
       ipmx +=1;        /* bias is positive if real duration
       sw += weight[i];         * is higher than the multiple of stepm and negative otherwise.
       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]); */        if( s2 > nlstate && (mle <5) ){  /* Jackson */
       if(globpr){          lli=log(out[s1][s2] - savm[s1][s2]);
         fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\        } else if  (s2==-2) {
  %11.6f %11.6f %11.6f ", \          for (j=1,survp=0. ; j<=nlstate; j++) 
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);          lli= log(survp);
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){        }else if (mle==1){
           llt +=ll[k]*gipmx/gsw;          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);        } else if(mle==2){
         }          lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
         fprintf(ficresilk," %10.6f\n", -llt);        } 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 */
     } /* end of wave */        } else if (mle==4){  /* mle=4 no inter-extrapolation */
   } /* end of individual */          lli=log(out[s1][s2]); /* Original formula */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */          lli=log(out[s1][s2]); /* Original formula */
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */        } /* End of if */
   if(globpr==0){ /* First time we count the contributions and weights */        ipmx +=1;
     gipmx=ipmx;        sw += weight[i];
     gsw=sw;        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]); */
   return -l;        if(globpr){
 }          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
    %11.6f %11.6f %11.6f ", \
                   num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 /*************** function likelione ***********/                  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,llt=0.,l=0.; k<=nlstate; k++){
 {            llt +=ll[k]*gipmx/gsw;
   /* This routine should help understanding what is done with            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
      the selection of individuals/waves and          }
      to check the exact contribution to the likelihood.          fprintf(ficresilk," %10.6f\n", -llt);
      Plotting could be done.        }
    */      } /* end of wave */
   int k;    } /* end of individual */
     for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
   if(*globpri !=0){ /* Just counts and sums, no printings */    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     strcpy(fileresilk,"ilk");    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
     strcat(fileresilk,fileres);    if(globpr==0){ /* First time we count the contributions and weights */
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {      gipmx=ipmx;
       printf("Problem with resultfile: %s\n", fileresilk);      gsw=sw;
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);    }
     }    return -l;
     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 ");  
     /*  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++)  /*************** function likelione ***********/
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");  {
   }    /* This routine should help understanding what is done with 
        the selection of individuals/waves and
   *fretone=(*funcone)(p);       to check the exact contribution to the likelihood.
   if(*globpri !=0){       Plotting could be done.
     fclose(ficresilk);     */
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));    int k;
     fflush(fichtm);  
   }    if(*globpri !=0){ /* Just counts and sums, no printings */
   return;      strcpy(fileresilk,"ilk"); 
 }      strcat(fileresilk,fileres);
       if((ficresilk=fopen(fileresilk,"w"))==NULL) {
         printf("Problem with resultfile: %s\n", fileresilk);
 /*********** Maximum Likelihood Estimation ***************/        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
       }
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))      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 ");
   int i,j, iter;      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
   double **xi;      for(k=1; k<=nlstate; k++) 
   double fret;        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
   double fretone; /* Only one call to likelihood */      fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
   /*  char filerespow[FILENAMELENGTH];*/    }
   xi=matrix(1,npar,1,npar);  
   for (i=1;i<=npar;i++)    *fretone=(*funcone)(p);
     for (j=1;j<=npar;j++)    if(*globpri !=0){
       xi[i][j]=(i==j ? 1.0 : 0.0);      fclose(ficresilk);
   printf("Powell\n");  fprintf(ficlog,"Powell\n");      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
   strcpy(filerespow,"pow");      fflush(fichtm); 
   strcat(filerespow,fileres);    } 
   if((ficrespow=fopen(filerespow,"w"))==NULL) {    return;
     printf("Problem with resultfile: %s\n", filerespow);  }
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);  
   }  
   fprintf(ficrespow,"# Powell\n# iter -2*LL");  /*********** Maximum Likelihood Estimation ***************/
   for (i=1;i<=nlstate;i++)  
     for(j=1;j<=nlstate+ndeath;j++)  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);  {
   fprintf(ficrespow,"\n");    int i,j, iter;
     double **xi;
   powell(p,xi,npar,ftol,&iter,&fret,func);    double fret;
     double fretone; /* Only one call to likelihood */
   free_matrix(xi,1,npar,1,npar);    /*  char filerespow[FILENAMELENGTH];*/
   fclose(ficrespow);    xi=matrix(1,npar,1,npar);
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));    for (i=1;i<=npar;i++)
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));      for (j=1;j<=npar;j++)
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));        xi[i][j]=(i==j ? 1.0 : 0.0);
     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 }    strcpy(filerespow,"pow"); 
     strcat(filerespow,fileres);
 /**** Computes Hessian and covariance matrix ***/    if((ficrespow=fopen(filerespow,"w"))==NULL) {
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))      printf("Problem with resultfile: %s\n", filerespow);
 {      fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
   double  **a,**y,*x,pd;    }
   double **hess;    fprintf(ficrespow,"# Powell\n# iter -2*LL");
   int i, j,jk;    for (i=1;i<=nlstate;i++)
   int *indx;      for(j=1;j<=nlstate+ndeath;j++)
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);    fprintf(ficrespow,"\n");
   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[]) ;    powell(p,xi,npar,ftol,&iter,&fret,func);
   void ludcmp(double **a, int npar, int *indx, double *d) ;  
   double gompertz(double p[]);    free_matrix(xi,1,npar,1,npar);
   hess=matrix(1,npar,1,npar);    fclose(ficrespow);
     printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
   printf("\nCalculation of the hessian matrix. Wait...\n");    fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");    fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
   for (i=1;i<=npar;i++){  
     printf("%d",i);fflush(stdout);  }
     fprintf(ficlog,"%d",i);fflush(ficlog);  
      /**** Computes Hessian and covariance matrix ***/
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
      {
     /*  printf(" %f ",p[i]);    double  **a,**y,*x,pd;
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/    double **hess;
   }    int i, j,jk;
      int *indx;
   for (i=1;i<=npar;i++) {  
     for (j=1;j<=npar;j++)  {    double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
       if (j>i) {    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
         printf(".%d%d",i,j);fflush(stdout);    void lubksb(double **a, int npar, int *indx, double b[]) ;
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);    void ludcmp(double **a, int npar, int *indx, double *d) ;
         hess[i][j]=hessij(p,delti,i,j,func,npar);    double gompertz(double p[]);
            hess=matrix(1,npar,1,npar);
         hess[j][i]=hess[i][j];      
         /*printf(" %lf ",hess[i][j]);*/    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);
   printf("\n");      fprintf(ficlog,"%d",i);fflush(ficlog);
   fprintf(ficlog,"\n");     
        hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");      
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");      /*  printf(" %f ",p[i]);
            printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
   a=matrix(1,npar,1,npar);    }
   y=matrix(1,npar,1,npar);    
   x=vector(1,npar);    for (i=1;i<=npar;i++) {
   indx=ivector(1,npar);      for (j=1;j<=npar;j++)  {
   for (i=1;i<=npar;i++)        if (j>i) { 
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];          printf(".%d%d",i,j);fflush(stdout);
   ludcmp(a,npar,indx,&pd);          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
           hess[i][j]=hessij(p,delti,i,j,func,npar);
   for (j=1;j<=npar;j++) {          
     for (i=1;i<=npar;i++) x[i]=0;          hess[j][i]=hess[i][j];    
     x[j]=1;          /*printf(" %lf ",hess[i][j]);*/
     lubksb(a,npar,indx,x);        }
     for (i=1;i<=npar;i++){      }
       matcov[i][j]=x[i];    }
     }    printf("\n");
   }    fprintf(ficlog,"\n");
   
   printf("\n#Hessian matrix#\n");    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
   fprintf(ficlog,"\n#Hessian matrix#\n");    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
   for (i=1;i<=npar;i++) {    
     for (j=1;j<=npar;j++) {    a=matrix(1,npar,1,npar);
       printf("%.3e ",hess[i][j]);    y=matrix(1,npar,1,npar);
       fprintf(ficlog,"%.3e ",hess[i][j]);    x=vector(1,npar);
     }    indx=ivector(1,npar);
     printf("\n");    for (i=1;i<=npar;i++)
     fprintf(ficlog,"\n");      for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
   }    ludcmp(a,npar,indx,&pd);
   
   /* Recompute Inverse */    for (j=1;j<=npar;j++) {
   for (i=1;i<=npar;i++)      for (i=1;i<=npar;i++) x[i]=0;
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];      x[j]=1;
   ludcmp(a,npar,indx,&pd);      lubksb(a,npar,indx,x);
       for (i=1;i<=npar;i++){ 
   /*  printf("\n#Hessian matrix recomputed#\n");        matcov[i][j]=x[i];
       }
   for (j=1;j<=npar;j++) {    }
     for (i=1;i<=npar;i++) x[i]=0;  
     x[j]=1;    printf("\n#Hessian matrix#\n");
     lubksb(a,npar,indx,x);    fprintf(ficlog,"\n#Hessian matrix#\n");
     for (i=1;i<=npar;i++){    for (i=1;i<=npar;i++) { 
       y[i][j]=x[i];      for (j=1;j<=npar;j++) { 
       printf("%.3e ",y[i][j]);        printf("%.3e ",hess[i][j]);
       fprintf(ficlog,"%.3e ",y[i][j]);        fprintf(ficlog,"%.3e ",hess[i][j]);
     }      }
     printf("\n");      printf("\n");
     fprintf(ficlog,"\n");      fprintf(ficlog,"\n");
   }    }
   */  
     /* Recompute Inverse */
   free_matrix(a,1,npar,1,npar);    for (i=1;i<=npar;i++)
   free_matrix(y,1,npar,1,npar);      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
   free_vector(x,1,npar);    ludcmp(a,npar,indx,&pd);
   free_ivector(indx,1,npar);  
   free_matrix(hess,1,npar,1,npar);    /*  printf("\n#Hessian matrix recomputed#\n");
   
     for (j=1;j<=npar;j++) {
 }      for (i=1;i<=npar;i++) x[i]=0;
       x[j]=1;
 /*************** hessian matrix ****************/      lubksb(a,npar,indx,x);
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)      for (i=1;i<=npar;i++){ 
 {        y[i][j]=x[i];
   int i;        printf("%.3e ",y[i][j]);
   int l=1, lmax=20;        fprintf(ficlog,"%.3e ",y[i][j]);
   double k1,k2;      }
   double p2[NPARMAX+1];      printf("\n");
   double res;      fprintf(ficlog,"\n");
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;    }
   double fx;    */
   int k=0,kmax=10;  
   double l1;    free_matrix(a,1,npar,1,npar);
     free_matrix(y,1,npar,1,npar);
   fx=func(x);    free_vector(x,1,npar);
   for (i=1;i<=npar;i++) p2[i]=x[i];    free_ivector(indx,1,npar);
   for(l=0 ; l <=lmax; l++){    free_matrix(hess,1,npar,1,npar);
     l1=pow(10,l);  
     delts=delt;  
     for(k=1 ; k <kmax; k=k+1){  }
       delt = delta*(l1*k);  
       p2[theta]=x[theta] +delt;  /*************** hessian matrix ****************/
       k1=func(p2)-fx;  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
       p2[theta]=x[theta]-delt;  {
       k2=func(p2)-fx;    int i;
       /*res= (k1-2.0*fx+k2)/delt/delt; */    int l=1, lmax=20;
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */    double k1,k2;
          double p2[MAXPARM+1]; /* identical to x */
 #ifdef DEBUG    double res;
       printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);    double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
       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 fx;
 #endif    int k=0,kmax=10;
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */    double l1;
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){  
         k=kmax;    fx=func(x);
       }    for (i=1;i<=npar;i++) p2[i]=x[i];
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */    for(l=0 ; l <=lmax; l++){
         k=kmax; l=lmax*10.;      l1=pow(10,l);
       }      delts=delt;
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){      for(k=1 ; k <kmax; k=k+1){
         delts=delt;        delt = delta*(l1*k);
       }        p2[theta]=x[theta] +delt;
     }        k1=func(p2)-fx;
   }        p2[theta]=x[theta]-delt;
   delti[theta]=delts;        k2=func(p2)-fx;
   return res;        /*res= (k1-2.0*fx+k2)/delt/delt; */
          res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 }        
   #ifdef DEBUGHESS
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)        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);
   int i;  #endif
   int l=1, l1, lmax=20;        /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
   double k1,k2,k3,k4,res,fx;        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
   double p2[NPARMAX+1];          k=kmax;
   int k;        }
         else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
   fx=func(x);          k=kmax; l=lmax*10.;
   for (k=1; k<=2; k++) {        }
     for (i=1;i<=npar;i++) p2[i]=x[i];        else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
     p2[thetai]=x[thetai]+delti[thetai]/k;          delts=delt;
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;        }
     k1=func(p2)-fx;      }
      }
     p2[thetai]=x[thetai]+delti[thetai]/k;    delti[theta]=delts;
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    return res; 
     k2=func(p2)-fx;    
    }
     p2[thetai]=x[thetai]-delti[thetai]/k;  
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;  double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
     k3=func(p2)-fx;  {
      int i;
     p2[thetai]=x[thetai]-delti[thetai]/k;    int l=1, l1, lmax=20;
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    double k1,k2,k3,k4,res,fx;
     k4=func(p2)-fx;    double p2[MAXPARM+1];
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */    int k;
 #ifdef DEBUG  
     printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);    fx=func(x);
     fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);    for (k=1; k<=2; k++) {
 #endif      for (i=1;i<=npar;i++) p2[i]=x[i];
   }      p2[thetai]=x[thetai]+delti[thetai]/k;
   return res;      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 }      k1=func(p2)-fx;
     
 /************** Inverse of matrix **************/      p2[thetai]=x[thetai]+delti[thetai]/k;
 void ludcmp(double **a, int n, int *indx, double *d)      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 {      k2=func(p2)-fx;
   int i,imax,j,k;    
   double big,dum,sum,temp;      p2[thetai]=x[thetai]-delti[thetai]/k;
   double *vv;      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
        k3=func(p2)-fx;
   vv=vector(1,n);    
   *d=1.0;      p2[thetai]=x[thetai]-delti[thetai]/k;
   for (i=1;i<=n;i++) {      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
     big=0.0;      k4=func(p2)-fx;
     for (j=1;j<=n;j++)      res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
       if ((temp=fabs(a[i][j])) > big) big=temp;  #ifdef DEBUG
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");      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);
     vv[i]=1.0/big;      fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
   }  #endif
   for (j=1;j<=n;j++) {    }
     for (i=1;i<j;i++) {    return res;
       sum=a[i][j];  }
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];  
       a[i][j]=sum;  /************** Inverse of matrix **************/
     }  void ludcmp(double **a, int n, int *indx, double *d) 
     big=0.0;  { 
     for (i=j;i<=n;i++) {    int i,imax,j,k; 
       sum=a[i][j];    double big,dum,sum,temp; 
       for (k=1;k<j;k++)    double *vv; 
         sum -= a[i][k]*a[k][j];   
       a[i][j]=sum;    vv=vector(1,n); 
       if ( (dum=vv[i]*fabs(sum)) >= big) {    *d=1.0; 
         big=dum;    for (i=1;i<=n;i++) { 
         imax=i;      big=0.0; 
       }      for (j=1;j<=n;j++) 
     }        if ((temp=fabs(a[i][j])) > big) big=temp; 
     if (j != imax) {      if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
       for (k=1;k<=n;k++) {      vv[i]=1.0/big; 
         dum=a[imax][k];    } 
         a[imax][k]=a[j][k];    for (j=1;j<=n;j++) { 
         a[j][k]=dum;      for (i=1;i<j;i++) { 
       }        sum=a[i][j]; 
       *d = -(*d);        for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
       vv[imax]=vv[j];        a[i][j]=sum; 
     }      } 
     indx[j]=imax;      big=0.0; 
     if (a[j][j] == 0.0) a[j][j]=TINY;      for (i=j;i<=n;i++) { 
     if (j != n) {        sum=a[i][j]; 
       dum=1.0/(a[j][j]);        for (k=1;k<j;k++) 
       for (i=j+1;i<=n;i++) a[i][j] *= dum;          sum -= a[i][k]*a[k][j]; 
     }        a[i][j]=sum; 
   }        if ( (dum=vv[i]*fabs(sum)) >= big) { 
   free_vector(vv,1,n);  /* Doesn't work */          big=dum; 
 ;          imax=i; 
 }        } 
       } 
 void lubksb(double **a, int n, int *indx, double b[])      if (j != imax) { 
 {        for (k=1;k<=n;k++) { 
   int i,ii=0,ip,j;          dum=a[imax][k]; 
   double sum;          a[imax][k]=a[j][k]; 
            a[j][k]=dum; 
   for (i=1;i<=n;i++) {        } 
     ip=indx[i];        *d = -(*d); 
     sum=b[ip];        vv[imax]=vv[j]; 
     b[ip]=b[i];      } 
     if (ii)      indx[j]=imax; 
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];      if (a[j][j] == 0.0) a[j][j]=TINY; 
     else if (sum) ii=i;      if (j != n) { 
     b[i]=sum;        dum=1.0/(a[j][j]); 
   }        for (i=j+1;i<=n;i++) a[i][j] *= dum; 
   for (i=n;i>=1;i--) {      } 
     sum=b[i];    } 
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];    free_vector(vv,1,n);  /* Doesn't work */
     b[i]=sum/a[i][i];  ;
   }  } 
 }  
   void lubksb(double **a, int n, int *indx, double b[]) 
 void pstamp(FILE *fichier)  { 
 {    int i,ii=0,ip,j; 
   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);    double sum; 
 }   
     for (i=1;i<=n;i++) { 
 /************ Frequencies ********************/      ip=indx[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[])      sum=b[ip]; 
 {  /* Some frequencies */      b[ip]=b[i]; 
        if (ii) 
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;        for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
   int first;      else if (sum) ii=i; 
   double ***freq; /* Frequencies */      b[i]=sum; 
   double *pp, **prop;    } 
   double pos,posprop, k2, dateintsum=0,k2cpt=0;    for (i=n;i>=1;i--) { 
   char fileresp[FILENAMELENGTH];      sum=b[i]; 
        for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
   pp=vector(1,nlstate);      b[i]=sum/a[i][i]; 
   prop=matrix(1,nlstate,iagemin,iagemax+3);    } 
   strcpy(fileresp,"p");  } 
   strcat(fileresp,fileres);  
   if((ficresp=fopen(fileresp,"w"))==NULL) {  void pstamp(FILE *fichier)
     printf("Problem with prevalence resultfile: %s\n", fileresp);  {
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
     exit(0);  }
   }  
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);  /************ Frequencies ********************/
   j1=0;  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
    {  /* Some frequencies */
   j=cptcoveff;    
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    int i, m, jk, k1,i1, j1, bool, z1,j;
     int first;
   first=1;    double ***freq; /* Frequencies */
     double *pp, **prop;
   for(k1=1; k1<=j;k1++){    double pos,posprop, k2, dateintsum=0,k2cpt=0;
     for(i1=1; i1<=ncodemax[k1];i1++){    char fileresp[FILENAMELENGTH];
       j1++;    
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    pp=vector(1,nlstate);
         scanf("%d", i);*/    prop=matrix(1,nlstate,iagemin,iagemax+3);
       for (i=-5; i<=nlstate+ndeath; i++)      strcpy(fileresp,"p");
         for (jk=-5; jk<=nlstate+ndeath; jk++)      strcat(fileresp,fileres);
           for(m=iagemin; m <= iagemax+3; m++)    if((ficresp=fopen(fileresp,"w"))==NULL) {
             freq[i][jk][m]=0;      printf("Problem with prevalence resultfile: %s\n", fileresp);
       fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
     for (i=1; i<=nlstate; i++)        exit(0);
       for(m=iagemin; m <= iagemax+3; m++)    }
         prop[i][m]=0;    freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
          j1=0;
       dateintsum=0;    
       k2cpt=0;    j=cptcoveff;
       for (i=1; i<=imx; i++) {    if (cptcovn<1) {j=1;ncodemax[1]=1;}
         bool=1;  
         if  (cptcovn>0) {    first=1;
           for (z1=1; z1<=cptcoveff; z1++)  
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])    for(k1=1; k1<=j;k1++){
               bool=0;      for(i1=1; i1<=ncodemax[k1];i1++){
         }        j1++;
         if (bool==1){        /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
           for(m=firstpass; m<=lastpass; m++){          scanf("%d", i);*/
             k2=anint[m][i]+(mint[m][i]/12.);        for (i=-5; i<=nlstate+ndeath; i++)  
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/          for (jk=-5; jk<=nlstate+ndeath; jk++)  
               if(agev[m][i]==0) agev[m][i]=iagemax+1;            for(m=iagemin; m <= iagemax+3; m++)
               if(agev[m][i]==1) agev[m][i]=iagemax+2;              freq[i][jk][m]=0;
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];  
               if (m<lastpass) {      for (i=1; i<=nlstate; i++)  
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];        for(m=iagemin; m <= iagemax+3; m++)
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];          prop[i][m]=0;
               }        
                      dateintsum=0;
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {        k2cpt=0;
                 dateintsum=dateintsum+k2;        for (i=1; i<=imx; i++) {
                 k2cpt++;          bool=1;
               }          if  (cptcovn>0) {
               /*}*/            for (z1=1; z1<=cptcoveff; z1++) 
           }              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
         }                bool=0;
       }          }
                  if (bool==1){
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/            for(m=firstpass; m<=lastpass; m++){
       pstamp(ficresp);              k2=anint[m][i]+(mint[m][i]/12.);
       if  (cptcovn>0) {              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
         fprintf(ficresp, "\n#********** Variable ");                if(agev[m][i]==0) agev[m][i]=iagemax+1;
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);                if(agev[m][i]==1) agev[m][i]=iagemax+2;
         fprintf(ficresp, "**********\n#");                if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
       }                if (m<lastpass) {
       for(i=1; i<=nlstate;i++)                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
       fprintf(ficresp, "\n");                }
                      
       for(i=iagemin; i <= iagemax+3; i++){                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
         if(i==iagemax+3){                  dateintsum=dateintsum+k2;
           fprintf(ficlog,"Total");                  k2cpt++;
         }else{                }
           if(first==1){                /*}*/
             first=0;            }
             printf("See log file for details...\n");          }
           }        }
           fprintf(ficlog,"Age %d", i);         
         }        /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
         for(jk=1; jk <=nlstate ; jk++){        pstamp(ficresp);
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)        if  (cptcovn>0) {
             pp[jk] += freq[jk][m][i];          fprintf(ficresp, "\n#********** Variable "); 
         }          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         for(jk=1; jk <=nlstate ; jk++){          fprintf(ficresp, "**********\n#");
           for(m=-1, pos=0; m <=0 ; m++)        }
             pos += freq[jk][m][i];        for(i=1; i<=nlstate;i++) 
           if(pp[jk]>=1.e-10){          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
             if(first==1){        fprintf(ficresp, "\n");
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);        
             }        for(i=iagemin; i <= iagemax+3; i++){
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);          if(i==iagemax+3){
           }else{            fprintf(ficlog,"Total");
             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);              first=0;
           }              printf("See log file for details...\n");
         }            }
             fprintf(ficlog,"Age %d", i);
         for(jk=1; jk <=nlstate ; jk++){          }
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)          for(jk=1; jk <=nlstate ; jk++){
             pp[jk] += freq[jk][m][i];            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
         }                    pp[jk] += freq[jk][m][i]; 
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){          }
           pos += pp[jk];          for(jk=1; jk <=nlstate ; jk++){
           posprop += prop[jk][i];            for(m=-1, pos=0; m <=0 ; m++)
         }              pos += freq[jk][m][i];
         for(jk=1; jk <=nlstate ; jk++){            if(pp[jk]>=1.e-10){
           if(pos>=1.e-5){              if(first==1){
             if(first==1)                printf(" %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);              }
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);              fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
           }else{            }else{
             if(first==1)              if(first==1)
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);              fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
           }            }
           if( i <= iagemax){          }
             if(pos>=1.e-5){  
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);          for(jk=1; jk <=nlstate ; jk++){
               /*probs[i][jk][j1]= pp[jk]/pos;*/            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/              pp[jk] += freq[jk][m][i];
             }          }       
             else          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);            pos += pp[jk];
           }            posprop += prop[jk][i];
         }          }
                  for(jk=1; jk <=nlstate ; jk++){
         for(jk=-1; jk <=nlstate+ndeath; jk++)            if(pos>=1.e-5){
           for(m=-1; m <=nlstate+ndeath; m++)              if(first==1)
             if(freq[jk][m][i] !=0 ) {                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             if(first==1)              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);            }else{
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);              if(first==1)
             }                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
         if(i <= iagemax)              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
           fprintf(ficresp,"\n");            }
         if(first==1)            if( i <= iagemax){
           printf("Others in log...\n");              if(pos>=1.e-5){
         fprintf(ficlog,"\n");                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
       }                /*probs[i][jk][j1]= pp[jk]/pos;*/
     }                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
   }              }
   dateintmean=dateintsum/k2cpt;              else
                  fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
   fclose(ficresp);            }
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);          }
   free_vector(pp,1,nlstate);          
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);          for(jk=-1; jk <=nlstate+ndeath; jk++)
   /* End of Freq */            for(m=-1; m <=nlstate+ndeath; m++)
 }              if(freq[jk][m][i] !=0 ) {
               if(first==1)
 /************ Prevalence ********************/                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 {                }
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people          if(i <= iagemax)
      in each health status at the date of interview (if between dateprev1 and dateprev2).            fprintf(ficresp,"\n");
      We still use firstpass and lastpass as another selection.          if(first==1)
   */            printf("Others in log...\n");
            fprintf(ficlog,"\n");
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;        }
   double ***freq; /* Frequencies */      }
   double *pp, **prop;    }
   double pos,posprop;    dateintmean=dateintsum/k2cpt; 
   double  y2; /* in fractional years */   
   int iagemin, iagemax;    fclose(ficresp);
     free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
   iagemin= (int) agemin;    free_vector(pp,1,nlstate);
   iagemax= (int) agemax;    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
   /*pp=vector(1,nlstate);*/    /* End of Freq */
   prop=matrix(1,nlstate,iagemin,iagemax+3);  }
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/  
   j1=0;  /************ 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)
   j=cptcoveff;  {  
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
         in each health status at the date of interview (if between dateprev1 and dateprev2).
   for(k1=1; k1<=j;k1++){       We still use firstpass and lastpass as another selection.
     for(i1=1; i1<=ncodemax[k1];i1++){    */
       j1++;   
          int i, m, jk, k1, i1, j1, bool, z1,j;
       for (i=1; i<=nlstate; i++)      double ***freq; /* Frequencies */
         for(m=iagemin; m <= iagemax+3; m++)    double *pp, **prop;
           prop[i][m]=0.0;    double pos,posprop; 
          double  y2; /* in fractional years */
       for (i=1; i<=imx; i++) { /* Each individual */    int iagemin, iagemax;
         bool=1;  
         if  (cptcovn>0) {    iagemin= (int) agemin;
           for (z1=1; z1<=cptcoveff; z1++)    iagemax= (int) agemax;
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])    /*pp=vector(1,nlstate);*/
               bool=0;    prop=matrix(1,nlstate,iagemin,iagemax+3); 
         }    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
         if (bool==1) {    j1=0;
           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 */    j=cptcoveff;
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */    if (cptcovn<1) {j=1;ncodemax[1]=1;}
               if(agev[m][i]==0) agev[m][i]=iagemax+1;    
               if(agev[m][i]==1) agev[m][i]=iagemax+2;    for(k1=1; k1<=j;k1++){
               if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m);      for(i1=1; i1<=ncodemax[k1];i1++){
               if (s[m][i]>0 && s[m][i]<=nlstate) {        j1++;
                 /*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];        for (i=1; i<=nlstate; i++)  
                 prop[s[m][i]][iagemax+3] += weight[i];          for(m=iagemin; m <= iagemax+3; m++)
               }            prop[i][m]=0.0;
             }       
           } /* end selection of waves */        for (i=1; i<=imx; i++) { /* Each individual */
         }          bool=1;
       }          if  (cptcovn>0) {
       for(i=iagemin; i <= iagemax+3; i++){              for (z1=1; z1<=cptcoveff; z1++) 
                      if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {                bool=0;
           posprop += prop[jk][i];          } 
         }          if (bool==1) { 
             for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
         for(jk=1; jk <=nlstate ; jk++){                  y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
           if( i <=  iagemax){              if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
             if(posprop>=1.e-5){                if(agev[m][i]==0) agev[m][i]=iagemax+1;
               probs[i][jk][j1]= prop[jk][i]/posprop;                if(agev[m][i]==1) agev[m][i]=iagemax+2;
             }                if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
           }                if (s[m][i]>0 && s[m][i]<=nlstate) { 
         }/* end jk */                  /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
       }/* end i */                  prop[s[m][i]][(int)agev[m][i]] += weight[i];
     } /* end i1 */                  prop[s[m][i]][iagemax+3] += weight[i]; 
   } /* end k1 */                } 
                }
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/            } /* end selection of waves */
   /*free_vector(pp,1,nlstate);*/          }
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);        }
 }  /* End of prevalence */        for(i=iagemin; i <= iagemax+3; i++){  
           
 /************* Waves Concatenation ***************/          for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
             posprop += prop[jk][i]; 
 void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)          } 
 {  
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.          for(jk=1; jk <=nlstate ; jk++){     
      Death is a valid wave (if date is known).            if( i <=  iagemax){ 
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i              if(posprop>=1.e-5){ 
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]                probs[i][jk][j1]= prop[jk][i]/posprop;
      and mw[mi+1][i]. dh depends on stepm.              } else
      */                printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\n",jk,i,j1,probs[i][jk][j1]);
             } 
   int i, mi, m;          }/* end jk */ 
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;        }/* end i */ 
      double sum=0., jmean=0.;*/      } /* end i1 */
   int first;    } /* end k1 */
   int j, k=0,jk, ju, jl;    
   double sum=0.;    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
   first=0;    /*free_vector(pp,1,nlstate);*/
   jmin=1e+5;    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
   jmax=-1;  }  /* End of prevalence */
   jmean=0.;  
   for(i=1; i<=imx; i++){  /************* Waves Concatenation ***************/
     mi=0;  
     m=firstpass;  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)
     while(s[m][i] <= nlstate){  {
       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
         mw[++mi][i]=m;       Death is a valid wave (if date is known).
       if(m >=lastpass)       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
         break;       dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
       else       and mw[mi+1][i]. dh depends on stepm.
         m++;       */
     }/* end while */  
     if (s[m][i] > nlstate){    int i, mi, m;
       mi++;     /* Death is another wave */    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
       /* if(mi==0)  never been interviewed correctly before death */       double sum=0., jmean=0.;*/
          /* Only death is a correct wave */    int first;
       mw[mi][i]=m;    int j, k=0,jk, ju, jl;
     }    double sum=0.;
     first=0;
     wav[i]=mi;    jmin=1e+5;
     if(mi==0){    jmax=-1;
       nbwarn++;    jmean=0.;
       if(first==0){    for(i=1; i<=imx; i++){
         printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);      mi=0;
         first=1;      m=firstpass;
       }      while(s[m][i] <= nlstate){
       if(first==1){        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
         fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);          mw[++mi][i]=m;
       }        if(m >=lastpass)
     } /* end mi==0 */          break;
   } /* End individuals */        else
           m++;
   for(i=1; i<=imx; i++){      }/* end while */
     for(mi=1; mi<wav[i];mi++){      if (s[m][i] > nlstate){
       if (stepm <=0)        mi++;     /* Death is another wave */
         dh[mi][i]=1;        /* if(mi==0)  never been interviewed correctly before death */
       else{           /* Only death is a correct wave */
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */        mw[mi][i]=m;
           if (agedc[i] < 2*AGESUP) {      }
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);  
             if(j==0) j=1;  /* Survives at least one month after exam */      wav[i]=mi;
             else if(j<0){      if(mi==0){
               nberr++;        nbwarn++;
               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]);        if(first==0){
               j=1; /* Temporary Dangerous patch */          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
               printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);          first=1;
               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);        if(first==1){
             }          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
             k=k+1;        }
             if (j >= jmax){      } /* end mi==0 */
               jmax=j;    } /* End individuals */
               ijmax=i;  
             }    for(i=1; i<=imx; i++){
             if (j <= jmin){      for(mi=1; mi<wav[i];mi++){
               jmin=j;        if (stepm <=0)
               ijmin=i;          dh[mi][i]=1;
             }        else{
             sum=sum+j;          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/            if (agedc[i] < 2*AGESUP) {
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/              j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
           }              if(j==0) j=1;  /* Survives at least one month after exam */
         }              else if(j<0){
         else{                nberr++;
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));                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]);
 /*        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]); */                j=1; /* Temporary Dangerous patch */
                 printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
           k=k+1;                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 >= jmax) {                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);
             jmax=j;              }
             ijmax=i;              k=k+1;
           }              if (j >= jmax){
           else if (j <= jmin){                jmax=j;
             jmin=j;                ijmax=i;
             ijmin=i;              }
           }              if (j <= jmin){
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */                jmin=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]);*/                ijmin=i;
           if(j<0){              }
             nberr++;              sum=sum+j;
             printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);              /*if (j<0) printf("j=%d num=%d \n",j,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]);              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
           }            }
           sum=sum+j;          }
         }          else{
         jk= j/stepm;            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
         jl= j -jk*stepm;  /*        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]); */
         ju= j -(jk+1)*stepm;  
         if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */            k=k+1;
           if(jl==0){            if (j >= jmax) {
             dh[mi][i]=jk;              jmax=j;
             bh[mi][i]=0;              ijmax=i;
           }else{ /* We want a negative bias in order to only have interpolation ie            }
                   * at the price of an extra matrix product in likelihood */            else if (j <= jmin){
             dh[mi][i]=jk+1;              jmin=j;
             bh[mi][i]=ju;              ijmin=i;
           }            }
         }else{            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
           if(jl <= -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]);*/
             dh[mi][i]=jk;            if(j<0){
             bh[mi][i]=jl;       /* bias is positive if real duration              nberr++;
                                  * is higher than the multiple of stepm and negative otherwise.              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{            sum=sum+j;
             dh[mi][i]=jk+1;          }
             bh[mi][i]=ju;          jk= j/stepm;
           }          jl= j -jk*stepm;
           if(dh[mi][i]==0){          ju= j -(jk+1)*stepm;
             dh[mi][i]=1; /* At least one step */          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
             bh[mi][i]=ju; /* At least one step */            if(jl==0){
             /*  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);*/              dh[mi][i]=jk;
           }              bh[mi][i]=0;
         } /* end if mle */            }else{ /* We want a negative bias in order to only have interpolation ie
       }                    * at the price of an extra matrix product in likelihood */
     } /* end wave */              dh[mi][i]=jk+1;
   }              bh[mi][i]=ju;
   jmean=sum/k;            }
   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);          }else{
   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);            if(jl <= -ju){
  }              dh[mi][i]=jk;
               bh[mi][i]=jl;       /* bias is positive if real duration
 /*********** Tricode ****************************/                                   * is higher than the multiple of stepm and negative otherwise.
 void tricode(int *Tvar, int **nbcode, int imx)                                   */
 {            }
              else{
   int Ndum[20],ij=1, k, j, i, maxncov=19;              dh[mi][i]=jk+1;
   int cptcode=0;              bh[mi][i]=ju;
   cptcoveff=0;            }
              if(dh[mi][i]==0){
   for (k=0; k<maxncov; k++) Ndum[k]=0;              dh[mi][i]=1; /* At least one step */
   for (k=1; k<=7; k++) ncodemax[k]=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 (j=1; j<=(cptcovn+2*cptcovprod); j++) {            }
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum          } /* end if mle */
                                modality*/        }
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/      } /* end wave */
       Ndum[ij]++; /*store the modality */    }
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/    jmean=sum/k;
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable    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);
                                        Tvar[j]. If V=sex and male is 0 and    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);
                                        female is 1, then  cptcode=1.*/   }
     }  
   /*********** Tricode ****************************/
     for (i=0; i<=cptcode; i++) {  void tricode(int *Tvar, int **nbcode, int imx)
       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 */  {
     }    
     /*      Tvar[i]=atoi(stre); /* find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 */
     ij=1;  
     for (i=1; i<=ncodemax[j]; i++) {    int Ndum[20],ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
       for (k=0; k<= maxncov; k++) {    int cptcode=0;
         if (Ndum[k] != 0) {    cptcoveff=0; 
           nbcode[Tvar[j]][ij]=k;   
           /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */    for (k=0; k<maxncov; k++) Ndum[k]=0;
              for (k=1; k<=7; k++) ncodemax[k]=0; /* Horrible constant again */
           ij++;  
         }    for (j=1; j<=(cptcovn+2*cptcovprod); j++) { /* For each covariate */
         if (ij > ncodemax[j]) break;      for (i=1; i<=imx; i++) { /*reads the data file to get the maximum 
       }                                   modality*/ 
     }        ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual, might be -1*/
   }          Ndum[ij]++; /*counts the occurence of this modality */
         /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
  for (k=0; k< maxncov; k++) Ndum[k]=0;        if (ij > cptcode) cptcode=ij; /* getting the maximum value of the modality of the covariate  (should be 0 or 1 now) 
                                          Tvar[j]. If V=sex and male is 0 and 
  for (i=1; i<=ncovmodel-2; i++) {                                         female is 1, then  cptcode=1.*/
    /* 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]++;      for (i=0; i<=cptcode; i++) { /* i=-1 ?*/
  }        if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j
                                          th covariate. In fact
  ij=1;                                         ncodemax[j]=2
  for (i=1; i<= maxncov; i++) {                                         (dichotom. variables only) but
    if((Ndum[i]!=0) && (i<=ncovcol)){                                         it can be more */
      Tvaraff[ij]=i; /*For printing */      } /* Ndum[-1] number of undefined modalities */
      ij++;  
    }      ij=1; 
  }      for (i=1; i<=ncodemax[j]; i++) { /* i= 1 to 2 */
          for (k=0; k<= maxncov; k++) { /* k=-1 ?*/
  cptcoveff=ij-1; /*Number of simple covariates*/          if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 }            nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                                        k is a modality. If we have model=V1+V1*sex 
 /*********** Health Expectancies ****************/                                       then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
             ij++;
 void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )          }
           if (ij > ncodemax[j]) break; 
 {        }  
   /* Health expectancies, no variances */      } 
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;    }  
   double age, agelim, hf;  
   double ***p3mat;   for (k=0; k< maxncov; k++) Ndum[k]=0;
   double eip;  
    for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
   pstamp(ficreseij);     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");     ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
   fprintf(ficreseij,"# Age");     Ndum[ij]++;
   for(i=1; i<=nlstate;i++){   }
     for(j=1; j<=nlstate;j++){  
       fprintf(ficreseij," e%1d%1d ",i,j);   ij=1;
     }   for (i=1; i<= maxncov; i++) {
     fprintf(ficreseij," e%1d. ",i);     if((Ndum[i]!=0) && (i<=ncovcol)){
   }       Tvaraff[ij]=i; /*For printing */
   fprintf(ficreseij,"\n");       ij++;
      }
     }
   if(estepm < stepm){   ij--;
     printf ("Problem %d lower than %d\n",estepm, stepm);   cptcoveff=ij; /*Number of simple covariates*/
   }  }
   else  hstepm=estepm;    
   /* We compute the life expectancy from trapezoids spaced every estepm months  /*********** Health Expectancies ****************/
    * This is mainly to measure the difference between two models: for example  
    * if stepm=24 months pijx are given only every 2 years and by summing them  void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
    * we are calculating an estimate of the Life Expectancy assuming a linear  
    * progression in between and thus overestimating or underestimating according  {
    * to the curvature of the survival function. If, for the same date, we    /* Health expectancies, no variances */
    * estimate the model with stepm=1 month, we can keep estepm to 24 months    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
    * to compare the new estimate of Life expectancy with the same linear    int nhstepma, nstepma; /* Decreasing with age */
    * hypothesis. A more precise result, taking into account a more precise    double age, agelim, hf;
    * curvature will be obtained if estepm is as small as stepm. */    double ***p3mat;
     double eip;
   /* For example we decided to compute the life expectancy with the smallest unit */  
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.    pstamp(ficreseij);
      nhstepm is the number of hstepm from age to agelim    fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
      nstepm is the number of stepm from age to agelin.    fprintf(ficreseij,"# Age");
      Look at hpijx to understand the reason of that which relies in memory size    for(i=1; i<=nlstate;i++){
      and note for a fixed period like estepm months */      for(j=1; j<=nlstate;j++){
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the        fprintf(ficreseij," e%1d%1d ",i,j);
      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      fprintf(ficreseij," e%1d. ",i);
      you sum them up and add 1 year (area under the trapezoids) you won't get the same    }
      results. So we changed our mind and took the option of the best precision.    fprintf(ficreseij,"\n");
   */  
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */    
     if(estepm < stepm){
   agelim=AGESUP;      printf ("Problem %d lower than %d\n",estepm, stepm);
   /* If stepm=6 months */    }
     /* Computed by stepm unit matrices, product of hstepm matrices, stored    else  hstepm=estepm;   
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */    /* We compute the life expectancy from trapezoids spaced every estepm months
         * This is mainly to measure the difference between two models: for example
 /* nhstepm age range expressed in number of stepm */     * if stepm=24 months pijx are given only every 2 years and by summing them
   nstepm=(int) rint((agelim-bage)*YEARM/stepm);     * we are calculating an estimate of the Life Expectancy assuming a linear 
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */     * progression in between and thus overestimating or underestimating according
   /* if (stepm >= YEARM) hstepm=1;*/     * to the curvature of the survival function. If, for the same date, we 
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */     * estimate the model with stepm=1 month, we can keep estepm to 24 months
   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);     * to compare the new estimate of Life expectancy with the same linear 
      * hypothesis. A more precise result, taking into account a more precise
   for (age=bage; age<=fage; age ++){     * curvature will be obtained if estepm is as small as stepm. */
   
     /* For example we decided to compute the life expectancy with the smallest unit */
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);      /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
           nhstepm is the number of hstepm from age to agelim 
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */       nstepm is the number of stepm from age to agelin. 
           Look at hpijx to understand the reason of that which relies in memory size
     printf("%d|",(int)age);fflush(stdout);       and note for a fixed period like estepm months */
     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);    /* 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
        means that if the survival funtion is printed only each two years of age and if
     /* Computing expectancies */       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
     for(i=1; i<=nlstate;i++)       results. So we changed our mind and took the option of the best precision.
       for(j=1; j<=nlstate;j++)    */
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;  
              agelim=AGESUP;
           /*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]);*/    /* If stepm=6 months */
       /* Computed by stepm unit matrices, product of hstepm matrices, stored
         }         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
          
     fprintf(ficreseij,"%3.0f",age );  /* nhstepm age range expressed in number of stepm */
     for(i=1; i<=nlstate;i++){    nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
       eip=0;    /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
       for(j=1; j<=nlstate;j++){    /* if (stepm >= YEARM) hstepm=1;*/
         eip +=eij[i][j][(int)age];    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
         fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       }  
       fprintf(ficreseij,"%9.4f", eip );    for (age=bage; age<=fage; age ++){ 
     }      nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
     fprintf(ficreseij,"\n");      /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
          /* if (stepm >= YEARM) hstepm=1;*/
   }      nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  
   printf("\n");      /* If stepm=6 months */
   fprintf(ficlog,"\n");      /* Computed by stepm unit matrices, product of hstepma matrices, stored
           in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 }      
       hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 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[] )      
       hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 {      
   /* Covariances of health expectancies eij and of total life expectancies according      printf("%d|",(int)age);fflush(stdout);
    to initial status i, ei. .      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
   */      
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;      /* Computing expectancies */
   double age, agelim, hf;      for(i=1; i<=nlstate;i++)
   double ***p3matp, ***p3matm, ***varhe;        for(j=1; j<=nlstate;j++)
   double **dnewm,**doldm;          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   double *xp, *xm;            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
   double **gp, **gm;            
   double ***gradg, ***trgradg;            /* 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]);*/
   int theta;  
           }
   double eip, vip;  
       fprintf(ficreseij,"%3.0f",age );
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);      for(i=1; i<=nlstate;i++){
   xp=vector(1,npar);        eip=0;
   xm=vector(1,npar);        for(j=1; j<=nlstate;j++){
   dnewm=matrix(1,nlstate*nlstate,1,npar);          eip +=eij[i][j][(int)age];
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
          }
   pstamp(ficresstdeij);        fprintf(ficreseij,"%9.4f", eip );
   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");      }
   fprintf(ficresstdeij,"# Age");      fprintf(ficreseij,"\n");
   for(i=1; i<=nlstate;i++){      
     for(j=1; j<=nlstate;j++)    }
       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     fprintf(ficresstdeij," e%1d. ",i);    printf("\n");
   }    fprintf(ficlog,"\n");
   fprintf(ficresstdeij,"\n");    
   }
   pstamp(ficrescveij);  
   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");  void cvevsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
   fprintf(ficrescveij,"# Age");  
   for(i=1; i<=nlstate;i++)  {
     for(j=1; j<=nlstate;j++){    /* Covariances of health expectancies eij and of total life expectancies according
       cptj= (j-1)*nlstate+i;     to initial status i, ei. .
       for(i2=1; i2<=nlstate;i2++)    */
         for(j2=1; j2<=nlstate;j2++){    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
           cptj2= (j2-1)*nlstate+i2;    int nhstepma, nstepma; /* Decreasing with age */
           if(cptj2 <= cptj)    double age, agelim, hf;
             fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);    double ***p3matp, ***p3matm, ***varhe;
         }    double **dnewm,**doldm;
     }    double *xp, *xm;
   fprintf(ficrescveij,"\n");    double **gp, **gm;
      double ***gradg, ***trgradg;
   if(estepm < stepm){    int theta;
     printf ("Problem %d lower than %d\n",estepm, stepm);  
   }    double eip, vip;
   else  hstepm=estepm;    
   /* We compute the life expectancy from trapezoids spaced every estepm months    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
    * This is mainly to measure the difference between two models: for example    xp=vector(1,npar);
    * if stepm=24 months pijx are given only every 2 years and by summing them    xm=vector(1,npar);
    * we are calculating an estimate of the Life Expectancy assuming a linear    dnewm=matrix(1,nlstate*nlstate,1,npar);
    * progression in between and thus overestimating or underestimating according    doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
    * 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    pstamp(ficresstdeij);
    * to compare the new estimate of Life expectancy with the same linear    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
    * hypothesis. A more precise result, taking into account a more precise    fprintf(ficresstdeij,"# Age");
    * curvature will be obtained if estepm is as small as stepm. */    for(i=1; i<=nlstate;i++){
       for(j=1; j<=nlstate;j++)
   /* For example we decided to compute the life expectancy with the smallest unit */        fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.      fprintf(ficresstdeij," e%1d. ",i);
      nhstepm is the number of hstepm from age to agelim    }
      nstepm is the number of stepm from age to agelin.    fprintf(ficresstdeij,"\n");
      Look at hpijx to understand the reason of that which relies in memory size  
      and note for a fixed period like estepm months */    pstamp(ficrescveij);
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
      survival function given by stepm (the optimization length). Unfortunately it    fprintf(ficrescveij,"# Age");
      means that if the survival funtion is printed only each 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      for(j=1; j<=nlstate;j++){
      results. So we changed our mind and took the option of the best precision.        cptj= (j-1)*nlstate+i;
   */        for(i2=1; i2<=nlstate;i2++)
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */          for(j2=1; j2<=nlstate;j2++){
             cptj2= (j2-1)*nlstate+i2;
   /* If stepm=6 months */            if(cptj2 <= cptj)
   /* nhstepm age range expressed in number of stepm */              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
   agelim=AGESUP;          }
   nstepm=(int) rint((agelim-bage)*YEARM/stepm);      }
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */    fprintf(ficrescveij,"\n");
   /* if (stepm >= YEARM) hstepm=1;*/    
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */    if(estepm < stepm){
        printf ("Problem %d lower than %d\n",estepm, stepm);
   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    }
   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    else  hstepm=estepm;   
   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);    /* We compute the life expectancy from trapezoids spaced every estepm months
   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);     * This is mainly to measure the difference between two models: for example
   gp=matrix(0,nhstepm,1,nlstate*nlstate);     * if stepm=24 months pijx are given only every 2 years and by summing them
   gm=matrix(0,nhstepm,1,nlstate*nlstate);     * we are calculating an estimate of the Life Expectancy assuming a linear 
      * progression in between and thus overestimating or underestimating according
   for (age=bage; age<=fage; age ++){     * 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
     /* Computed by stepm unit matrices, product of hstepm matrices, stored     * to compare the new estimate of Life expectancy with the same linear 
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */     * hypothesis. A more precise result, taking into account a more precise
       * curvature will be obtained if estepm is as small as stepm. */
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */  
     /* For example we decided to compute the life expectancy with the smallest unit */
     /* Computing  Variances of health expectancies */    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to       nhstepm is the number of hstepm from age to agelim 
        decrease memory allocation */       nstepm is the number of stepm from age to agelin. 
     for(theta=1; theta <=npar; theta++){       Look at hpijx to understand the reason of that which relies in memory size
       for(i=1; i<=npar; i++){       and note for a fixed period like estepm months */
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
         xm[i] = x[i] - (i==theta ?delti[theta]:0);       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
       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);         you sum them up and add 1 year (area under the trapezoids) you won't get the same 
       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);         results. So we changed our mind and took the option of the best precision.
      */
       for(j=1; j<= nlstate; j++){    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
         for(i=1; i<=nlstate; i++){  
           for(h=0; h<=nhstepm-1; h++){    /* If stepm=6 months */
             gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;    /* nhstepm age range expressed in number of stepm */
             gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;    agelim=AGESUP;
           }    nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
         }    /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
       }    /* if (stepm >= YEARM) hstepm=1;*/
          nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       for(ij=1; ij<= nlstate*nlstate; ij++)    
         for(h=0; h<=nhstepm-1; h++){    p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         }    gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
     }/* End theta */    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
        gp=matrix(0,nhstepm,1,nlstate*nlstate);
        gm=matrix(0,nhstepm,1,nlstate*nlstate);
     for(h=0; h<=nhstepm-1; h++)  
       for(j=1; j<=nlstate*nlstate;j++)    for (age=bage; age<=fage; age ++){ 
         for(theta=1; theta <=npar; theta++)      nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
           trgradg[h][j][theta]=gradg[h][theta][j];      /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
          /* if (stepm >= YEARM) hstepm=1;*/
       nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
      for(ij=1;ij<=nlstate*nlstate;ij++)  
       for(ji=1;ji<=nlstate*nlstate;ji++)      /* If stepm=6 months */
         varhe[ij][ji][(int)age] =0.;      /* Computed by stepm unit matrices, product of hstepma matrices, stored
          in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
      printf("%d|",(int)age);fflush(stdout);      
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
      for(h=0;h<=nhstepm-1;h++){  
       for(k=0;k<=nhstepm-1;k++){      /* Computing  Variances of health expectancies */
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
         matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);         decrease memory allocation */
         for(ij=1;ij<=nlstate*nlstate;ij++)      for(theta=1; theta <=npar; theta++){
           for(ji=1;ji<=nlstate*nlstate;ji++)        for(i=1; i<=npar; i++){ 
             varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;          xp[i] = x[i] + (i==theta ?delti[theta]:0);
       }          xm[i] = x[i] - (i==theta ?delti[theta]:0);
     }        }
         hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
     /* Computing expectancies */        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);      
     for(i=1; i<=nlstate;i++)        for(j=1; j<= nlstate; j++){
       for(j=1; j<=nlstate;j++)          for(i=1; i<=nlstate; i++){
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){            for(h=0; h<=nhstepm-1; h++){
           eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;              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.;
           /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/            }
           }
         }        }
        
     fprintf(ficresstdeij,"%3.0f",age );        for(ij=1; ij<= nlstate*nlstate; ij++)
     for(i=1; i<=nlstate;i++){          for(h=0; h<=nhstepm-1; h++){
       eip=0.;            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
       vip=0.;          }
       for(j=1; j<=nlstate;j++){      }/* End theta */
         eip += eij[i][j][(int)age];      
         for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */      
           vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];      for(h=0; h<=nhstepm-1; h++)
         fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );        for(j=1; j<=nlstate*nlstate;j++)
       }          for(theta=1; theta <=npar; theta++)
       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));            trgradg[h][j][theta]=gradg[h][theta][j];
     }      
     fprintf(ficresstdeij,"\n");  
        for(ij=1;ij<=nlstate*nlstate;ij++)
     fprintf(ficrescveij,"%3.0f",age );        for(ji=1;ji<=nlstate*nlstate;ji++)
     for(i=1; i<=nlstate;i++)          varhe[ij][ji][(int)age] =0.;
       for(j=1; j<=nlstate;j++){  
         cptj= (j-1)*nlstate+i;       printf("%d|",(int)age);fflush(stdout);
         for(i2=1; i2<=nlstate;i2++)       fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
           for(j2=1; j2<=nlstate;j2++){       for(h=0;h<=nhstepm-1;h++){
             cptj2= (j2-1)*nlstate+i2;        for(k=0;k<=nhstepm-1;k++){
             if(cptj2 <= cptj)          matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
               fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
           }          for(ij=1;ij<=nlstate*nlstate;ij++)
       }            for(ji=1;ji<=nlstate*nlstate;ji++)
     fprintf(ficrescveij,"\n");              varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
            }
   }      }
   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);  
   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);      /* Computing expectancies */
   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);      for(i=1; i<=nlstate;i++)
   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        for(j=1; j<=nlstate;j++)
   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
   printf("\n");            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
   fprintf(ficlog,"\n");            
             /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
   free_vector(xm,1,npar);  
   free_vector(xp,1,npar);          }
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);  
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);      fprintf(ficresstdeij,"%3.0f",age );
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);      for(i=1; i<=nlstate;i++){
 }        eip=0.;
         vip=0.;
 /************ Variance ******************/        for(j=1; j<=nlstate;j++){
 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[])          eip += eij[i][j][(int)age];
 {          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
   /* Variance of health expectancies */            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
   /* double **newm;*/        }
   double **dnewm,**doldm;        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
   double **dnewmp,**doldmp;      }
   int i, j, nhstepm, hstepm, h, nstepm ;      fprintf(ficresstdeij,"\n");
   int k, cptcode;  
   double *xp;      fprintf(ficrescveij,"%3.0f",age );
   double **gp, **gm;  /* for var eij */      for(i=1; i<=nlstate;i++)
   double ***gradg, ***trgradg; /*for var eij */        for(j=1; j<=nlstate;j++){
   double **gradgp, **trgradgp; /* for var p point j */          cptj= (j-1)*nlstate+i;
   double *gpp, *gmp; /* for var p point j */          for(i2=1; i2<=nlstate;i2++)
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */            for(j2=1; j2<=nlstate;j2++){
   double ***p3mat;              cptj2= (j2-1)*nlstate+i2;
   double age,agelim, hf;              if(cptj2 <= cptj)
   double ***mobaverage;                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
   int theta;            }
   char digit[4];        }
   char digitp[25];      fprintf(ficrescveij,"\n");
      
   char fileresprobmorprev[FILENAMELENGTH];    }
     free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
   if(popbased==1){    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
     if(mobilav!=0)    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
       strcpy(digitp,"-populbased-mobilav-");    free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
     else strcpy(digitp,"-populbased-nomobil-");    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   }    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   else    printf("\n");
     strcpy(digitp,"-stablbased-");    fprintf(ficlog,"\n");
   
   if (mobilav!=0) {    free_vector(xm,1,npar);
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    free_vector(xp,1,npar);
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
     }  }
   }  
   /************ Variance ******************/
   strcpy(fileresprobmorprev,"prmorprev");  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[])
   sprintf(digit,"%-d",ij);  {
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/    /* Variance of health expectancies */
   strcat(fileresprobmorprev,digit); /* Tvar to be done */    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */    /* double **newm;*/
   strcat(fileresprobmorprev,fileres);    double **dnewm,**doldm;
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {    double **dnewmp,**doldmp;
     printf("Problem with resultfile: %s\n", fileresprobmorprev);    int i, j, nhstepm, hstepm, h, nstepm ;
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);    int k, cptcode;
   }    double *xp;
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    double **gp, **gm;  /* for var eij */
      double ***gradg, ***trgradg; /*for var eij */
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    double **gradgp, **trgradgp; /* for var p point j */
   pstamp(ficresprobmorprev);    double *gpp, *gmp; /* for var p point 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);    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);    double ***p3mat;
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){    double age,agelim, hf;
     fprintf(ficresprobmorprev," p.%-d SE",j);    double ***mobaverage;
     for(i=1; i<=nlstate;i++)    int theta;
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);    char digit[4];
   }      char digitp[25];
   fprintf(ficresprobmorprev,"\n");  
   fprintf(ficgp,"\n# Routine varevsij");    char fileresprobmorprev[FILENAMELENGTH];
   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/  
   fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");    if(popbased==1){
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);      if(mobilav!=0)
 /*   } */        strcpy(digitp,"-populbased-mobilav-");
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);      else strcpy(digitp,"-populbased-nomobil-");
   pstamp(ficresvij);    }
   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");    else 
   if(popbased==1)      strcpy(digitp,"-stablbased-");
     fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");  
   else    if (mobilav!=0) {
     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficresvij,"# Age");      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
   for(i=1; i<=nlstate;i++)        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
     for(j=1; j<=nlstate;j++)        printf(" Error in movingaverage mobilav=%d\n",mobilav);
       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);      }
   fprintf(ficresvij,"\n");    }
   
   xp=vector(1,npar);    strcpy(fileresprobmorprev,"prmorprev"); 
   dnewm=matrix(1,nlstate,1,npar);    sprintf(digit,"%-d",ij);
   doldm=matrix(1,nlstate,1,nlstate);    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);    strcat(fileresprobmorprev,digit); /* Tvar to be done */
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
     strcat(fileresprobmorprev,fileres);
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
   gpp=vector(nlstate+1,nlstate+ndeath);      printf("Problem with resultfile: %s\n", fileresprobmorprev);
   gmp=vector(nlstate+1,nlstate+ndeath);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/    }
      printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   if(estepm < stepm){   
     printf ("Problem %d lower than %d\n",estepm, stepm);    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   }    pstamp(ficresprobmorprev);
   else  hstepm=estepm;      fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);
   /* For example we decided to compute the life expectancy with the smallest unit */    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
      nhstepm is the number of hstepm from age to agelim      fprintf(ficresprobmorprev," p.%-d SE",j);
      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        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
      and note for a fixed period like k years */    }  
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    fprintf(ficresprobmorprev,"\n");
      survival function given by stepm (the optimization length). Unfortunately it    fprintf(ficgp,"\n# Routine varevsij");
      means that if the survival funtion is printed every two years of age and if    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
      you sum them up and add 1 year (area under the trapezoids) you won't get the same    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");
      results. So we changed our mind and took the option of the best precision.    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
   */  /*   } */
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   agelim = AGESUP;    pstamp(ficresvij);
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */    if(popbased==1)
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */      fprintf(ficresvij,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d\n",mobilav);
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    else
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
     gp=matrix(0,nhstepm,1,nlstate);    fprintf(ficresvij,"# Age");
     gm=matrix(0,nhstepm,1,nlstate);    for(i=1; i<=nlstate;i++)
       for(j=1; j<=nlstate;j++)
         fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
     for(theta=1; theta <=npar; theta++){    fprintf(ficresvij,"\n");
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/  
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    xp=vector(1,npar);
       }    dnewm=matrix(1,nlstate,1,npar);
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);      doldm=matrix(1,nlstate,1,nlstate);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
     doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
       if (popbased==1) {  
         if(mobilav ==0){    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
           for(i=1; i<=nlstate;i++)    gpp=vector(nlstate+1,nlstate+ndeath);
             prlim[i][i]=probs[(int)age][i][ij];    gmp=vector(nlstate+1,nlstate+ndeath);
         }else{ /* mobilav */    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
           for(i=1; i<=nlstate;i++)    
             prlim[i][i]=mobaverage[(int)age][i][ij];    if(estepm < stepm){
         }      printf ("Problem %d lower than %d\n",estepm, stepm);
       }    }
      else  hstepm=estepm;   
       for(j=1; j<= nlstate; j++){    /* For example we decided to compute the life expectancy with the smallest unit */
         for(h=0; h<=nhstepm; h++){    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)       nhstepm is the number of hstepm from age to agelim 
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];       nstepm is the number of stepm from age to agelin. 
         }       Look at function hpijx to understand why (it is linked to memory size questions) */
       }    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
       /* This for computing probability of death (h=1 means       survival function given by stepm (the optimization length). Unfortunately it
          computed over hstepm matrices product = hstepm*stepm months)       means that if the survival funtion is printed every two years of age and if
          as a weighted average of prlim.       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.
       for(j=nlstate+1;j<=nlstate+ndeath;j++){    */
         for(i=1,gpp[j]=0.; i<= nlstate; i++)    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
           gpp[j] += prlim[i][i]*p3mat[i][j][1];    agelim = AGESUP;
       }        for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
       /* end probability of death */      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(i=1; i<=npar; i++) /* Computes gradient x - delta */      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         xp[i] = x[i] - (i==theta ?delti[theta]:0);      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        gp=matrix(0,nhstepm,1,nlstate);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      gm=matrix(0,nhstepm,1,nlstate);
    
       if (popbased==1) {  
         if(mobilav ==0){      for(theta=1; theta <=npar; theta++){
           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 */        }
           for(i=1; i<=nlstate;i++)        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
             prlim[i][i]=mobaverage[(int)age][i][ij];        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         }  
       }        if (popbased==1) {
           if(mobilav ==0){
       for(j=1; j<= nlstate; j++){            for(i=1; i<=nlstate;i++)
         for(h=0; h<=nhstepm; h++){              prlim[i][i]=probs[(int)age][i][ij];
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)          }else{ /* mobilav */ 
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];            for(i=1; i<=nlstate;i++)
         }              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)    
          as a weighted average of prlim.        for(j=1; j<= nlstate; j++){
       */          for(h=0; h<=nhstepm; h++){
       for(j=nlstate+1;j<=nlstate+ndeath;j++){            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
         for(i=1,gmp[j]=0.; i<= nlstate; i++)              gp[h][j] += prlim[i][i]*p3mat[i][j][h];
          gmp[j] += prlim[i][i]*p3mat[i][j][1];          }
       }            }
       /* end probability of death */        /* This for computing probability of death (h=1 means
            computed over hstepm matrices product = hstepm*stepm months) 
       for(j=1; j<= nlstate; j++) /* vareij */           as a weighted average of prlim.
         for(h=0; h<=nhstepm; h++){        */
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];        for(j=nlstate+1;j<=nlstate+ndeath;j++){
         }          for(i=1,gpp[j]=0.; i<= nlstate; i++)
             gpp[j] += prlim[i][i]*p3mat[i][j][1];
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */        }    
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];        /* end probability of death */
       }  
         for(i=1; i<=npar; i++) /* Computes gradient x - delta */
     } /* End theta */          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
    
     for(h=0; h<=nhstepm; h++) /* veij */        if (popbased==1) {
       for(j=1; j<=nlstate;j++)          if(mobilav ==0){
         for(theta=1; theta <=npar; theta++)            for(i=1; i<=nlstate;i++)
           trgradg[h][j][theta]=gradg[h][theta][j];              prlim[i][i]=probs[(int)age][i][ij];
           }else{ /* mobilav */ 
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */            for(i=1; i<=nlstate;i++)
       for(theta=1; theta <=npar; theta++)              prlim[i][i]=mobaverage[(int)age][i][ij];
         trgradgp[j][theta]=gradgp[theta][j];          }
          }
   
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
     for(i=1;i<=nlstate;i++)          for(h=0; h<=nhstepm; h++){
       for(j=1;j<=nlstate;j++)            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
         vareij[i][j][(int)age] =0.;              gm[h][j] += prlim[i][i]*p3mat[i][j][h];
           }
     for(h=0;h<=nhstepm;h++){        }
       for(k=0;k<=nhstepm;k++){        /* This for computing probability of death (h=1 means
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);           computed over hstepm matrices product = hstepm*stepm months) 
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);           as a weighted average of prlim.
         for(i=1;i<=nlstate;i++)        */
           for(j=1;j<=nlstate;j++)        for(j=nlstate+1;j<=nlstate+ndeath;j++){
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;          for(i=1,gmp[j]=0.; i<= nlstate; i++)
       }           gmp[j] += prlim[i][i]*p3mat[i][j][1];
     }        }    
          /* end probability of death */
     /* pptj */  
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);        for(j=1; j<= nlstate; j++) /* vareij */
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);          for(h=0; h<=nhstepm; h++){
     for(j=nlstate+1;j<=nlstate+ndeath;j++)            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
       for(i=nlstate+1;i<=nlstate+ndeath;i++)          }
         varppt[j][i]=doldmp[j][i];  
     /* end ppptj */        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
     /*  x centered again */          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);          }
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);  
        } /* End theta */
     if (popbased==1) {  
       if(mobilav ==0){      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
         for(i=1; i<=nlstate;i++)  
           prlim[i][i]=probs[(int)age][i][ij];      for(h=0; h<=nhstepm; h++) /* veij */
       }else{ /* mobilav */        for(j=1; j<=nlstate;j++)
         for(i=1; i<=nlstate;i++)          for(theta=1; theta <=npar; theta++)
           prlim[i][i]=mobaverage[(int)age][i][ij];            trgradg[h][j][theta]=gradg[h][theta][j];
       }  
     }      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                      for(theta=1; theta <=npar; theta++)
     /* This for computing probability of death (h=1 means          trgradgp[j][theta]=gradgp[theta][j];
        computed over hstepm (estepm) matrices product = hstepm*stepm months)    
        as a weighted average of prlim.  
     */      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     for(j=nlstate+1;j<=nlstate+ndeath;j++){      for(i=1;i<=nlstate;i++)
       for(i=1,gmp[j]=0.;i<= nlstate; i++)        for(j=1;j<=nlstate;j++)
         gmp[j] += prlim[i][i]*p3mat[i][j][1];          vareij[i][j][(int)age] =0.;
     }      
     /* end probability of death */      for(h=0;h<=nhstepm;h++){
         for(k=0;k<=nhstepm;k++){
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));          for(i=1;i<=nlstate;i++)
       for(i=1; i<=nlstate;i++){            for(j=1;j<=nlstate;j++)
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);              vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
       }        }
     }      }
     fprintf(ficresprobmorprev,"\n");    
       /* pptj */
     fprintf(ficresvij,"%.0f ",age );      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
     for(i=1; i<=nlstate;i++)      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
       for(j=1; j<=nlstate;j++){      for(j=nlstate+1;j<=nlstate+ndeath;j++)
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);        for(i=nlstate+1;i<=nlstate+ndeath;i++)
       }          varppt[j][i]=doldmp[j][i];
     fprintf(ficresvij,"\n");      /* end ppptj */
     free_matrix(gp,0,nhstepm,1,nlstate);      /*  x centered again */
     free_matrix(gm,0,nhstepm,1,nlstate);      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);   
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      if (popbased==1) {
   } /* End age */        if(mobilav ==0){
   free_vector(gpp,nlstate+1,nlstate+ndeath);          for(i=1; i<=nlstate;i++)
   free_vector(gmp,nlstate+1,nlstate+ndeath);            prlim[i][i]=probs[(int)age][i][ij];
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);        }else{ /* mobilav */ 
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/          for(i=1; i<=nlstate;i++)
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");            prlim[i][i]=mobaverage[(int)age][i][ij];
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */        }
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");      }
 /*   fprintf(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); */      /* This for computing probability of death (h=1 means
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */         computed over hstepm (estepm) matrices product = hstepm*stepm months) 
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));         as a weighted average of prlim.
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));      */
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));      for(j=nlstate+1;j<=nlstate+ndeath;j++){
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
   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);          gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
   /*  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);      }    
 */      /* end probability of death */
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */  
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
       for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   free_vector(xp,1,npar);        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
   free_matrix(doldm,1,nlstate,1,nlstate);        for(i=1; i<=nlstate;i++){
   free_matrix(dnewm,1,nlstate,1,npar);          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);        }
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);      } 
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);      fprintf(ficresprobmorprev,"\n");
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  
   fclose(ficresprobmorprev);      fprintf(ficresvij,"%.0f ",age );
   fflush(ficgp);      for(i=1; i<=nlstate;i++)
   fflush(fichtm);        for(j=1; j<=nlstate;j++){
 }  /* end varevsij */          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
         }
 /************ Variance of prevlim ******************/      fprintf(ficresvij,"\n");
 void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])      free_matrix(gp,0,nhstepm,1,nlstate);
 {      free_matrix(gm,0,nhstepm,1,nlstate);
   /* Variance of prevalence limit */      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
   double **newm;      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   double **dnewm,**doldm;    } /* End age */
   int i, j, nhstepm, hstepm;    free_vector(gpp,nlstate+1,nlstate+ndeath);
   int k, cptcode;    free_vector(gmp,nlstate+1,nlstate+ndeath);
   double *xp;    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
   double *gp, *gm;    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
   double **gradg, **trgradg;    fprintf(ficgp,"\nunset parametric;unset label; set ter png small;set size 0.65, 0.65");
   double age,agelim;    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
   int theta;    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
   pstamp(ficresvpl);  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
   fprintf(ficresvpl,"# Age");    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
   for(i=1; i<=nlstate;i++)    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
       fprintf(ficresvpl," %1d-%1d",i,i);    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
   fprintf(ficresvpl,"\n");    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
     fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
   xp=vector(1,npar);    /*  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);
   dnewm=matrix(1,nlstate,1,npar);  */
   doldm=matrix(1,nlstate,1,nlstate);  /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
      fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
   hstepm=1*YEARM; /* Every year of age */  
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */    free_vector(xp,1,npar);
   agelim = AGESUP;    free_matrix(doldm,1,nlstate,1,nlstate);
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    free_matrix(dnewm,1,nlstate,1,npar);
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
     if (stepm >= YEARM) hstepm=1;    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
     gradg=matrix(1,npar,1,nlstate);    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     gp=vector(1,nlstate);    fclose(ficresprobmorprev);
     gm=vector(1,nlstate);    fflush(ficgp);
     fflush(fichtm); 
     for(theta=1; theta <=npar; theta++){  }  /* end varevsij */
       for(i=1; i<=npar; i++){ /* Computes gradient */  
         xp[i] = x[i] + (i==theta ?delti[theta]:0);  /************ Variance of prevlim ******************/
       }  void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);  {
       for(i=1;i<=nlstate;i++)    /* Variance of prevalence limit */
         gp[i] = prlim[i][i];    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
        double **newm;
       for(i=1; i<=npar; i++) /* Computes gradient */    double **dnewm,**doldm;
         xp[i] = x[i] - (i==theta ?delti[theta]:0);    int i, j, nhstepm, hstepm;
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    int k, cptcode;
       for(i=1;i<=nlstate;i++)    double *xp;
         gm[i] = prlim[i][i];    double *gp, *gm;
     double **gradg, **trgradg;
       for(i=1;i<=nlstate;i++)    double age,agelim;
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];    int theta;
     } /* End theta */    
     pstamp(ficresvpl);
     trgradg =matrix(1,nlstate,1,npar);    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
     fprintf(ficresvpl,"# Age");
     for(j=1; j<=nlstate;j++)    for(i=1; i<=nlstate;i++)
       for(theta=1; theta <=npar; theta++)        fprintf(ficresvpl," %1d-%1d",i,i);
         trgradg[j][theta]=gradg[theta][j];    fprintf(ficresvpl,"\n");
   
     for(i=1;i<=nlstate;i++)    xp=vector(1,npar);
       varpl[i][(int)age] =0.;    dnewm=matrix(1,nlstate,1,npar);
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);    doldm=matrix(1,nlstate,1,nlstate);
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);    
     for(i=1;i<=nlstate;i++)    hstepm=1*YEARM; /* Every year of age */
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
     agelim = AGESUP;
     fprintf(ficresvpl,"%.0f ",age );    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
     for(i=1; i<=nlstate;i++)      nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));      if (stepm >= YEARM) hstepm=1;
     fprintf(ficresvpl,"\n");      nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
     free_vector(gp,1,nlstate);      gradg=matrix(1,npar,1,nlstate);
     free_vector(gm,1,nlstate);      gp=vector(1,nlstate);
     free_matrix(gradg,1,npar,1,nlstate);      gm=vector(1,nlstate);
     free_matrix(trgradg,1,nlstate,1,npar);  
   } /* End age */      for(theta=1; theta <=npar; theta++){
         for(i=1; i<=npar; i++){ /* Computes gradient */
   free_vector(xp,1,npar);          xp[i] = x[i] + (i==theta ?delti[theta]:0);
   free_matrix(doldm,1,nlstate,1,npar);        }
   free_matrix(dnewm,1,nlstate,1,nlstate);        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(i=1;i<=nlstate;i++)
 }          gp[i] = prlim[i][i];
       
 /************ Variance of one-step probabilities  ******************/        for(i=1; i<=npar; i++) /* Computes gradient */
 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[])          xp[i] = x[i] - (i==theta ?delti[theta]:0);
 {        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
   int i, j=0,  i1, k1, l1, t, tj;        for(i=1;i<=nlstate;i++)
   int k2, l2, j1,  z1;          gm[i] = prlim[i][i];
   int k=0,l, cptcode;  
   int first=1, first1;        for(i=1;i<=nlstate;i++)
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
   double **dnewm,**doldm;      } /* End theta */
   double *xp;  
   double *gp, *gm;      trgradg =matrix(1,nlstate,1,npar);
   double **gradg, **trgradg;  
   double **mu;      for(j=1; j<=nlstate;j++)
   double age,agelim, cov[NCOVMAX];        for(theta=1; theta <=npar; theta++)
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */          trgradg[j][theta]=gradg[theta][j];
   int theta;  
   char fileresprob[FILENAMELENGTH];      for(i=1;i<=nlstate;i++)
   char fileresprobcov[FILENAMELENGTH];        varpl[i][(int)age] =0.;
   char fileresprobcor[FILENAMELENGTH];      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
       matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
   double ***varpij;      for(i=1;i<=nlstate;i++)
         varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
   strcpy(fileresprob,"prob");  
   strcat(fileresprob,fileres);      fprintf(ficresvpl,"%.0f ",age );
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {      for(i=1; i<=nlstate;i++)
     printf("Problem with resultfile: %s\n", fileresprob);        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);      fprintf(ficresvpl,"\n");
   }      free_vector(gp,1,nlstate);
   strcpy(fileresprobcov,"probcov");      free_vector(gm,1,nlstate);
   strcat(fileresprobcov,fileres);      free_matrix(gradg,1,npar,1,nlstate);
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {      free_matrix(trgradg,1,nlstate,1,npar);
     printf("Problem with resultfile: %s\n", fileresprobcov);    } /* End age */
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);  
   }    free_vector(xp,1,npar);
   strcpy(fileresprobcor,"probcor");    free_matrix(doldm,1,nlstate,1,npar);
   strcat(fileresprobcor,fileres);    free_matrix(dnewm,1,nlstate,1,nlstate);
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {  
     printf("Problem with resultfile: %s\n", fileresprobcor);  }
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);  
   }  /************ Variance of one-step probabilities  ******************/
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);  void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);  {
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    int i, j=0,  i1, k1, l1, t, tj;
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    int k2, l2, j1,  z1;
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    int k=0,l, cptcode;
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    int first=1, first1;
   pstamp(ficresprob);    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");    double **dnewm,**doldm;
   fprintf(ficresprob,"# Age");    double *xp;
   pstamp(ficresprobcov);    double *gp, *gm;
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");    double **gradg, **trgradg;
   fprintf(ficresprobcov,"# Age");    double **mu;
   pstamp(ficresprobcor);    double age,agelim, cov[NCOVMAX];
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
   fprintf(ficresprobcor,"# Age");    int theta;
     char fileresprob[FILENAMELENGTH];
     char fileresprobcov[FILENAMELENGTH];
   for(i=1; i<=nlstate;i++)    char fileresprobcor[FILENAMELENGTH];
     for(j=1; j<=(nlstate+ndeath);j++){  
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);    double ***varpij;
       fprintf(ficresprobcov," p%1d-%1d ",i,j);  
       fprintf(ficresprobcor," p%1d-%1d ",i,j);    strcpy(fileresprob,"prob"); 
     }      strcat(fileresprob,fileres);
  /* fprintf(ficresprob,"\n");    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
   fprintf(ficresprobcov,"\n");      printf("Problem with resultfile: %s\n", fileresprob);
   fprintf(ficresprobcor,"\n");      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
  */    }
  xp=vector(1,npar);    strcpy(fileresprobcov,"probcov"); 
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    strcat(fileresprobcov,fileres);
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);      printf("Problem with resultfile: %s\n", fileresprobcov);
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
   first=1;    }
   fprintf(ficgp,"\n# Routine varprob");    strcpy(fileresprobcor,"probcor"); 
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");    strcat(fileresprobcor,fileres);
   fprintf(fichtm,"\n");    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
       printf("Problem with resultfile: %s\n", fileresprobcor);
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\    }
   file %s<br>\n",optionfilehtmcov);    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 and drawn. It helps understanding how is the covariance between two incidences.\    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
   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. \    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \    pstamp(ficresprob);
 standard deviations wide on each axis. <br>\    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\    fprintf(ficresprob,"# Age");
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\    pstamp(ficresprobcov);
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
     fprintf(ficresprobcov,"# Age");
   cov[1]=1;    pstamp(ficresprobcor);
   tj=cptcoveff;    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}    fprintf(ficresprobcor,"# Age");
   j1=0;  
   for(t=1; t<=tj;t++){  
     for(i1=1; i1<=ncodemax[t];i1++){    for(i=1; i<=nlstate;i++)
       j1++;      for(j=1; j<=(nlstate+ndeath);j++){
       if  (cptcovn>0) {        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
         fprintf(ficresprob, "\n#********** Variable ");        fprintf(ficresprobcov," p%1d-%1d ",i,j);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);        fprintf(ficresprobcor," p%1d-%1d ",i,j);
         fprintf(ficresprob, "**********\n#\n");      }  
         fprintf(ficresprobcov, "\n#********** Variable ");   /* fprintf(ficresprob,"\n");
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    fprintf(ficresprobcov,"\n");
         fprintf(ficresprobcov, "**********\n#\n");    fprintf(ficresprobcor,"\n");
           */
         fprintf(ficgp, "\n#********** Variable ");    xp=vector(1,npar);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
         fprintf(ficgp, "**********\n#\n");    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
            mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
            varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");    first=1;
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    fprintf(ficgp,"\n# Routine varprob");
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
            fprintf(fichtm,"\n");
         fprintf(ficresprobcor, "\n#********** Variable ");      
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "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(ficresprobcor, "**********\n#");        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 (age=bage; age<=fage; age ++){  and drawn. It helps understanding how is the covariance between two incidences.\
         cov[2]=age;   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
         for (k=1; k<=cptcovn;k++) {    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. \
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];  It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
         }  would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];  standard deviations wide on each axis. <br>\
         for (k=1; k<=cptcovprod;k++)   Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
           cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
          To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));  
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);    cov[1]=1;
         gp=vector(1,(nlstate)*(nlstate+ndeath));    tj=cptcoveff;
         gm=vector(1,(nlstate)*(nlstate+ndeath));    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
        j1=0;
         for(theta=1; theta <=npar; theta++){    for(t=1; t<=tj;t++){
           for(i=1; i<=npar; i++)      for(i1=1; i1<=ncodemax[t];i1++){ 
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);        j1++;
                  if  (cptcovn>0) {
           pmij(pmmij,cov,ncovmodel,xp,nlstate);          fprintf(ficresprob, "\n#********** Variable "); 
                    for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           k=0;          fprintf(ficresprob, "**********\n#\n");
           for(i=1; i<= (nlstate); i++){          fprintf(ficresprobcov, "\n#********** Variable "); 
             for(j=1; j<=(nlstate+ndeath);j++){          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
               k=k+1;          fprintf(ficresprobcov, "**********\n#\n");
               gp[k]=pmmij[i][j];          
             }          fprintf(ficgp, "\n#********** Variable "); 
           }          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                    fprintf(ficgp, "**********\n#\n");
           for(i=1; i<=npar; i++)          
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);          
              fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
           pmij(pmmij,cov,ncovmodel,xp,nlstate);          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
           k=0;          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
           for(i=1; i<=(nlstate); i++){          
             for(j=1; j<=(nlstate+ndeath);j++){          fprintf(ficresprobcor, "\n#********** Variable ");    
               k=k+1;          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
               gm[k]=pmmij[i][j];          fprintf(ficresprobcor, "**********\n#");    
             }        }
           }        
              for (age=bage; age<=fage; age ++){ 
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)          cov[2]=age;
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];            for (k=1; k<=cptcovn;k++) {
         }            cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
           }
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)          for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           for(theta=1; theta <=npar; theta++)          for (k=1; k<=cptcovprod;k++)
             trgradg[j][theta]=gradg[theta][j];            cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                  
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));          gp=vector(1,(nlstate)*(nlstate+ndeath));
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));          gm=vector(1,(nlstate)*(nlstate+ndeath));
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);      
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);          for(theta=1; theta <=npar; theta++){
             for(i=1; i<=npar; i++)
         pmij(pmmij,cov,ncovmodel,x,nlstate);              xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                    
         k=0;            pmij(pmmij,cov,ncovmodel,xp,nlstate);
         for(i=1; i<=(nlstate); i++){            
           for(j=1; j<=(nlstate+ndeath);j++){            k=0;
             k=k+1;            for(i=1; i<= (nlstate); i++){
             mu[k][(int) age]=pmmij[i][j];              for(j=1; j<=(nlstate+ndeath);j++){
           }                k=k+1;
         }                gp[k]=pmmij[i][j];
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)              }
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)            }
             varpij[i][j][(int)age] = doldm[i][j];            
             for(i=1; i<=npar; i++)
         /*printf("\n%d ",(int)age);              xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
           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]));            pmij(pmmij,cov,ncovmodel,xp,nlstate);
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));            k=0;
           }*/            for(i=1; i<=(nlstate); i++){
               for(j=1; j<=(nlstate+ndeath);j++){
         fprintf(ficresprob,"\n%d ",(int)age);                k=k+1;
         fprintf(ficresprobcov,"\n%d ",(int)age);                gm[k]=pmmij[i][j];
         fprintf(ficresprobcor,"\n%d ",(int)age);              }
             }
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)       
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));            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];  
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);          }
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);  
         }          for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
         i=0;            for(theta=1; theta <=npar; theta++)
         for (k=1; k<=(nlstate);k++){              trgradg[j][theta]=gradg[theta][j];
           for (l=1; l<=(nlstate+ndeath);l++){          
             i=i++;          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
             for (j=1; j<=i;j++){          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
             }  
           }          pmij(pmmij,cov,ncovmodel,x,nlstate);
         }/* end of loop for state */          
       } /* end of loop for age */          k=0;
           for(i=1; i<=(nlstate); i++){
       /* Confidence intervalle of pij  */            for(j=1; j<=(nlstate+ndeath);j++){
       /*              k=k+1;
         fprintf(ficgp,"\nset noparametric;unset label");              mu[k][(int) age]=pmmij[i][j];
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");            }
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");          }
         fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);            for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);              varpij[i][j][(int)age] = doldm[i][j];
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);  
       */          /*printf("\n%d ",(int)age);
             for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
       first1=1;            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
       for (k2=1; k2<=(nlstate);k2++){            }*/
         for (l2=1; l2<=(nlstate+ndeath);l2++){  
           if(l2==k2) continue;          fprintf(ficresprob,"\n%d ",(int)age);
           j=(k2-1)*(nlstate+ndeath)+l2;          fprintf(ficresprobcov,"\n%d ",(int)age);
           for (k1=1; k1<=(nlstate);k1++){          fprintf(ficresprobcor,"\n%d ",(int)age);
             for (l1=1; l1<=(nlstate+ndeath);l1++){  
               if(l1==k1) continue;          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
               i=(k1-1)*(nlstate+ndeath)+l1;            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
               if(i<=j) continue;          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
               for (age=bage; age<=fage; age ++){            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                 if ((int)age %5==0){            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;          }
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;          i=0;
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;          for (k=1; k<=(nlstate);k++){
                   mu1=mu[i][(int) age]/stepm*YEARM ;            for (l=1; l<=(nlstate+ndeath);l++){ 
                   mu2=mu[j][(int) age]/stepm*YEARM;              i=i++;
                   c12=cv12/sqrt(v1*v2);              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   /* Computing eigen value of matrix of covariance */              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;              for (j=1; j<=i;j++){
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   /* Eigen vectors */                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));              }
                   /*v21=sqrt(1.-v11*v11); *//* error */            }
                   v21=(lc1-v1)/cv12*v11;          }/* end of loop for state */
                   v12=-v21;        } /* end of loop for age */
                   v22=v11;  
                   tnalp=v21/v11;        /* Confidence intervalle of pij  */
                   if(first1==1){        /*
                     first1=0;          fprintf(ficgp,"\nunset parametric;unset label");
                     printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   }          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   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(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);
                   /*printf(fignu*/          fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   if(first==1){        */
                     first=0;  
                     fprintf(ficgp,"\nset parametric;unset label");        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                     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);        first1=1;
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");        for (k2=1; k2<=(nlstate);k2++){
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\          for (l2=1; l2<=(nlstate+ndeath);l2++){ 
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\            if(l2==k2) continue;
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\            j=(k2-1)*(nlstate+ndeath)+l2;
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\            for (k1=1; k1<=(nlstate);k1++){
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);              for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                if(l1==k1) continue;
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);                i=(k1-1)*(nlstate+ndeath)+l1;
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                if(i<=j) continue;
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                for (age=bage; age<=fage; age ++){ 
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                  if ((int)age %5==0){
                     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",\                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   }else{                    mu1=mu[i][(int) age]/stepm*YEARM ;
                     first=0;                    mu2=mu[j][(int) age]/stepm*YEARM;
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);                    c12=cv12/sqrt(v1*v2);
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                    /* Computing eigen value of matrix of covariance */
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                     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",\                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                    if ((lc2 <0) || (lc1 <0) ){
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                      printf("Error: One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Continuing by making them positive: WRONG RESULTS.\n", lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
                   }/* if first */                      fprintf(ficlog,"Error: One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e\n", lc1, lc2, v1, v2, cv12);fflush(ficlog);
                 } /* age mod 5 */                      lc1=fabs(lc1);
               } /* end loop age */                      lc2=fabs(lc2);
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    }
               first=1;  
             } /*l12 */                    /* Eigen vectors */
           } /* k12 */                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
         } /*l1 */                    /*v21=sqrt(1.-v11*v11); *//* error */
       }/* k1 */                    v21=(lc1-v1)/cv12*v11;
     } /* loop covariates */                    v12=-v21;
   }                    v22=v11;
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);                    tnalp=v21/v11;
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);                    if(first1==1){
   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));                      first1=0;
   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);                      printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
   free_vector(xp,1,npar);                    }
   fclose(ficresprob);                    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);
   fclose(ficresprobcov);                    /*printf(fignu*/
   fclose(ficresprobcor);                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
   fflush(ficgp);                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
   fflush(fichtmcov);                    if(first==1){
 }                      first=0;
                       fprintf(ficgp,"\nset parametric;unset label");
                       fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);
 /******************* Printing html file ***********/                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   int lastpass, int stepm, int weightopt, char model[],\   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   int popforecast, int estepm ,\                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   double jprev1, double mprev1,double anprev1, \                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   double jprev2, double mprev2,double anprev2){                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   int jj1, k1, i1, cpt;                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                       fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 </ul>");                      fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));                    }else{
    fprintf(fichtm,"\                      first=0;
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
    fprintf(fichtm,"\                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",                      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",\
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
    fprintf(fichtm,"\                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
  - (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): \                    }/* if first */
    <a href=\"%s\">%s</a> <br>\n",                  } /* age mod 5 */
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));                } /* end loop age */
    fprintf(fichtm,"\                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
  - Population projections by age and states: \                first=1;
    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));              } /*l12 */
             } /* k12 */
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");          } /*l1 */
         }/* k1 */
  m=cptcoveff;      } /* loop covariates */
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}    }
     free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
  jj1=0;    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
  for(k1=1; k1<=m;k1++){    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
    for(i1=1; i1<=ncodemax[k1];i1++){    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
      jj1++;    free_vector(xp,1,npar);
      if (cptcovn > 0) {    fclose(ficresprob);
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");    fclose(ficresprobcov);
        for (cpt=1; cpt<=cptcoveff;cpt++)    fclose(ficresprobcor);
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);    fflush(ficgp);
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");    fflush(fichtmcov);
      }  }
      /* Pij */  
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \  
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);      /******************* Printing html file ***********/
      /* Quasi-incidences */  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\                    int lastpass, int stepm, int weightopt, char model[],\
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \                    int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);                    int popforecast, int estepm ,\
        /* Period (stable) prevalence in each health state */                    double jprev1, double mprev1,double anprev1, \
        for(cpt=1; cpt<nlstate;cpt++){                    double jprev2, double mprev2,double anprev2){
          fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \    int jj1, k1, i1, cpt;
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);  
        }     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
      for(cpt=1; cpt<=nlstate;cpt++) {     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \  </ul>");
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);     fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
      }   - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
    } /* end i1 */             jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
  }/* End k1 */     fprintf(fichtm,"\
  fprintf(fichtm,"</ul>");   - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
              stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
      fprintf(fichtm,"\
  fprintf(fichtm,"\   - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);     fprintf(fichtm,"\
    - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",     <a href=\"%s\">%s</a> <br>\n",
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
  fprintf(fichtm,"\     fprintf(fichtm,"\
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",   - Population projections by age and states: \
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
   
  fprintf(fichtm,"\  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",  
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));   m=cptcoveff;
  fprintf(fichtm,"\   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
  - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \  
    <a href=\"%s\">%s</a> <br>\n</li>",   jj1=0;
            estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));   for(k1=1; k1<=m;k1++){
  fprintf(fichtm,"\     for(i1=1; i1<=ncodemax[k1];i1++){
  - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \       jj1++;
    <a href=\"%s\">%s</a> <br>\n</li>",       if (cptcovn > 0) {
            estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
  fprintf(fichtm,"\         for (cpt=1; cpt<=cptcoveff;cpt++) 
  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), eij are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences (i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
  fprintf(fichtm,"\       }
  - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors: <a href=\"%s\">%s</a> <br>\n",       /* Pij */
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \
  fprintf(fichtm,"\  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\       /* Quasi-incidences */
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));       fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
    before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \
 /*  if(popforecast==1) fprintf(fichtm,"\n */  <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */         /* Period (stable) prevalence in each health state */
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */         for(cpt=1; cpt<nlstate;cpt++){
 /*      <br>",fileres,fileres,fileres,fileres); */           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
 /*  else  */  <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */         }
  fflush(fichtm);       for(cpt=1; cpt<=nlstate;cpt++) {
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");          fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
   <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
  m=cptcoveff;       }
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}     } /* end i1 */
    }/* End k1 */
  jj1=0;   fprintf(fichtm,"</ul>");
  for(k1=1; k1<=m;k1++){  
    for(i1=1; i1<=ncodemax[k1];i1++){  
      jj1++;   fprintf(fichtm,"\
      if (cptcovn > 0) {  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
        for (cpt=1; cpt<=cptcoveff;cpt++)  
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");           subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
      }   fprintf(fichtm,"\
      for(cpt=1; cpt<=nlstate;cpt++) {   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\  
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);     fprintf(fichtm,"\
      }   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 health expectancies in states (1) and (2): %s%d.png<br>\   fprintf(fichtm,"\
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);   - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
    } /* end i1 */     <a href=\"%s\">%s</a> <br>\n</li>",
  }/* End k1 */             estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
  fprintf(fichtm,"</ul>");   fprintf(fichtm,"\
  fflush(fichtm);   - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \
 }     <a href=\"%s\">%s</a> <br>\n</li>",
              estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 /******************* Gnuplot file **************/   fprintf(fichtm,"\
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){   - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
            estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
   char dirfileres[132],optfileres[132];   fprintf(fichtm,"\
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;   - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (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",
   int ng;           estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */   fprintf(fichtm,"\
 /*     printf("Problem with file %s",optionfilegnuplot); */   - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 /*   } */  
   /*  if(popforecast==1) fprintf(fichtm,"\n */
   /*#ifdef windows */  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
   fprintf(ficgp,"cd \"%s\" \n",pathc);  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
     /*#endif */  /*      <br>",fileres,fileres,fileres,fileres); */
   m=pow(2,cptcoveff);  /*  else  */
   /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
   strcpy(dirfileres,optionfilefiname);   fflush(fichtm);
   strcpy(optfileres,"vpl");   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
  /* 1eme*/  
   for (cpt=1; cpt<= nlstate ; cpt ++) {   m=cptcoveff;
    for (k1=1; k1<= m ; k1 ++) {   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);  
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);   jj1=0;
      fprintf(ficgp,"set xlabel \"Age\" \n\   for(k1=1; k1<=m;k1++){
 set ylabel \"Probability\" \n\     for(i1=1; i1<=ncodemax[k1];i1++){
 set ter png small\n\       jj1++;
 set size 0.65,0.65\n\       if (cptcovn > 0) {
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
          for (cpt=1; cpt<=cptcoveff;cpt++) 
      for (i=1; i<= nlstate ; i ++) {           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        else fprintf(ficgp," \%%*lf (\%%*lf)");       }
      }       for(cpt=1; cpt<=nlstate;cpt++) {
      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
      for (i=1; i<= nlstate ; i ++) {  prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
        else fprintf(ficgp," \%%*lf (\%%*lf)");       }
      }       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
      fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);  health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
      for (i=1; i<= nlstate ; i ++) {  true period expectancies (those weighted with period prevalences are also\
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");   drawn in addition to the population based expectancies computed using\
        else fprintf(ficgp," \%%*lf (\%%*lf)");   observed and cahotic prevalences: %s%d.png<br>\
      }    <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
      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));     } /* end i1 */
    }   }/* End k1 */
   }   fprintf(fichtm,"</ul>");
   /*2 eme*/   fflush(fichtm);
    }
   for (k1=1; k1<= m ; k1 ++) {  
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);  /******************* Gnuplot file **************/
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);  void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
      
     for (i=1; i<= nlstate+1 ; i ++) {    char dirfileres[132],optfileres[132];
       k=2*i;    int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);    int ng=0;
       for (j=1; j<= nlstate+1 ; j ++) {  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");  /*     printf("Problem with file %s",optionfilegnuplot); */
         else fprintf(ficgp," \%%*lf (\%%*lf)");  /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
       }    /*   } */
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");  
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);    /*#ifdef windows */
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);    fprintf(ficgp,"cd \"%s\" \n",pathc);
       for (j=1; j<= nlstate+1 ; j ++) {      /*#endif */
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");    m=pow(2,cptcoveff);
         else fprintf(ficgp," \%%*lf (\%%*lf)");  
       }      strcpy(dirfileres,optionfilefiname);
       fprintf(ficgp,"\" t\"\" w l 0,");    strcpy(optfileres,"vpl");
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);   /* 1eme*/
       for (j=1; j<= nlstate+1 ; j ++) {    for (cpt=1; cpt<= nlstate ; cpt ++) {
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");     for (k1=1; k1<= m ; k1 ++) {
         else fprintf(ficgp," \%%*lf (\%%*lf)");       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);
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");       fprintf(ficgp,"set xlabel \"Age\" \n\
       else fprintf(ficgp,"\" t\"\" w l 0,");  set ylabel \"Probability\" \n\
     }  set ter png small\n\
   }  set size 0.65,0.65\n\
    plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
   /*3eme*/  
         for (i=1; i<= nlstate ; i ++) {
   for (k1=1; k1<= m ; k1 ++) {         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
     for (cpt=1; cpt<= nlstate ; cpt ++) {         else        fprintf(ficgp," \%%*lf (\%%*lf)");
       /*       k=2+nlstate*(2*cpt-2); */       }
       k=2+(nlstate+1)*(cpt-1);       fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);       for (i=1; i<= nlstate ; i ++) {
       fprintf(ficgp,"set ter png small\n\         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 set size 0.65,0.65\n\         else fprintf(ficgp," \%%*lf (\%%*lf)");
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);       } 
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);       fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");       for (i=1; i<= nlstate ; i ++) {
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
         fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);         else fprintf(ficgp," \%%*lf (\%%*lf)");
         for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");       }  
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);       fprintf(ficgp,"\" t\"\" w l 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
             }
       */    }
       for (i=1; i< nlstate ; i ++) {    /*2 eme*/
         fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);    
         /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/    for (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);
       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);      
     }      for (i=1; i<= nlstate+1 ; i ++) {
   }        k=2*i;
          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
   /* CV preval stable (period) */        for (j=1; j<= nlstate+1 ; j ++) {
   for (k1=1; k1<= m ; k1 ++) {          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
     for (cpt=1; cpt<=nlstate ; cpt ++) {          else fprintf(ficgp," \%%*lf (\%%*lf)");
       k=3;        }   
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 set ter png small\nset size 0.65,0.65\n\        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 unset log y\n\        for (j=1; j<= nlstate+1 ; j ++) {
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                else fprintf(ficgp," \%%*lf (\%%*lf)");
       for (i=1; i< nlstate ; i ++)        }   
         fprintf(ficgp,"+$%d",k+i+1);        fprintf(ficgp,"\" t\"\" w l 0,");
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
              for (j=1; j<= nlstate+1 ; j ++) {
       l=3+(nlstate+ndeath)*cpt;          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);          else fprintf(ficgp," \%%*lf (\%%*lf)");
       for (i=1; i< nlstate ; i ++) {        }   
         l=3+(nlstate+ndeath)*cpt;        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
         fprintf(ficgp,"+$%d",l+i+1);        else fprintf(ficgp,"\" t\"\" w l 0,");
       }      }
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);      }
     }    
   }      /*3eme*/
      
   /* proba elementaires */    for (k1=1; k1<= m ; k1 ++) { 
   for(i=1,jk=1; i <=nlstate; i++){      for (cpt=1; cpt<= nlstate ; cpt ++) {
     for(k=1; k <=(nlstate+ndeath); k++){        /*       k=2+nlstate*(2*cpt-2); */
       if (k != i) {        k=2+(nlstate+1)*(cpt-1);
         for(j=1; j <=ncovmodel; j++){        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);        fprintf(ficgp,"set ter png small\n\
           jk++;  set size 0.65,0.65\n\
           fprintf(ficgp,"\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);
         }        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
       }          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
     }          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
    }          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(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
      for(jk=1; jk <=m; jk++) {          
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);        */
        if (ng==2)        for (i=1; i< nlstate ; i ++) {
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");          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);
        else          /*      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,"\nset title \"Probability\"\n");          
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);        } 
        i=1;        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
        for(k2=1; k2<=nlstate; k2++) {      }
          k3=i;    }
          for(k=1; k<=(nlstate+ndeath); k++) {    
            if (k != k2){    /* CV preval stable (period) */
              if(ng==2)    for (k1=1; k1<= m ; k1 ++) { 
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);      for (cpt=1; cpt<=nlstate ; cpt ++) {
              else        k=3;
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
              ij=1;        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
              for(j=3; j <=ncovmodel; j++) {  set ter png small\nset size 0.65,0.65\n\
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {  unset log y\n\
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);  plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
                  ij++;        
                }        for (i=1; i< nlstate ; i ++)
                else          fprintf(ficgp,"+$%d",k+i+1);
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
              }        
              fprintf(ficgp,")/(1");        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(k1=1; k1 <=nlstate; k1++){          for (i=1; i< nlstate ; i ++) {
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);          l=3+(nlstate+ndeath)*cpt;
                ij=1;          fprintf(ficgp,"+$%d",l+i+1);
                for(j=3; j <=ncovmodel; j++){        }
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);      } 
                    ij++;    }  
                  }    
                  else    /* proba elementaires */
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);    for(i=1,jk=1; i <=nlstate; i++){
                }      for(k=1; k <=(nlstate+ndeath); k++){
                fprintf(ficgp,")");        if (k != i) {
              }          for(j=1; j <=ncovmodel; j++){
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");            jk++; 
              i=i+ncovmodel;            fprintf(ficgp,"\n");
            }          }
          } /* end k */        }
        } /* end k2 */      }
      } /* end jk */     }
    } /* end ng */  
    fflush(ficgp);     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 }  /* end gnuplot */       for(jk=1; jk <=m; jk++) {
          fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
          if (ng==2)
 /*************** Moving average **************/           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){         else
            fprintf(ficgp,"\nset title \"Probability\"\n");
   int i, cpt, cptcod;         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
   int modcovmax =1;         i=1;
   int mobilavrange, mob;         for(k2=1; k2<=nlstate; k2++) {
   double age;           k3=i;
            for(k=1; k<=(nlstate+ndeath); k++) {
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose             if (k != k2){
                            a covariate has 2 modalities */               if(ng==2)
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                else
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
     if(mobilav==1) mobilavrange=5; /* default */               ij=1;
     else mobilavrange=mobilav;               for(j=3; j <=ncovmodel; j++) {
     for (age=bage; age<=fage; age++)                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
       for (i=1; i<=nlstate;i++)                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
         for (cptcod=1;cptcod<=modcovmax;cptcod++)                   ij++;
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];                 }
     /* We keep the original values on the extreme ages bage, fage and for                 else
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
        we use a 5 terms etc. until the borders are no more concerned.               }
     */               fprintf(ficgp,")/(1");
     for (mob=3;mob <=mobilavrange;mob=mob+2){               
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){               for(k1=1; k1 <=nlstate; k1++){   
         for (i=1; i<=nlstate;i++){                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
           for (cptcod=1;cptcod<=modcovmax;cptcod++){                 ij=1;
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];                 for(j=3; j <=ncovmodel; j++){
               for (cpt=1;cpt<=(mob-1)/2;cpt++){                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];                     ij++;
               }                   }
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;                   else
           }                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
         }                 }
       }/* end age */                 fprintf(ficgp,")");
     }/* end mob */               }
   }else return -1;               fprintf(ficgp,") t \"p%d%d\" ", k2,k);
   return 0;               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 }/* End movingaverage */               i=i+ncovmodel;
              }
            } /* end k */
 /************** Forecasting ******************/         } /* end k2 */
 prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){       } /* end jk */
   /* proj1, year, month, day of starting projection     } /* end ng */
      agemin, agemax range of age     fflush(ficgp); 
      dateprev1 dateprev2 range of dates during which prevalence is computed  }  /* end gnuplot */
      anproj2 year of en of projection (same day and month as proj1).  
   */  
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;  /*************** Moving average **************/
   int *popage;  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
   double agec; /* generic age */  
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;    int i, cpt, cptcod;
   double *popeffectif,*popcount;    int modcovmax =1;
   double ***p3mat;    int mobilavrange, mob;
   double ***mobaverage;    double age;
   char fileresf[FILENAMELENGTH];  
     modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
   agelim=AGESUP;                             a covariate has 2 modalities */
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
    
   strcpy(fileresf,"f");    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
   strcat(fileresf,fileres);      if(mobilav==1) mobilavrange=5; /* default */
   if((ficresf=fopen(fileresf,"w"))==NULL) {      else mobilavrange=mobilav;
     printf("Problem with forecast resultfile: %s\n", fileresf);      for (age=bage; age<=fage; age++)
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);        for (i=1; i<=nlstate;i++)
   }          for (cptcod=1;cptcod<=modcovmax;cptcod++)
   printf("Computing forecasting: result on file '%s' \n", fileresf);            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);      /* We keep the original values on the extreme ages bage, fage and for 
          fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
   if (cptcoveff==0) ncodemax[cptcoveff]=1;         we use a 5 terms etc. until the borders are no more concerned. 
       */ 
   if (mobilav!=0) {      for (mob=3;mob <=mobilavrange;mob=mob+2){
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){          for (i=1; i<=nlstate;i++){
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);            for (cptcod=1;cptcod<=modcovmax;cptcod++){
       printf(" Error in movingaverage mobilav=%d\n",mobilav);              mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
     }                for (cpt=1;cpt<=(mob-1)/2;cpt++){
   }                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
   stepsize=(int) (stepm+YEARM-1)/YEARM;                }
   if (stepm<=12) stepsize=1;              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
   if(estepm < stepm){            }
     printf ("Problem %d lower than %d\n",estepm, stepm);          }
   }        }/* end age */
   else  hstepm=estepm;        }/* end mob */
     }else return -1;
   hstepm=hstepm/stepm;    return 0;
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and  }/* End movingaverage */
                                fractional in yp1 */  
   anprojmean=yp;  
   yp2=modf((yp1*12),&yp);  /************** Forecasting ******************/
   mprojmean=yp;  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){
   yp1=modf((yp2*30.5),&yp);    /* proj1, year, month, day of starting projection 
   jprojmean=yp;       agemin, agemax range of age
   if(jprojmean==0) jprojmean=1;       dateprev1 dateprev2 range of dates during which prevalence is computed
   if(mprojmean==0) jprojmean=1;       anproj2 year of en of projection (same day and month as proj1).
     */
   i1=cptcoveff;    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
   if (cptcovn < 1){i1=1;}    int *popage;
      double agec; /* generic age */
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
      double *popeffectif,*popcount;
   fprintf(ficresf,"#****** Routine prevforecast **\n");    double ***p3mat;
     double ***mobaverage;
 /*            if (h==(int)(YEARM*yearp)){ */    char fileresf[FILENAMELENGTH];
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){  
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    agelim=AGESUP;
       k=k+1;    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
       fprintf(ficresf,"\n#******");   
       for(j=1;j<=cptcoveff;j++) {    strcpy(fileresf,"f"); 
         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]]);    strcat(fileresf,fileres);
       }    if((ficresf=fopen(fileresf,"w"))==NULL) {
       fprintf(ficresf,"******\n");      printf("Problem with forecast resultfile: %s\n", fileresf);
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");      fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
       for(j=1; j<=nlstate+ndeath;j++){    }
         for(i=1; i<=nlstate;i++)                  printf("Computing forecasting: result on file '%s' \n", fileresf);
           fprintf(ficresf," p%d%d",i,j);    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
         fprintf(ficresf," p.%d",j);  
       }    if (cptcoveff==0) ncodemax[cptcoveff]=1;
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  
         fprintf(ficresf,"\n");    if (mobilav!=0) {
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);        mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
         for (agec=fage; agec>=(ageminpar-1); agec--){        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
           nhstepm = nhstepm/hstepm;      }
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    }
           oldm=oldms;savm=savms;  
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);      stepsize=(int) (stepm+YEARM-1)/YEARM;
            if (stepm<=12) stepsize=1;
           for (h=0; h<=nhstepm; h++){    if(estepm < stepm){
             if (h*hstepm/YEARM*stepm ==yearp) {      printf ("Problem %d lower than %d\n",estepm, stepm);
               fprintf(ficresf,"\n");    }
               for(j=1;j<=cptcoveff;j++)    else  hstepm=estepm;   
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);    hstepm=hstepm/stepm; 
             }    yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
             for(j=1; j<=nlstate+ndeath;j++) {                                 fractional in yp1 */
               ppij=0.;    anprojmean=yp;
               for(i=1; i<=nlstate;i++) {    yp2=modf((yp1*12),&yp);
                 if (mobilav==1)    mprojmean=yp;
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];    yp1=modf((yp2*30.5),&yp);
                 else {    jprojmean=yp;
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];    if(jprojmean==0) jprojmean=1;
                 }    if(mprojmean==0) jprojmean=1;
                 if (h*hstepm/YEARM*stepm== yearp) {  
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);    i1=cptcoveff;
                 }    if (cptcovn < 1){i1=1;}
               } /* end i */    
               if (h*hstepm/YEARM*stepm==yearp) {    fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                 fprintf(ficresf," %.3f", ppij);    
               }    fprintf(ficresf,"#****** Routine prevforecast **\n");
             }/* end j */  
           } /* end h */  /*            if (h==(int)(YEARM*yearp)){ */
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    for(cptcov=1, k=0;cptcov<=i1;cptcov++){
         } /* end agec */      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
       } /* end yearp */        k=k+1;
     } /* end cptcod */        fprintf(ficresf,"\n#******");
   } /* end  cptcov */        for(j=1;j<=cptcoveff;j++) {
                  fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        }
         fprintf(ficresf,"******\n");
   fclose(ficresf);        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 }        for(j=1; j<=nlstate+ndeath;j++){ 
           for(i=1; i<=nlstate;i++)              
 /************** Forecasting *****not tested NB*************/            fprintf(ficresf," p%d%d",i,j);
 populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){          fprintf(ficresf," p.%d",j);
          }
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;        for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
   int *popage;          fprintf(ficresf,"\n");
   double calagedatem, agelim, kk1, kk2;          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
   double *popeffectif,*popcount;  
   double ***p3mat,***tabpop,***tabpopprev;          for (agec=fage; agec>=(ageminpar-1); agec--){ 
   double ***mobaverage;            nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
   char filerespop[FILENAMELENGTH];            nhstepm = nhstepm/hstepm; 
             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            oldm=oldms;savm=savms;
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
   agelim=AGESUP;          
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;            for (h=0; h<=nhstepm; h++){
                if (h*hstepm/YEARM*stepm ==yearp) {
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);                fprintf(ficresf,"\n");
                  for(j=1;j<=cptcoveff;j++) 
                    fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   strcpy(filerespop,"pop");                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
   strcat(filerespop,fileres);              } 
   if((ficrespop=fopen(filerespop,"w"))==NULL) {              for(j=1; j<=nlstate+ndeath;j++) {
     printf("Problem with forecast resultfile: %s\n", filerespop);                ppij=0.;
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);                for(i=1; i<=nlstate;i++) {
   }                  if (mobilav==1) 
   printf("Computing forecasting: result on file '%s' \n", filerespop);                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);                  else {
                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
   if (cptcoveff==0) ncodemax[cptcoveff]=1;                  }
                   if (h*hstepm/YEARM*stepm== yearp) {
   if (mobilav!=0) {                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                  }
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){                } /* end i */
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);                if (h*hstepm/YEARM*stepm==yearp) {
       printf(" Error in movingaverage mobilav=%d\n",mobilav);                  fprintf(ficresf," %.3f", ppij);
     }                }
   }              }/* end j */
             } /* end h */
   stepsize=(int) (stepm+YEARM-1)/YEARM;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   if (stepm<=12) stepsize=1;          } /* end agec */
          } /* end yearp */
   agelim=AGESUP;      } /* end cptcod */
      } /* end  cptcov */
   hstepm=1;         
   hstepm=hstepm/stepm;    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
    
   if (popforecast==1) {    fclose(ficresf);
     if((ficpop=fopen(popfile,"r"))==NULL) {  }
       printf("Problem with population file : %s\n",popfile);exit(0);  
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);  /************** Forecasting *****not tested NB*************/
     }  populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
     popage=ivector(0,AGESUP);    
     popeffectif=vector(0,AGESUP);    int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
     popcount=vector(0,AGESUP);    int *popage;
        double calagedatem, agelim, kk1, kk2;
     i=1;      double *popeffectif,*popcount;
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;    double ***p3mat,***tabpop,***tabpopprev;
        double ***mobaverage;
     imx=i;    char filerespop[FILENAMELENGTH];
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];  
   }    tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){    agelim=AGESUP;
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
       k=k+1;    
       fprintf(ficrespop,"\n#******");    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
       for(j=1;j<=cptcoveff;j++) {    
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);    
       }    strcpy(filerespop,"pop"); 
       fprintf(ficrespop,"******\n");    strcat(filerespop,fileres);
       fprintf(ficrespop,"# Age");    if((ficrespop=fopen(filerespop,"w"))==NULL) {
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);      printf("Problem with forecast resultfile: %s\n", filerespop);
       if (popforecast==1)  fprintf(ficrespop," [Population]");      fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
          }
       for (cpt=0; cpt<=0;cpt++) {    printf("Computing forecasting: result on file '%s' \n", filerespop);
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);      fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
          
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){    if (cptcoveff==0) ncodemax[cptcoveff]=1;
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  
           nhstepm = nhstepm/hstepm;    if (mobilav!=0) {
                mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
           oldm=oldms;savm=savms;        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);          printf(" Error in movingaverage mobilav=%d\n",mobilav);
              }
           for (h=0; h<=nhstepm; h++){    }
             if (h==(int) (calagedatem+YEARM*cpt)) {  
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);    stepsize=(int) (stepm+YEARM-1)/YEARM;
             }    if (stepm<=12) stepsize=1;
             for(j=1; j<=nlstate+ndeath;j++) {    
               kk1=0.;kk2=0;    agelim=AGESUP;
               for(i=1; i<=nlstate;i++) {                  
                 if (mobilav==1)    hstepm=1;
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];    hstepm=hstepm/stepm; 
                 else {    
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];    if (popforecast==1) {
                 }      if((ficpop=fopen(popfile,"r"))==NULL) {
               }        printf("Problem with population file : %s\n",popfile);exit(0);
               if (h==(int)(calagedatem+12*cpt)){        fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;      } 
                   /*fprintf(ficrespop," %.3f", kk1);      popage=ivector(0,AGESUP);
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/      popeffectif=vector(0,AGESUP);
               }      popcount=vector(0,AGESUP);
             }      
             for(i=1; i<=nlstate;i++){      i=1;   
               kk1=0.;      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                 for(j=1; j<=nlstate;j++){     
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];      imx=i;
                 }      for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];    }
             }  
     for(cptcov=1,k=0;cptcov<=i2;cptcov++){
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);        k=k+1;
           }        fprintf(ficrespop,"\n#******");
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        for(j=1;j<=cptcoveff;j++) {
         }          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
       }        }
          fprintf(ficrespop,"******\n");
   /******/        fprintf(ficrespop,"# Age");
         for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {        if (popforecast==1)  fprintf(ficrespop," [Population]");
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);          
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){        for (cpt=0; cpt<=0;cpt++) { 
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
           nhstepm = nhstepm/hstepm;          
                    for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
           oldm=oldms;savm=savms;            nhstepm = nhstepm/hstepm; 
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);              
           for (h=0; h<=nhstepm; h++){            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             if (h==(int) (calagedatem+YEARM*cpt)) {            oldm=oldms;savm=savms;
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
             }          
             for(j=1; j<=nlstate+ndeath;j++) {            for (h=0; h<=nhstepm; h++){
               kk1=0.;kk2=0;              if (h==(int) (calagedatem+YEARM*cpt)) {
               for(i=1; i<=nlstate;i++) {                              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];                  } 
               }              for(j=1; j<=nlstate+ndeath;j++) {
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                        kk1=0.;kk2=0;
             }                for(i=1; i<=nlstate;i++) {              
           }                  if (mobilav==1) 
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                    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];
    }                  }
   }                }
                  if (h==(int)(calagedatem+12*cpt)){
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                  tabpop[(int)(agedeb)][j][cptcod]=kk1;
                     /*fprintf(ficrespop," %.3f", kk1);
   if (popforecast==1) {                      if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
     free_ivector(popage,0,AGESUP);                }
     free_vector(popeffectif,0,AGESUP);              }
     free_vector(popcount,0,AGESUP);              for(i=1; i<=nlstate;i++){
   }                kk1=0.;
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                  for(j=1; j<=nlstate;j++){
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                    kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
   fclose(ficrespop);                  }
 } /* End of popforecast */                    tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
               }
 int fileappend(FILE *fichier, char *optionfich)  
 {              if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
   if((fichier=fopen(optionfich,"a"))==NULL) {                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
     printf("Problem with file: %s\n", optionfich);            }
     fprintf(ficlog,"Problem with file: %s\n", optionfich);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     return (0);          }
   }        }
   fflush(fichier);   
   return (1);    /******/
 }  
         for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
           fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 /**************** function prwizard **********************/          for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 {            nhstepm = nhstepm/hstepm; 
             
   /* Wizard to print covariance matrix template */            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             oldm=oldms;savm=savms;
   char ca[32], cb[32], cc[32];            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;            for (h=0; h<=nhstepm; h++){
   int numlinepar;              if (h==(int) (calagedatem+YEARM*cpt)) {
                 fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");              } 
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");              for(j=1; j<=nlstate+ndeath;j++) {
   for(i=1; i <=nlstate; i++){                kk1=0.;kk2=0;
     jj=0;                for(i=1; i<=nlstate;i++) {              
     for(j=1; j <=nlstate+ndeath; j++){                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
       if(j==i) continue;                }
       jj++;                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
       /*ca[0]= k+'a'-1;ca[1]='\0';*/              }
       printf("%1d%1d",i,j);            }
       fprintf(ficparo,"%1d%1d",i,j);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       for(k=1; k<=ncovmodel;k++){          }
         /*        printf(" %lf",param[i][j][k]); */        }
         /*        fprintf(ficparo," %lf",param[i][j][k]); */     } 
         printf(" 0.");    }
         fprintf(ficparo," 0.");   
       }    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       printf("\n");  
       fprintf(ficparo,"\n");    if (popforecast==1) {
     }      free_ivector(popage,0,AGESUP);
   }      free_vector(popeffectif,0,AGESUP);
   printf("# Scales (for hessian or gradient estimation)\n");      free_vector(popcount,0,AGESUP);
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");    }
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   for(i=1; i <=nlstate; i++){    free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     jj=0;    fclose(ficrespop);
     for(j=1; j <=nlstate+ndeath; j++){  } /* End of popforecast */
       if(j==i) continue;  
       jj++;  int fileappend(FILE *fichier, char *optionfich)
       fprintf(ficparo,"%1d%1d",i,j);  {
       printf("%1d%1d",i,j);    if((fichier=fopen(optionfich,"a"))==NULL) {
       fflush(stdout);      printf("Problem with file: %s\n", optionfich);
       for(k=1; k<=ncovmodel;k++){      fprintf(ficlog,"Problem with file: %s\n", optionfich);
         /*      printf(" %le",delti3[i][j][k]); */      return (0);
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */    }
         printf(" 0.");    fflush(fichier);
         fprintf(ficparo," 0.");    return (1);
       }  }
       numlinepar++;  
       printf("\n");  
       fprintf(ficparo,"\n");  /**************** function prwizard **********************/
     }  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
   }  {
   printf("# Covariance matrix\n");  
 /* # 121 Var(a12)\n\ */    /* Wizard to print covariance matrix template */
 /* # 122 Cov(b12,a12) Var(b12)\n\ */  
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */    char ca[32], cb[32], cc[32];
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */    int numlinepar;
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */  
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
   fflush(stdout);    for(i=1; i <=nlstate; i++){
   fprintf(ficparo,"# Covariance matrix\n");      jj=0;
   /* # 121 Var(a12)\n\ */      for(j=1; j <=nlstate+ndeath; j++){
   /* # 122 Cov(b12,a12) Var(b12)\n\ */        if(j==i) continue;
   /* #   ...\n\ */        jj++;
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */        /*ca[0]= k+'a'-1;ca[1]='\0';*/
          printf("%1d%1d",i,j);
   for(itimes=1;itimes<=2;itimes++){        fprintf(ficparo,"%1d%1d",i,j);
     jj=0;        for(k=1; k<=ncovmodel;k++){
     for(i=1; i <=nlstate; i++){          /*        printf(" %lf",param[i][j][k]); */
       for(j=1; j <=nlstate+ndeath; j++){          /*        fprintf(ficparo," %lf",param[i][j][k]); */
         if(j==i) continue;          printf(" 0.");
         for(k=1; k<=ncovmodel;k++){          fprintf(ficparo," 0.");
           jj++;        }
           ca[0]= k+'a'-1;ca[1]='\0';        printf("\n");
           if(itimes==1){        fprintf(ficparo,"\n");
             printf("#%1d%1d%d",i,j,k);      }
             fprintf(ficparo,"#%1d%1d%d",i,j,k);    }
           }else{    printf("# Scales (for hessian or gradient estimation)\n");
             printf("%1d%1d%d",i,j,k);    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
             fprintf(ficparo,"%1d%1d%d",i,j,k);    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
             /*  printf(" %.5le",matcov[i][j]); */    for(i=1; i <=nlstate; i++){
           }      jj=0;
           ll=0;      for(j=1; j <=nlstate+ndeath; j++){
           for(li=1;li <=nlstate; li++){        if(j==i) continue;
             for(lj=1;lj <=nlstate+ndeath; lj++){        jj++;
               if(lj==li) continue;        fprintf(ficparo,"%1d%1d",i,j);
               for(lk=1;lk<=ncovmodel;lk++){        printf("%1d%1d",i,j);
                 ll++;        fflush(stdout);
                 if(ll<=jj){        for(k=1; k<=ncovmodel;k++){
                   cb[0]= lk +'a'-1;cb[1]='\0';          /*      printf(" %le",delti3[i][j][k]); */
                   if(ll<jj){          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                     if(itimes==1){          printf(" 0.");
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);          fprintf(ficparo," 0.");
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);        }
                     }else{        numlinepar++;
                       printf(" 0.");        printf("\n");
                       fprintf(ficparo," 0.");        fprintf(ficparo,"\n");
                     }      }
                   }else{    }
                     if(itimes==1){    printf("# Covariance matrix\n");
                       printf(" Var(%s%1d%1d)",ca,i,j);  /* # 121 Var(a12)\n\ */
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);  /* # 122 Cov(b12,a12) Var(b12)\n\ */
                     }else{  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                       printf(" 0.");  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                       fprintf(ficparo," 0.");  /* # 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\ */
                   }  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                 }  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
               } /* end lk */    fflush(stdout);
             } /* end lj */    fprintf(ficparo,"# Covariance matrix\n");
           } /* end li */    /* # 121 Var(a12)\n\ */
           printf("\n");    /* # 122 Cov(b12,a12) Var(b12)\n\ */
           fprintf(ficparo,"\n");    /* #   ...\n\ */
           numlinepar++;    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
         } /* end k*/    
       } /*end j */    for(itimes=1;itimes<=2;itimes++){
     } /* end i */      jj=0;
   } /* end itimes */      for(i=1; i <=nlstate; i++){
         for(j=1; j <=nlstate+ndeath; j++){
 } /* end of prwizard */          if(j==i) continue;
 /******************* Gompertz Likelihood ******************************/          for(k=1; k<=ncovmodel;k++){
 double gompertz(double x[])            jj++;
 {            ca[0]= k+'a'-1;ca[1]='\0';
   double A,B,L=0.0,sump=0.,num=0.;            if(itimes==1){
   int i,n=0; /* n is the size of the sample */              printf("#%1d%1d%d",i,j,k);
               fprintf(ficparo,"#%1d%1d%d",i,j,k);
   for (i=0;i<=imx-1 ; i++) {            }else{
     sump=sump+weight[i];              printf("%1d%1d%d",i,j,k);
     /*    sump=sump+1;*/              fprintf(ficparo,"%1d%1d%d",i,j,k);
     num=num+1;              /*  printf(" %.5le",matcov[i][j]); */
   }            }
              ll=0;
              for(li=1;li <=nlstate; li++){
   /* for (i=0; i<=imx; i++)              for(lj=1;lj <=nlstate+ndeath; lj++){
      if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/                if(lj==li) continue;
                 for(lk=1;lk<=ncovmodel;lk++){
   for (i=1;i<=imx ; i++)                  ll++;
     {                  if(ll<=jj){
       if (cens[i] == 1 && wav[i]>1)                    cb[0]= lk +'a'-1;cb[1]='\0';
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));                    if(ll<jj){
                            if(itimes==1){
       if (cens[i] == 0 && wav[i]>1)                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);                        }else{
                              printf(" 0.");
       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */                        fprintf(ficparo," 0.");
       if (wav[i] > 1 ) { /* ??? */                      }
         L=L+A*weight[i];                    }else{
         /*      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]);*/                      if(itimes==1){
       }                        printf(" Var(%s%1d%1d)",ca,i,j);
     }                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                       }else{
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/                        printf(" 0.");
                          fprintf(ficparo," 0.");
   return -2*L*num/sump;                      }
 }                    }
                   }
 /******************* Printing html file ***********/                } /* end lk */
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \              } /* end lj */
                   int lastpass, int stepm, int weightopt, char model[],\            } /* end li */
                   int imx,  double p[],double **matcov,double agemortsup){            printf("\n");
   int i,k;            fprintf(ficparo,"\n");
             numlinepar++;
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");          } /* end k*/
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);        } /*end j */
   for (i=1;i<=2;i++)      } /* end 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]));    } /* end itimes */
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");  
   fprintf(fichtm,"</ul>");  } /* end of prwizard */
   /******************* Gompertz Likelihood ******************************/
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");  double gompertz(double x[])
   { 
  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>");    double A,B,L=0.0,sump=0.,num=0.;
     int i,n=0; /* n is the size of the sample */
  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]);    for (i=0;i<=imx-1 ; i++) {
       sump=sump+weight[i];
        /*    sump=sump+1;*/
   fflush(fichtm);      num=num+1;
 }    }
    
 /******************* Gnuplot file **************/   
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){    /* for (i=0; i<=imx; i++) 
        if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
   char dirfileres[132],optfileres[132];  
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;    for (i=1;i<=imx ; i++)
   int ng;      {
         if (cens[i] == 1 && wav[i]>1)
           A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
   /*#ifdef windows */        
   fprintf(ficgp,"cd \"%s\" \n",pathc);        if (cens[i] == 0 && wav[i]>1)
     /*#endif */          A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
         
   strcpy(dirfileres,optionfilefiname);        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
   strcpy(optfileres,"vpl");        if (wav[i] > 1 ) { /* ??? */
   fprintf(ficgp,"set out \"graphmort.png\"\n ");          L=L+A*weight[i];
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");          /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
   fprintf(ficgp, "set ter png small\n set log y\n");        }
   fprintf(ficgp, "set size 0.65,0.65\n");      }
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);  
    /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 }   
     return -2*L*num/sump;
   }
   
   /******************* Printing html file ***********/
   void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 /***********************************************/                    int lastpass, int stepm, int weightopt, char model[],\
 /**************** Main Program *****************/                    int imx,  double p[],double **matcov,double agemortsup){
 /***********************************************/    int i,k;
   
 int main(int argc, char *argv[])    fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 {    fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);    for (i=1;i<=2;i++) 
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;      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]));
   int linei, month, year,iout;    fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
   int jj, ll, li, lj, lk, imk;    fprintf(fichtm,"</ul>");
   int numlinepar=0; /* Current linenumber of parameter file */  
   int itimes;  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
   int NDIM=2;  
    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>");
   char ca[32], cb[32], cc[32];  
   char dummy[]="                         ";   for (k=agegomp;k<(agemortsup-2);k++) 
   /*  FILE *fichtm; *//* Html File */     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]);
   /* FILE *ficgp;*/ /*Gnuplot File */  
   struct stat info;   
   double agedeb, agefin,hf;    fflush(fichtm);
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;  }
   
   double fret;  /******************* Gnuplot file **************/
   double **xi,tmp,delta;  void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   
   double dum; /* Dummy variable */    char dirfileres[132],optfileres[132];
   double ***p3mat;    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
   double ***mobaverage;    int ng;
   int *indx;  
   char line[MAXLINE], linepar[MAXLINE];  
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];    /*#ifdef windows */
   char pathr[MAXLINE], pathimach[MAXLINE];    fprintf(ficgp,"cd \"%s\" \n",pathc);
   char **bp, *tok, *val; /* pathtot */      /*#endif */
   int firstobs=1, lastobs=10;  
   int sdeb, sfin; /* Status at beginning and end */  
   int c,  h , cpt,l;    strcpy(dirfileres,optionfilefiname);
   int ju,jl, mi;    strcpy(optfileres,"vpl");
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;    fprintf(ficgp,"set out \"graphmort.png\"\n "); 
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;    fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */    fprintf(ficgp, "set ter png small\n set log y\n"); 
   int mobilav=0,popforecast=0;    fprintf(ficgp, "set size 0.65,0.65\n");
   int hstepm, nhstepm;    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
   int agemortsup;  
   float  sumlpop=0.;  } 
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;  
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;  
   
   double bage, fage, age, agelim, agebase;  
   double ftolpl=FTOL;  
   double **prlim;  /***********************************************/
   double *severity;  /**************** Main Program *****************/
   double ***param; /* Matrix of parameters */  /***********************************************/
   double  *p;  
   double **matcov; /* Matrix of covariance */  int main(int argc, char *argv[])
   double ***delti3; /* Scale */  {
   double *delti; /* Scale */    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
   double ***eij, ***vareij;    int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
   double **varpl; /* Variances of prevalence limits by age */    int linei, month, year,iout;
   double *epj, vepp;    int jj, ll, li, lj, lk, imk;
   double kk1, kk2;    int numlinepar=0; /* Current linenumber of parameter file */
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;    int itimes;
   double **ximort;    int NDIM=2;
   char *alph[]={"a","a","b","c","d","e"}, str[4];    int vpopbased=0;
   int *dcwave;  
     char ca[32], cb[32], cc[32];
   char z[1]="c", occ;    char dummy[]="                         ";
     /*  FILE *fichtm; *//* Html File */
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];    /* FILE *ficgp;*/ /*Gnuplot File */
   char  *strt, strtend[80];    struct stat info;
   char *stratrunc;    double agedeb, agefin,hf;
   int lstra;    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
   
   long total_usecs;    double fret;
      double **xi,tmp,delta;
 /*   setlocale (LC_ALL, ""); */  
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */    double dum; /* Dummy variable */
 /*   textdomain (PACKAGE); */    double ***p3mat;
 /*   setlocale (LC_CTYPE, ""); */    double ***mobaverage;
 /*   setlocale (LC_MESSAGES, ""); */    int *indx;
     char line[MAXLINE], linepar[MAXLINE];
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */    char linetmp[MAXLINE];
   (void) gettimeofday(&start_time,&tzp);      char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
   curr_time=start_time;    char pathr[MAXLINE], pathimach[MAXLINE]; 
   tm = *localtime(&start_time.tv_sec);    char **bp, *tok, *val; /* pathtot */
   tmg = *gmtime(&start_time.tv_sec);    int firstobs=1, lastobs=10;
   strcpy(strstart,asctime(&tm));    int sdeb, sfin; /* Status at beginning and end */
     int c,  h , cpt,l;
 /*  printf("Localtime (at start)=%s",strstart); */    int ju,jl, mi;
 /*  tp.tv_sec = tp.tv_sec +86400; */    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
 /*  tm = *localtime(&start_time.tv_sec); */    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab; 
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */    int mobilav=0,popforecast=0;
 /*   tmg.tm_hour=tmg.tm_hour + 1; */    int hstepm, nhstepm;
 /*   tp.tv_sec = mktime(&tmg); */    int agemortsup;
 /*   strt=asctime(&tmg); */    float  sumlpop=0.;
 /*   printf("Time(after) =%s",strstart);  */    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 /*  (void) time (&time_value);    double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);  
 *  tm = *localtime(&time_value);    double bage, fage, age, agelim, agebase;
 *  strstart=asctime(&tm);    double ftolpl=FTOL;
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);    double **prlim;
 */    double *severity;
     double ***param; /* Matrix of parameters */
   nberr=0; /* Number of errors and warnings */    double  *p;
   nbwarn=0;    double **matcov; /* Matrix of covariance */
   getcwd(pathcd, size);    double ***delti3; /* Scale */
     double *delti; /* Scale */
   printf("\n%s\n%s",version,fullversion);    double ***eij, ***vareij;
   if(argc <=1){    double **varpl; /* Variances of prevalence limits by age */
     printf("\nEnter the parameter file name: ");    double *epj, vepp;
     fgets(pathr,FILENAMELENGTH,stdin);    double kk1, kk2;
     i=strlen(pathr);    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
     if(pathr[i-1]=='\n')    double **ximort;
       pathr[i-1]='\0';    char *alph[]={"a","a","b","c","d","e"}, str[4];
    for (tok = pathr; tok != NULL; ){    int *dcwave;
       printf("Pathr |%s|\n",pathr);  
       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');    char z[1]="c", occ;
       printf("val= |%s| pathr=%s\n",val,pathr);  
       strcpy (pathtot, val);    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
       if(pathr[0] == '\0') break; /* Dirty */    char  *strt, strtend[80];
     }    char *stratrunc;
   }    int lstra;
   else{  
     strcpy(pathtot,argv[1]);    long total_usecs;
   }   
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/  /*   setlocale (LC_ALL, ""); */
   /*cygwin_split_path(pathtot,path,optionfile);  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/  /*   textdomain (PACKAGE); */
   /* cutv(path,optionfile,pathtot,'\\');*/  /*   setlocale (LC_CTYPE, ""); */
   /*   setlocale (LC_MESSAGES, ""); */
   /* Split argv[0], imach program to get pathimach */  
   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);    (void) gettimeofday(&start_time,&tzp);
   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);    curr_time=start_time;
  /*   strcpy(pathimach,argv[0]); */    tm = *localtime(&start_time.tv_sec);
   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */    tmg = *gmtime(&start_time.tv_sec);
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);    strcpy(strstart,asctime(&tm));
   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);  
   chdir(path); /* Can be a relative path */  /*  printf("Localtime (at start)=%s",strstart); */
   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */  /*  tp.tv_sec = tp.tv_sec +86400; */
     printf("Current directory %s!\n",pathcd);  /*  tm = *localtime(&start_time.tv_sec); */
   strcpy(command,"mkdir ");  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
   strcat(command,optionfilefiname);  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
   if((outcmd=system(command)) != 0){  /*   tmg.tm_hour=tmg.tm_hour + 1; */
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);  /*   tp.tv_sec = mktime(&tmg); */
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */  /*   strt=asctime(&tmg); */
     /* fclose(ficlog); */  /*   printf("Time(after) =%s",strstart);  */
 /*     exit(1); */  /*  (void) time (&time_value);
   }  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 /*   if((imk=mkdir(optionfilefiname))<0){ */  *  tm = *localtime(&time_value);
 /*     perror("mkdir"); */  *  strstart=asctime(&tm);
 /*   } */  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
   */
   /*-------- arguments in the command line --------*/  
     nberr=0; /* Number of errors and warnings */
   /* Log file */    nbwarn=0;
   strcat(filelog, optionfilefiname);    getcwd(pathcd, size);
   strcat(filelog,".log");    /* */  
   if((ficlog=fopen(filelog,"w"))==NULL)    {    printf("\n%s\n%s",version,fullversion);
     printf("Problem with logfile %s\n",filelog);    if(argc <=1){
     goto end;      printf("\nEnter the parameter file name: ");
   }      fgets(pathr,FILENAMELENGTH,stdin);
   fprintf(ficlog,"Log filename:%s\n",filelog);      i=strlen(pathr);
   fprintf(ficlog,"\n%s\n%s",version,fullversion);      if(pathr[i-1]=='\n')
   fprintf(ficlog,"\nEnter the parameter file name: \n");        pathr[i-1]='\0';
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\     for (tok = pathr; tok != NULL; ){
  path=%s \n\        printf("Pathr |%s|\n",pathr);
  optionfile=%s\n\        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
  optionfilext=%s\n\        printf("val= |%s| pathr=%s\n",val,pathr);
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);        strcpy (pathtot, val);
         if(pathr[0] == '\0') break; /* Dirty */
   printf("Local time (at start):%s",strstart);      }
   fprintf(ficlog,"Local time (at start): %s",strstart);    }
   fflush(ficlog);    else{
 /*   (void) gettimeofday(&curr_time,&tzp); */      strcpy(pathtot,argv[1]);
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */    }
     /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
   /* */    /*cygwin_split_path(pathtot,path,optionfile);
   strcpy(fileres,"r");      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
   strcat(fileres, optionfilefiname);    /* cutv(path,optionfile,pathtot,'\\');*/
   strcat(fileres,".txt");    /* Other files have txt extension */  
     /* Split argv[0], imach program to get pathimach */
   /*---------arguments file --------*/    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
     split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   if((ficpar=fopen(optionfile,"r"))==NULL)    {    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
     printf("Problem with optionfile %s\n",optionfile);   /*   strcpy(pathimach,argv[0]); */
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
     fflush(ficlog);    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
     goto end;    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
   }    chdir(path); /* Can be a relative path */
     if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
       printf("Current directory %s!\n",pathcd);
     strcpy(command,"mkdir ");
   strcpy(filereso,"o");    strcat(command,optionfilefiname);
   strcat(filereso,fileres);    if((outcmd=system(command)) != 0){
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */      printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
     printf("Problem with Output resultfile: %s\n", filereso);      /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);      /* fclose(ficlog); */
     fflush(ficlog);  /*     exit(1); */
     goto end;    }
   }  /*   if((imk=mkdir(optionfilefiname))<0){ */
   /*     perror("mkdir"); */
   /* Reads comments: lines beginning with '#' */  /*   } */
   numlinepar=0;  
   while((c=getc(ficpar))=='#' && c!= EOF){    /*-------- arguments in the command line --------*/
     ungetc(c,ficpar);  
     fgets(line, MAXLINE, ficpar);    /* Log file */
     numlinepar++;    strcat(filelog, optionfilefiname);
     puts(line);    strcat(filelog,".log");    /* */
     fputs(line,ficparo);    if((ficlog=fopen(filelog,"w"))==NULL)    {
     fputs(line,ficlog);      printf("Problem with logfile %s\n",filelog);
   }      goto end;
   ungetc(c,ficpar);    }
     fprintf(ficlog,"Log filename:%s\n",filelog);
   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);    fprintf(ficlog,"\n%s\n%s",version,fullversion);
   numlinepar++;    fprintf(ficlog,"\nEnter the parameter file name: \n");
   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
   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);   path=%s \n\
   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);   optionfile=%s\n\
   fflush(ficlog);   optionfilext=%s\n\
   while((c=getc(ficpar))=='#' && c!= EOF){   optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
     ungetc(c,ficpar);  
     fgets(line, MAXLINE, ficpar);    printf("Local time (at start):%s",strstart);
     numlinepar++;    fprintf(ficlog,"Local time (at start): %s",strstart);
     puts(line);    fflush(ficlog);
     fputs(line,ficparo);  /*   (void) gettimeofday(&curr_time,&tzp); */
     fputs(line,ficlog);  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   }  
   ungetc(c,ficpar);    /* */
     strcpy(fileres,"r");
        strcat(fileres, optionfilefiname);
   covar=matrix(0,NCOVMAX,1,n);    strcat(fileres,".txt");    /* Other files have txt extension */
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/  
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;    /*---------arguments file --------*/
   
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */    if((ficpar=fopen(optionfile,"r"))==NULL)    {
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */      printf("Problem with optionfile %s\n",optionfile);
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
       fflush(ficlog);
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      goto end;
   delti=delti3[1][1];    }
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/  
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */  
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);  
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);    strcpy(filereso,"o");
     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);    strcat(filereso,fileres);
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
     fclose (ficparo);      printf("Problem with Output resultfile: %s\n", filereso);
     fclose (ficlog);      fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
     goto end;      fflush(ficlog);
     exit(0);      goto end;
   }    }
   else if(mle==-3) {  
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);    /* Reads comments: lines beginning with '#' */
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    numlinepar=0;
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    while((c=getc(ficpar))=='#' && c!= EOF){
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      ungetc(c,ficpar);
     matcov=matrix(1,npar,1,npar);      fgets(line, MAXLINE, ficpar);
   }      numlinepar++;
   else{      puts(line);
     /* Read guess parameters */      fputs(line,ficparo);
     /* Reads comments: lines beginning with '#' */      fputs(line,ficlog);
     while((c=getc(ficpar))=='#' && c!= EOF){    }
       ungetc(c,ficpar);    ungetc(c,ficpar);
       fgets(line, MAXLINE, ficpar);  
       numlinepar++;    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);
       puts(line);    numlinepar++;
       fputs(line,ficparo);    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);
       fputs(line,ficlog);    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);
     ungetc(c,ficpar);    fflush(ficlog);
        while((c=getc(ficpar))=='#' && c!= EOF){
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      ungetc(c,ficpar);
     for(i=1; i <=nlstate; i++){      fgets(line, MAXLINE, ficpar);
       j=0;      numlinepar++;
       for(jj=1; jj <=nlstate+ndeath; jj++){      puts(line);
         if(jj==i) continue;      fputs(line,ficparo);
         j++;      fputs(line,ficlog);
         fscanf(ficpar,"%1d%1d",&i1,&j1);    }
         if ((i1 != i) && (j1 != j)){    ungetc(c,ficpar);
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \  
 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);    covar=matrix(0,NCOVMAX,1,n); 
           exit(1);    cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
         }    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
         fprintf(ficparo,"%1d%1d",i1,j1);    /* where is ncovprod ?*/
         if(mle==1)    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7*/
           printf("%1d%1d",i,j);    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
         fprintf(ficlog,"%1d%1d",i,j);    nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
         for(k=1; k<=ncovmodel;k++){    npar= nforce*ncovmodel; /* Number of parameters like aij*/
           fscanf(ficpar," %lf",&param[i][j][k]);    if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
           if(mle==1){      printf("Too complex model for current IMaCh: npar=(nlstate+ndeath-1)*nlstate*ncovmodel=%d >= %d(MAXPARM) or nlstate=%d >= %d(NLSTATEMAX) or ndeath=%d >= %d(NDEATHMAX) or ncovmodel=(k+age+#of+signs)=%d(NCOVMAX) >= %d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
             printf(" %lf",param[i][j][k]);      fprintf(ficlog,"Too complex model for current IMaCh: %d >=%d(MAXPARM) or %d >=%d(NLSTATEMAX) or %d >=%d(NDEATHMAX) or %d(NCOVMAX) >=%d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
             fprintf(ficlog," %lf",param[i][j][k]);      fflush(stdout);
           }      fclose (ficlog);
           else      goto end;
             fprintf(ficlog," %lf",param[i][j][k]);    }
           fprintf(ficparo," %lf",param[i][j][k]);    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         }    delti=delti3[1][1];
         fscanf(ficpar,"\n");    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
         numlinepar++;    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
         if(mle==1)      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
           printf("\n");      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
         fprintf(ficlog,"\n");      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
         fprintf(ficparo,"\n");      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
       }      fclose (ficparo);
     }        fclose (ficlog);
     fflush(ficlog);      goto end;
       exit(0);
     p=param[1][1];    }
        else if(mle==-3) {
     /* Reads comments: lines beginning with '#' */      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
     while((c=getc(ficpar))=='#' && c!= EOF){      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);
       fgets(line, MAXLINE, ficpar);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
       numlinepar++;      matcov=matrix(1,npar,1,npar);
       puts(line);    }
       fputs(line,ficparo);    else{
       fputs(line,ficlog);      /* Read guess parameters */
     }      /* Reads comments: lines beginning with '#' */
     ungetc(c,ficpar);      while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
     for(i=1; i <=nlstate; i++){        fgets(line, MAXLINE, ficpar);
       for(j=1; j <=nlstate+ndeath-1; j++){        numlinepar++;
         fscanf(ficpar,"%1d%1d",&i1,&j1);        puts(line);
         if ((i1-i)*(j1-j)!=0){        fputs(line,ficparo);
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);        fputs(line,ficlog);
           exit(1);      }
         }      ungetc(c,ficpar);
         printf("%1d%1d",i,j);      
         fprintf(ficparo,"%1d%1d",i1,j1);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
         fprintf(ficlog,"%1d%1d",i1,j1);      for(i=1; i <=nlstate; i++){
         for(k=1; k<=ncovmodel;k++){        j=0;
           fscanf(ficpar,"%le",&delti3[i][j][k]);        for(jj=1; jj <=nlstate+ndeath; jj++){
           printf(" %le",delti3[i][j][k]);          if(jj==i) continue;
           fprintf(ficparo," %le",delti3[i][j][k]);          j++;
           fprintf(ficlog," %le",delti3[i][j][k]);          fscanf(ficpar,"%1d%1d",&i1,&j1);
         }          if ((i1 != i) && (j1 != j)){
         fscanf(ficpar,"\n");            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
         numlinepar++;  It might be a problem of design; if ncovcol and the model are correct\n \
         printf("\n");  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
         fprintf(ficparo,"\n");            exit(1);
         fprintf(ficlog,"\n");          }
       }          fprintf(ficparo,"%1d%1d",i1,j1);
     }          if(mle==1)
     fflush(ficlog);            printf("%1d%1d",i,j);
           fprintf(ficlog,"%1d%1d",i,j);
     delti=delti3[1][1];          for(k=1; k<=ncovmodel;k++){
             fscanf(ficpar," %lf",&param[i][j][k]);
             if(mle==1){
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */              printf(" %lf",param[i][j][k]);
                fprintf(ficlog," %lf",param[i][j][k]);
     /* Reads comments: lines beginning with '#' */            }
     while((c=getc(ficpar))=='#' && c!= EOF){            else
       ungetc(c,ficpar);              fprintf(ficlog," %lf",param[i][j][k]);
       fgets(line, MAXLINE, ficpar);            fprintf(ficparo," %lf",param[i][j][k]);
       numlinepar++;          }
       puts(line);          fscanf(ficpar,"\n");
       fputs(line,ficparo);          numlinepar++;
       fputs(line,ficlog);          if(mle==1)
     }            printf("\n");
     ungetc(c,ficpar);          fprintf(ficlog,"\n");
            fprintf(ficparo,"\n");
     matcov=matrix(1,npar,1,npar);        }
     for(i=1; i <=npar; i++){      }  
       fscanf(ficpar,"%s",&str);      fflush(ficlog);
       if(mle==1)  
         printf("%s",str);      p=param[1][1];
       fprintf(ficlog,"%s",str);      
       fprintf(ficparo,"%s",str);      /* Reads comments: lines beginning with '#' */
       for(j=1; j <=i; j++){      while((c=getc(ficpar))=='#' && c!= EOF){
         fscanf(ficpar," %le",&matcov[i][j]);        ungetc(c,ficpar);
         if(mle==1){        fgets(line, MAXLINE, ficpar);
           printf(" %.5le",matcov[i][j]);        numlinepar++;
         }        puts(line);
         fprintf(ficlog," %.5le",matcov[i][j]);        fputs(line,ficparo);
         fprintf(ficparo," %.5le",matcov[i][j]);        fputs(line,ficlog);
       }      }
       fscanf(ficpar,"\n");      ungetc(c,ficpar);
       numlinepar++;  
       if(mle==1)      for(i=1; i <=nlstate; i++){
         printf("\n");        for(j=1; j <=nlstate+ndeath-1; j++){
       fprintf(ficlog,"\n");          fscanf(ficpar,"%1d%1d",&i1,&j1);
       fprintf(ficparo,"\n");          if ((i1-i)*(j1-j)!=0){
     }            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
     for(i=1; i <=npar; i++)            exit(1);
       for(j=i+1;j<=npar;j++)          }
         matcov[i][j]=matcov[j][i];          printf("%1d%1d",i,j);
              fprintf(ficparo,"%1d%1d",i1,j1);
     if(mle==1)          fprintf(ficlog,"%1d%1d",i1,j1);
       printf("\n");          for(k=1; k<=ncovmodel;k++){
     fprintf(ficlog,"\n");            fscanf(ficpar,"%le",&delti3[i][j][k]);
                printf(" %le",delti3[i][j][k]);
     fflush(ficlog);            fprintf(ficparo," %le",delti3[i][j][k]);
                fprintf(ficlog," %le",delti3[i][j][k]);
     /*-------- Rewriting parameter file ----------*/          }
     strcpy(rfileres,"r");    /* "Rparameterfile */          fscanf(ficpar,"\n");
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/          numlinepar++;
     strcat(rfileres,".");    /* */          printf("\n");
     strcat(rfileres,optionfilext);    /* Other files have txt extension */          fprintf(ficparo,"\n");
     if((ficres =fopen(rfileres,"w"))==NULL) {          fprintf(ficlog,"\n");
       printf("Problem writing new parameter file: %s\n", fileres);goto end;        }
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;      }
     }      fflush(ficlog);
     fprintf(ficres,"#%s\n",version);  
   }    /* End of mle != -3 */      delti=delti3[1][1];
   
   /*-------- data file ----------*/  
   if((fic=fopen(datafile,"r"))==NULL)    {      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
     printf("Problem while opening datafile: %s\n", datafile);goto end;    
     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;      /* Reads comments: lines beginning with '#' */
   }      while((c=getc(ficpar))=='#' && c!= EOF){
         ungetc(c,ficpar);
   n= lastobs;        fgets(line, MAXLINE, ficpar);
   severity = vector(1,maxwav);        numlinepar++;
   outcome=imatrix(1,maxwav+1,1,n);        puts(line);
   num=lvector(1,n);        fputs(line,ficparo);
   moisnais=vector(1,n);        fputs(line,ficlog);
   annais=vector(1,n);      }
   moisdc=vector(1,n);      ungetc(c,ficpar);
   andc=vector(1,n);    
   agedc=vector(1,n);      matcov=matrix(1,npar,1,npar);
   cod=ivector(1,n);      for(i=1; i <=npar; i++)
   weight=vector(1,n);        for(j=1; j <=npar; j++) matcov[i][j]=0.;
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */        
   mint=matrix(1,maxwav,1,n);      for(i=1; i <=npar; i++){
   anint=matrix(1,maxwav,1,n);        fscanf(ficpar,"%s",&str);
   s=imatrix(1,maxwav+1,1,n);        if(mle==1)
   tab=ivector(1,NCOVMAX);          printf("%s",str);
   ncodemax=ivector(1,8);        fprintf(ficlog,"%s",str);
         fprintf(ficparo,"%s",str);
   i=1;        for(j=1; j <=i; j++){
   linei=0;          fscanf(ficpar," %le",&matcov[i][j]);
   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {          if(mle==1){
     linei=linei+1;            printf(" %.5le",matcov[i][j]);
     for(j=strlen(line); j>=0;j--){  /* Untabifies line */          }
       if(line[j] == '\t')          fprintf(ficlog," %.5le",matcov[i][j]);
         line[j] = ' ';          fprintf(ficparo," %.5le",matcov[i][j]);
     }        }
     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){        fscanf(ficpar,"\n");
       ;        numlinepar++;
     };        if(mle==1)
     line[j+1]=0;  /* Trims blanks at end of line */          printf("\n");
     if(line[0]=='#'){        fprintf(ficlog,"\n");
       fprintf(ficlog,"Comment line\n%s\n",line);        fprintf(ficparo,"\n");
       printf("Comment line\n%s\n",line);      }
       continue;      for(i=1; i <=npar; i++)
     }        for(j=i+1;j<=npar;j++)
           matcov[i][j]=matcov[j][i];
     for (j=maxwav;j>=1;j--){      
       cutv(stra, strb,line,' ');      if(mle==1)
       errno=0;        printf("\n");
       lval=strtol(strb,&endptr,10);      fprintf(ficlog,"\n");
       /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/      
       if( strb[0]=='\0' || (*endptr != '\0')){      fflush(ficlog);
         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);      /*-------- Rewriting parameter file ----------*/
       }      strcpy(rfileres,"r");    /* "Rparameterfile */
       s[j][i]=lval;      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
            strcat(rfileres,".");    /* */
       strcpy(line,stra);      strcat(rfileres,optionfilext);    /* Other files have txt extension */
       cutv(stra, strb,line,' ');      if((ficres =fopen(rfileres,"w"))==NULL) {
       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){        printf("Problem writing new parameter file: %s\n", fileres);goto end;
       }        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
       else  if(iout=sscanf(strb,"%s.") != 0){      }
         month=99;      fprintf(ficres,"#%s\n",version);
         year=9999;    }    /* End of mle != -3 */
       }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);    /*-------- data file ----------*/
         exit(1);    if((fic=fopen(datafile,"r"))==NULL)    {
       }      printf("Problem while opening datafile: %s\n", datafile);goto end;
       anint[j][i]= (double) year;      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
       mint[j][i]= (double)month;    }
       strcpy(line,stra);  
     } /* ENd Waves */    n= lastobs;
        severity = vector(1,maxwav);
     cutv(stra, strb,line,' ');    outcome=imatrix(1,maxwav+1,1,n);
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){    num=lvector(1,n);
     }    moisnais=vector(1,n);
     else  if(iout=sscanf(strb,"%s.",dummy) != 0){    annais=vector(1,n);
       month=99;    moisdc=vector(1,n);
       year=9999;    andc=vector(1,n);
     }else{    agedc=vector(1,n);
       printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);    cod=ivector(1,n);
       exit(1);    weight=vector(1,n);
     }    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
     andc[i]=(double) year;    mint=matrix(1,maxwav,1,n);
     moisdc[i]=(double) month;    anint=matrix(1,maxwav,1,n);
     strcpy(line,stra);    s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
        tab=ivector(1,NCOVMAX);
     cutv(stra, strb,line,' ');    ncodemax=ivector(1,8);
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){  
     }    i=1;
     else  if(iout=sscanf(strb,"%s.") != 0){    linei=0;
       month=99;    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
       year=9999;      linei=linei+1;
     }else{      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
       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);        if(line[j] == '\t')
       exit(1);          line[j] = ' ';
     }      }
     annais[i]=(double)(year);      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
     moisnais[i]=(double)(month);        ;
     strcpy(line,stra);      };
          line[j+1]=0;  /* Trims blanks at end of line */
     cutv(stra, strb,line,' ');      if(line[0]=='#'){
     errno=0;        fprintf(ficlog,"Comment line\n%s\n",line);
     dval=strtod(strb,&endptr);        printf("Comment line\n%s\n",line);
     if( strb[0]=='\0' || (*endptr != '\0')){        continue;
       printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);      }
       exit(1);      trimbb(linetmp,line); /* Trims multiple blanks in line */
     }      for (j=0; line[j]!='\0';j++){
     weight[i]=dval;        line[j]=linetmp[j];
     strcpy(line,stra);      }
        
     for (j=ncovcol;j>=1;j--){  
       cutv(stra, strb,line,' ');      for (j=maxwav;j>=1;j--){
       errno=0;        cutv(stra, strb,line,' '); 
       lval=strtol(strb,&endptr,10);        if(strb[0]=='.') { /* Missing status */
       if( strb[0]=='\0' || (*endptr != '\0')){          lval=-1;
         printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a covar (meaning 0 for the reference or 1).  Exiting.\n",lval, linei,i, line);        }else{
         exit(1);          errno=0;
       }          lval=strtol(strb,&endptr,10); 
       if(lval <-1 || lval >1){        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
         printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \          if( strb[0]=='\0' || (*endptr != '\0')){
  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \            printf("Error reading data around '%s' at line number %ld 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);
  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \            fprintf(ficlog,"Error reading data around '%s' at line number %ld 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);fflush(ficlog);
  For example, for multinomial values like 1, 2 and 3,\n \            goto end;
  build V1=0 V2=0 for the reference value (1),\n \          }
         V1=1 V2=0 for (2) \n \        }
  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \        s[j][i]=lval;
  output of IMaCh is often meaningless.\n \        
  Exiting.\n",lval,linei, i,line,j);        strcpy(line,stra);
         exit(1);        cutv(stra, strb,line,' ');
       }        if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
       covar[j][i]=(double)(lval);        }
       strcpy(line,stra);        else  if(iout=sscanf(strb,"%s.") != 0){
     }          month=99;
     lstra=strlen(stra);          year=9999;
            }else{
     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */          printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
       stratrunc = &(stra[lstra-9]);          fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);fflush(ficlog);
       num[i]=atol(stratrunc);          goto end;
     }        }
     else        anint[j][i]= (double) year; 
       num[i]=atol(stra);        mint[j][i]= (double)month; 
     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){        strcpy(line,stra);
       printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/      } /* ENd Waves */
          
     i=i+1;      cutv(stra, strb,line,' '); 
   } /* End loop reading  data */      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
   fclose(fic);      }
   /* printf("ii=%d", ij);      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
      scanf("%d",i);*/        month=99;
   imx=i-1; /* Number of individuals */        year=9999;
       }else{
   /* for (i=1; i<=imx; i++){        printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
     if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;          fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
     if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;          goto end;
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;      }
     }*/      andc[i]=(double) year; 
    /*  for (i=1; i<=imx; i++){      moisdc[i]=(double) month; 
      if (s[4][i]==9)  s[4][i]=-1;      strcpy(line,stra);
      printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/      
        cutv(stra, strb,line,' '); 
   /* for (i=1; i<=imx; i++) */      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
        }
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;      else  if(iout=sscanf(strb,"%s.") != 0){
      else weight[i]=1;*/        month=99;
         year=9999;
   /* Calculation of the number of parameters from char model */      }else{
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */        printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
   Tprod=ivector(1,15);        fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
   Tvaraff=ivector(1,15);          goto end;
   Tvard=imatrix(1,15,1,2);      }
   Tage=ivector(1,15);            if (year==9999) {
            printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given.  Exiting.\n",strb, linei,i,line);
   if (strlen(model) >1){ /* If there is at least 1 covariate */        fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given. Exiting.\n",strb, linei,i,line);fflush(ficlog);
     j=0, j1=0, k1=1, k2=1;          goto end;
     j=nbocc(model,'+'); /* j=Number of '+' */  
     j1=nbocc(model,'*'); /* j1=Number of '*' */      }
     cptcovn=j+1;      annais[i]=(double)(year);
     cptcovprod=j1; /*Number of products */      moisnais[i]=(double)(month); 
          strcpy(line,stra);
     strcpy(modelsav,model);      
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){      cutv(stra, strb,line,' '); 
       printf("Error. Non available option model=%s ",model);      errno=0;
       fprintf(ficlog,"Error. Non available option model=%s ",model);      dval=strtod(strb,&endptr); 
       goto end;      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);
            fprintf(ficlog,"Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
     /* This loop fills the array Tvar from the string 'model'.*/        fflush(ficlog);
         goto end;
     for(i=(j+1); i>=1;i--){      }
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */      weight[i]=dval; 
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */      strcpy(line,stra);
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/      
       /*scanf("%d",i);*/      for (j=ncovcol;j>=1;j--){
       if (strchr(strb,'*')) {  /* Model includes a product */        cutv(stra, strb,line,' '); 
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/        if(strb[0]=='.') { /* Missing status */
         if (strcmp(strc,"age")==0) { /* Vn*age */          lval=-1;
           cptcovprod--;        }else{
           cutv(strb,stre,strd,'V');          errno=0;
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/          lval=strtol(strb,&endptr,10); 
           cptcovage++;          if( strb[0]=='\0' || (*endptr != '\0')){
             Tage[cptcovage]=i;            printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);
             /*printf("stre=%s ", stre);*/            fprintf(ficlog,"Error reading data around '%d' at line number %ld for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);fflush(ficlog);
         }            goto end;
         else if (strcmp(strd,"age")==0) { /* or age*Vn */          }
           cptcovprod--;        }
           cutv(strb,stre,strc,'V');        if(lval <-1 || lval >1){
           Tvar[i]=atoi(stre);          printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
           cptcovage++;   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
           Tage[cptcovage]=i;   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 \
         else {  /* Age is not in the model */   build V1=0 V2=0 for the reference value (1),\n \
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/          V1=1 V2=0 for (2) \n \
           Tvar[i]=ncovcol+k1;   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */   output of IMaCh is often meaningless.\n \
           Tprod[k1]=i;   Exiting.\n",lval,linei, i,line,j);
           Tvard[k1][1]=atoi(strc); /* m*/          fprintf(ficlog,"Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
           Tvard[k1][2]=atoi(stre); /* n */   Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
           Tvar[cptcovn+k2]=Tvard[k1][1];   for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
           Tvar[cptcovn+k2+1]=Tvard[k1][2];   For example, for multinomial values like 1, 2 and 3,\n \
           for (k=1; k<=lastobs;k++)   build V1=0 V2=0 for the reference value (1),\n \
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];          V1=1 V2=0 for (2) \n \
           k1++;   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
           k2=k2+2;   output of IMaCh is often meaningless.\n \
         }   Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
       }          goto end;
       else { /* no more sum */        }
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/        covar[j][i]=(double)(lval);
        /*  scanf("%d",i);*/        strcpy(line,stra);
       cutv(strd,strc,strb,'V');      }  
       Tvar[i]=atoi(strc);      lstra=strlen(stra);
       }       
       strcpy(modelsav,stra);        if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);        stratrunc = &(stra[lstra-9]);
         scanf("%d",i);*/        num[i]=atol(stratrunc);
     } /* end of loop + */      }
   } /* end model */      else
          num[i]=atol(stra);
   /*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((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/        printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/
       
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);      i=i+1;
   printf("cptcovprod=%d ", cptcovprod);    } /* End loop reading  data */
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);    fclose(fic);
     /* printf("ii=%d", ij);
   scanf("%d ",i);*/       scanf("%d",i);*/
     imx=i-1; /* Number of individuals */
     /*  if(mle==1){*/  
   if (weightopt != 1) { /* Maximisation without weights*/    /* for (i=1; i<=imx; i++){
     for(i=1;i<=n;i++) weight[i]=1.0;      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
   }      if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
     /*-calculation of age at interview from date of interview and age at death -*/      if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
   agev=matrix(1,maxwav,1,imx);      }*/
      /*  for (i=1; i<=imx; i++){
   for (i=1; i<=imx; i++) {       if (s[4][i]==9)  s[4][i]=-1; 
     for(m=2; (m<= maxwav); m++) {       printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){    
         anint[m][i]=9999;    /* for (i=1; i<=imx; i++) */
         s[m][i]=-1;   
       }     /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){       else weight[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);    /* Calculation of the number of parameters from char model */
         fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);    Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. Stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
         s[m][i]=-1;    Tprod=ivector(1,15); 
       }    Tvaraff=ivector(1,15); 
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){    Tvard=imatrix(1,15,1,2);
         nberr++;    Tage=ivector(1,15);      
         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]);    if (strlen(model) >1){ /* If there is at least 1 covariate */
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */      j=0, j1=0, k1=1, k2=1;
       }      j=nbocc(model,'+'); /* j=Number of '+' */
     }      j1=nbocc(model,'*'); /* j1=Number of '*' */
   }      cptcovn=j+1; /* Number of covariates V1+V2+V3 =>2+1=3 */
       cptcovprod=j1; /*Number of products  V1*V2 =1 */
   for (i=1; i<=imx; i++)  {      
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);      strcpy(modelsav,model); 
     for(m=firstpass; (m<= lastpass); m++){      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){        printf("Error. Non available option model=%s ",model);
         if (s[m][i] >= nlstate+1) {        fprintf(ficlog,"Error. Non available option model=%s ",model);fflush(ficlog);
           if(agedc[i]>0)        goto end;
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)      }
               agev[m][i]=agedc[i];      
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/      /* This loop fills the array Tvar from the string 'model'.*/
             else {      /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
               if ((int)andc[i]!=9999){      for(i=(j+1); i>=1;i--){
                 nbwarn++;        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);                                       modelsav=V2+V3*age+V1+V4 strb=V3*age+V1+V4 
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);                                       stra=V2
                 agev[m][i]=-1;                                      */ 
               }        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
             }        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
         }        /*scanf("%d",i);*/
         else if(s[m][i] !=9){ /* Standard case, age in fractional        if (strchr(strb,'*')) {  /* Model includes a product V1+V3*age+V2 strb=V3*age*/
                                  years but with the precision of a month */          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn: V3*age strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);          if (strcmp(strc,"age")==0) { /* Vn*age */
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)            cptcovprod--;
             agev[m][i]=1;            cutv(strb,stre,strd,'V');
           else if(agev[m][i] <agemin){            Tvar[i]=atoi(stre);  /* V1+V3*age+V2 Tvar[2]=3 */
             agemin=agev[m][i];            cptcovage++; /* Sums the number of covariates including age as a product */
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/            Tage[cptcovage]=i;  /* Tage[1] =2 */
           }            /*printf("stre=%s ", stre);*/
           else if(agev[m][i] >agemax){          }
             agemax=agev[m][i];          else if (strcmp(strd,"age")==0) { /* or age*Vn */
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/            cptcovprod--;
           }            cutv(strb,stre,strc,'V');
           /*agev[m][i]=anint[m][i]-annais[i];*/            Tvar[i]=atoi(stre);
           /*     agev[m][i] = age[i]+2*m;*/            cptcovage++;
         }            Tage[cptcovage]=i;
         else { /* =9 */          }
           agev[m][i]=1;          else {  /* Age is not in the model V1+V3*V2+V2  strb=V3*V2*/
           s[m][i]=-1;            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
         }            Tvar[i]=ncovcol+k1;  /* find 'n' in Vn and stores in Tvar. 
       }                                    If already ncovcol=2 and model=V2*V1 Tvar[1]=2+1 and Tvar[2]=2+2 etc */
       else /*= 0 Unknown */            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
         agev[m][i]=1;            Tprod[k1]=i;  /* Tprod[1]  */
     }            Tvard[k1][1]=atoi(strc); /* m*/
                Tvard[k1][2]=atoi(stre); /* n */
   }            Tvar[cptcovn+k2]=Tvard[k1][1];
   for (i=1; i<=imx; i++)  {            Tvar[cptcovn+k2+1]=Tvard[k1][2]; 
     for(m=firstpass; (m<=lastpass); m++){            for (k=1; k<=lastobs;k++) 
       if (s[m][i] > (nlstate+ndeath)) {              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
         nberr++;            k1++;
         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);                k2=k2+2;
         fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);              }
         goto end;        }
       }        else { /* no more sum */
     }          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
   }         /*  scanf("%d",i);*/
         cutv(strd,strc,strb,'V');
   /*for (i=1; i<=imx; i++){        Tvar[i]=atoi(strc);
   for (m=firstpass; (m<lastpass); m++){        }
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);        strcpy(modelsav,stra);  /* modelsav=V2+V3*age+V1+V4 strb=V3*age+V1+V4 */ 
 }        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
           scanf("%d",i);*/
 }*/      } /* end of loop + */
     } /* end model */
     
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);      If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
   
   agegomp=(int)agemin;    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
   free_vector(severity,1,maxwav);    printf("cptcovprod=%d ", cptcovprod);
   free_imatrix(outcome,1,maxwav+1,1,n);    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
   free_vector(moisnais,1,n);  
   free_vector(annais,1,n);    scanf("%d ",i);*/
   /* free_matrix(mint,1,maxwav,1,n);  
      free_matrix(anint,1,maxwav,1,n);*/      /*  if(mle==1){*/
   free_vector(moisdc,1,n);    if (weightopt != 1) { /* Maximisation without weights*/
   free_vector(andc,1,n);      for(i=1;i<=n;i++) weight[i]=1.0;
     }
          /*-calculation of age at interview from date of interview and age at death -*/
   wav=ivector(1,imx);    agev=matrix(1,maxwav,1,imx);
   dh=imatrix(1,lastpass-firstpass+1,1,imx);  
   bh=imatrix(1,lastpass-firstpass+1,1,imx);    for (i=1; i<=imx; i++) {
   mw=imatrix(1,lastpass-firstpass+1,1,imx);      for(m=2; (m<= maxwav); m++) {
            if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
   /* Concatenates waves */          anint[m][i]=9999;
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);          s[m][i]=-1;
         }
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */        if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
           nberr++;
   Tcode=ivector(1,100);          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);
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);          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);
   ncodemax[1]=1;          s[m][i]=-1;
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);        }
              if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of          nberr++;
                                  the estimations*/          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]); 
   h=0;          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]); 
   m=pow(2,cptcoveff);          s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
          }
   for(k=1;k<=cptcoveff; k++){      }
     for(i=1; i <=(m/pow(2,k));i++){    }
       for(j=1; j <= ncodemax[k]; j++){  
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){    for (i=1; i<=imx; i++)  {
           h++;      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;      for(m=firstpass; (m<= lastpass); m++){
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
         }          if (s[m][i] >= nlstate+1) {
       }            if(agedc[i]>0)
     }              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
   }                agev[m][i]=agedc[i];
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
      codtab[1][2]=1;codtab[2][2]=2; */              else {
   /* for(i=1; i <=m ;i++){                if ((int)andc[i]!=9999){
      for(k=1; k <=cptcovn; k++){                  nbwarn++;
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);                  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);
      printf("\n");                  agev[m][i]=-1;
      }                }
      scanf("%d",i);*/              }
              }
   /*------------ gnuplot -------------*/          else if(s[m][i] !=9){ /* Standard case, age in fractional
   strcpy(optionfilegnuplot,optionfilefiname);                                   years but with the precision of a month */
   if(mle==-3)            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
     strcat(optionfilegnuplot,"-mort");            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
   strcat(optionfilegnuplot,".gp");              agev[m][i]=1;
             else if(agev[m][i] <agemin){ 
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {              agemin=agev[m][i];
     printf("Problem with file %s",optionfilegnuplot);              printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);
   }            }
   else{            else if(agev[m][i] >agemax){
     fprintf(ficgp,"\n# %s\n", version);              agemax=agev[m][i];
     fprintf(ficgp,"# %s\n", optionfilegnuplot);              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
     fprintf(ficgp,"set missing 'NaNq'\n");            }
   }            /*agev[m][i]=anint[m][i]-annais[i];*/
   /*  fclose(ficgp);*/            /*     agev[m][i] = age[i]+2*m;*/
   /*--------- index.htm --------*/          }
           else { /* =9 */
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */            agev[m][i]=1;
   if(mle==-3)            s[m][i]=-1;
     strcat(optionfilehtm,"-mort");          }
   strcat(optionfilehtm,".htm");        }
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {        else /*= 0 Unknown */
     printf("Problem with %s \n",optionfilehtm), exit(0);          agev[m][i]=1;
   }      }
       
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */    }
   strcat(optionfilehtmcov,"-cov.htm");    for (i=1; i<=imx; i++)  {
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {      for(m=firstpass; (m<=lastpass); m++){
     printf("Problem with %s \n",optionfilehtmcov), exit(0);        if (s[m][i] > (nlstate+ndeath)) {
   }          nberr++;
   else{          printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);     
   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \          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);     
 <hr size=\"2\" color=\"#EC5E5E\"> \n\          goto end;
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\        }
           optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);      }
   }    }
   
   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \    /*for (i=1; i<=imx; i++){
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    for (m=firstpass; (m<lastpass); m++){
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 \n\  }
 <hr  size=\"2\" color=\"#EC5E5E\">\  
  <ul><li><h4>Parameter files</h4>\n\  }*/
  - 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\    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax); 
  - Date and time at start: %s</ul>\n",\  
           optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\    agegomp=(int)agemin;
           optionfilefiname,optionfilext,optionfilefiname,optionfilext,\    free_vector(severity,1,maxwav);
           fileres,fileres,\    free_imatrix(outcome,1,maxwav+1,1,n);
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);    free_vector(moisnais,1,n);
   fflush(fichtm);    free_vector(annais,1,n);
     /* free_matrix(mint,1,maxwav,1,n);
   strcpy(pathr,path);       free_matrix(anint,1,maxwav,1,n);*/
   strcat(pathr,optionfilefiname);    free_vector(moisdc,1,n);
   chdir(optionfilefiname); /* Move to directory named optionfile */    free_vector(andc,1,n);
    
   /* Calculates basic frequencies. Computes observed prevalence at single age     
      and prints on file fileres'p'. */    wav=ivector(1,imx);
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);    dh=imatrix(1,lastpass-firstpass+1,1,imx);
     bh=imatrix(1,lastpass-firstpass+1,1,imx);
   fprintf(fichtm,"\n");    mw=imatrix(1,lastpass-firstpass+1,1,imx);
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\     
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\    /* Concatenates waves */
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
           imx,agemin,agemax,jmin,jmax,jmean);  
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    ncodemax[1]=1;
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */    if (cptcovn > 0) tricode(Tvar,nbcode,imx);
            
        codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of 
   /* For Powell, parameters are in a vector p[] starting at p[1]                                   the estimations*/
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */    h=0;
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */    m=pow(2,cptcoveff);
    
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/    for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
       for(i=1; i <=(m/pow(2,k));i++){ /* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 */ 
   if (mle==-3){        for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate */
     ximort=matrix(1,NDIM,1,NDIM);          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
     cens=ivector(1,n);            h++;
     ageexmed=vector(1,n);            if (h>m) 
     agecens=vector(1,n);              h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
     dcwave=ivector(1,n);            printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]);
            } 
     for (i=1; i<=imx; i++){        }
       dcwave[i]=-1;      }
       for (m=firstpass; m<=lastpass; m++)    } 
         if (s[m][i]>nlstate) {    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
           dcwave[i]=m;       codtab[1][2]=1;codtab[2][2]=2; */
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/    /* for(i=1; i <=m ;i++){ 
           break;       for(k=1; k <=cptcovn; k++){
         }         printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
     }       }
        printf("\n");
     for (i=1; i<=imx; i++) {       }
       if (wav[i]>0){       scanf("%d",i);*/
         ageexmed[i]=agev[mw[1][i]][i];      
         j=wav[i];    /*------------ gnuplot -------------*/
         agecens[i]=1.;    strcpy(optionfilegnuplot,optionfilefiname);
     if(mle==-3)
         if (ageexmed[i]> 1 && wav[i] > 0){      strcat(optionfilegnuplot,"-mort");
           agecens[i]=agev[mw[j][i]][i];    strcat(optionfilegnuplot,".gp");
           cens[i]= 1;  
         }else if (ageexmed[i]< 1)    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
           cens[i]= -1;      printf("Problem with file %s",optionfilegnuplot);
         if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)    }
           cens[i]=0 ;    else{
       }      fprintf(ficgp,"\n# %s\n", version); 
       else cens[i]=-1;      fprintf(ficgp,"# %s\n", optionfilegnuplot); 
     }      fprintf(ficgp,"set missing 'NaNq'\n");
        }
     for (i=1;i<=NDIM;i++) {    /*  fclose(ficgp);*/
       for (j=1;j<=NDIM;j++)    /*--------- index.htm --------*/
         ximort[i][j]=(i == j ? 1.0 : 0.0);  
     }    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
        if(mle==-3)
     p[1]=0.0268; p[NDIM]=0.083;      strcat(optionfilehtm,"-mort");
     /*printf("%lf %lf", p[1], p[2]);*/    strcat(optionfilehtm,".htm");
        if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
          printf("Problem with %s \n",optionfilehtm);
     printf("Powell\n");  fprintf(ficlog,"Powell\n");      exit(0);
     strcpy(filerespow,"pow-mort");    }
     strcat(filerespow,fileres);  
     if((ficrespow=fopen(filerespow,"w"))==NULL) {    strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
       printf("Problem with resultfile: %s\n", filerespow);    strcat(optionfilehtmcov,"-cov.htm");
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
     }      printf("Problem with %s \n",optionfilehtmcov), exit(0);
     fprintf(ficrespow,"# Powell\n# iter -2*LL");    }
     /*  for (i=1;i<=nlstate;i++)    else{
         for(j=1;j<=nlstate+ndeath;j++)    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);  <hr size=\"2\" color=\"#EC5E5E\"> \n\
     */  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
     fprintf(ficrespow,"\n");            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
        }
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);  
     fclose(ficrespow);    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
      <hr size=\"2\" color=\"#EC5E5E\"> \n\
     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
   \n\
     for(i=1; i <=NDIM; i++)  <hr  size=\"2\" color=\"#EC5E5E\">\
       for(j=i+1;j<=NDIM;j++)   <ul><li><h4>Parameter files</h4>\n\
         matcov[i][j]=matcov[j][i];   - 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\
     printf("\nCovariance matrix\n ");   - Log file of the run: <a href=\"%s\">%s</a><br>\n\
     for(i=1; i <=NDIM; i++) {   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
       for(j=1;j<=NDIM;j++){   - Date and time at start: %s</ul>\n",\
         printf("%f ",matcov[i][j]);            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
       }            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
       printf("\n ");            fileres,fileres,\
     }            filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
        fflush(fichtm);
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);  
     for (i=1;i<=NDIM;i++)    strcpy(pathr,path);
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));    strcat(pathr,optionfilefiname);
     chdir(optionfilefiname); /* Move to directory named optionfile */
     lsurv=vector(1,AGESUP);    
     lpop=vector(1,AGESUP);    /* Calculates basic frequencies. Computes observed prevalence at single age
     tpop=vector(1,AGESUP);       and prints on file fileres'p'. */
     lsurv[agegomp]=100000;    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
      
     for (k=agegomp;k<=AGESUP;k++) {    fprintf(fichtm,"\n");
       agemortsup=k;    fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;  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",\
                imx,agemin,agemax,jmin,jmax,jmean);
     for (k=agegomp;k<agemortsup;k++)    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));      oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
          newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     for (k=agegomp;k<agemortsup;k++){      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
       sumlpop=sumlpop+lpop[k];      
     }     
        /* For Powell, parameters are in a vector p[] starting at p[1]
     tpop[agegomp]=sumlpop;       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
     for (k=agegomp;k<(agemortsup-3);k++){    p=param[1][1]; /* *(*(*(param +1)+1)+0) */
       /*  tpop[k+1]=2;*/  
       tpop[k+1]=tpop[k]-lpop[k];    globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
     }  
        if (mle==-3){
          ximort=matrix(1,NDIM,1,NDIM);
     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");      cens=ivector(1,n);
     for (k=agegomp;k<(agemortsup-2);k++)      ageexmed=vector(1,n);
       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]);      agecens=vector(1,n);
          dcwave=ivector(1,n);
       
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      for (i=1; i<=imx; i++){
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);        dcwave[i]=-1;
            for (m=firstpass; m<=lastpass; m++)
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \          if (s[m][i]>nlstate) {
                      stepm, weightopt,\            dcwave[i]=m;
                      model,imx,p,matcov,agemortsup);            /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                break;
     free_vector(lsurv,1,AGESUP);          }
     free_vector(lpop,1,AGESUP);      }
     free_vector(tpop,1,AGESUP);  
   } /* Endof if mle==-3 */      for (i=1; i<=imx; i++) {
          if (wav[i]>0){
   else{ /* For mle >=1 */          ageexmed[i]=agev[mw[1][i]][i];
            j=wav[i];
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */          agecens[i]=1.; 
     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);  
     for (k=1; k<=npar;k++)          if (ageexmed[i]> 1 && wav[i] > 0){
       printf(" %d %8.5f",k,p[k]);            agecens[i]=agev[mw[j][i]][i];
     printf("\n");            cens[i]= 1;
     globpr=1; /* to print the contributions */          }else if (ageexmed[i]< 1) 
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */            cens[i]= -1;
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);          if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
     for (k=1; k<=npar;k++)            cens[i]=0 ;
       printf(" %d %8.5f",k,p[k]);        }
     printf("\n");        else cens[i]=-1;
     if(mle>=1){ /* Could be 1 or 2 */      }
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);      
     }      for (i=1;i<=NDIM;i++) {
            for (j=1;j<=NDIM;j++)
     /*--------- results files --------------*/          ximort[i][j]=(i == j ? 1.0 : 0.0);
     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);      }
          
          p[1]=0.0268; p[NDIM]=0.083;
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      /*printf("%lf %lf", p[1], p[2]);*/
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      
     for(i=1,jk=1; i <=nlstate; i++){      printf("Powell\n");  fprintf(ficlog,"Powell\n");
       for(k=1; k <=(nlstate+ndeath); k++){      strcpy(filerespow,"pow-mort"); 
         if (k != i) {      strcat(filerespow,fileres);
           printf("%d%d ",i,k);      if((ficrespow=fopen(filerespow,"w"))==NULL) {
           fprintf(ficlog,"%d%d ",i,k);        printf("Problem with resultfile: %s\n", filerespow);
           fprintf(ficres,"%1d%1d ",i,k);        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
           for(j=1; j <=ncovmodel; j++){      }
             printf("%lf ",p[jk]);      fprintf(ficrespow,"# Powell\n# iter -2*LL");
             fprintf(ficlog,"%lf ",p[jk]);      /*  for (i=1;i<=nlstate;i++)
             fprintf(ficres,"%lf ",p[jk]);          for(j=1;j<=nlstate+ndeath;j++)
             jk++;          if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
           }      */
           printf("\n");      fprintf(ficrespow,"\n");
           fprintf(ficlog,"\n");      
           fprintf(ficres,"\n");      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
         }      fclose(ficrespow);
       }      
     }      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
     if(mle!=0){  
       /* Computing hessian and covariance matrix */      for(i=1; i <=NDIM; i++)
       ftolhess=ftol; /* Usually correct */        for(j=i+1;j<=NDIM;j++)
       hesscov(matcov, p, npar, delti, ftolhess, func);          matcov[i][j]=matcov[j][i];
     }      
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");      printf("\nCovariance matrix\n ");
     printf("# Scales (for hessian or gradient estimation)\n");      for(i=1; i <=NDIM; i++) {
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");        for(j=1;j<=NDIM;j++){ 
     for(i=1,jk=1; i <=nlstate; i++){          printf("%f ",matcov[i][j]);
       for(j=1; j <=nlstate+ndeath; j++){        }
         if (j!=i) {        printf("\n ");
           fprintf(ficres,"%1d%1d",i,j);      }
           printf("%1d%1d",i,j);      
           fprintf(ficlog,"%1d%1d",i,j);      printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
           for(k=1; k<=ncovmodel;k++){      for (i=1;i<=NDIM;i++) 
             printf(" %.5e",delti[jk]);        printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
             fprintf(ficlog," %.5e",delti[jk]);  
             fprintf(ficres," %.5e",delti[jk]);      lsurv=vector(1,AGESUP);
             jk++;      lpop=vector(1,AGESUP);
           }      tpop=vector(1,AGESUP);
           printf("\n");      lsurv[agegomp]=100000;
           fprintf(ficlog,"\n");      
           fprintf(ficres,"\n");      for (k=agegomp;k<=AGESUP;k++) {
         }        agemortsup=k;
       }        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
     }      }
          
     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");      for (k=agegomp;k<agemortsup;k++)
     if(mle>=1)        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
       printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");      
     fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");      for (k=agegomp;k<agemortsup;k++){
     /* # 121 Var(a12)\n\ */        lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
     /* # 122 Cov(b12,a12) Var(b12)\n\ */        sumlpop=sumlpop+lpop[k];
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */      }
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */      
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */      tpop[agegomp]=sumlpop;
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */      for (k=agegomp;k<(agemortsup-3);k++){
     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */        /*  tpop[k+1]=2;*/
     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */        tpop[k+1]=tpop[k]-lpop[k];
          }
          
     /* Just to have a covariance matrix which will be more understandable      
        even is we still don't want to manage dictionary of variables      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
     */      for (k=agegomp;k<(agemortsup-2);k++) 
     for(itimes=1;itimes<=2;itimes++){        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]);
       jj=0;      
       for(i=1; i <=nlstate; i++){      
         for(j=1; j <=nlstate+ndeath; j++){      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
           if(j==i) continue;      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
           for(k=1; k<=ncovmodel;k++){      
             jj++;      printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
             ca[0]= k+'a'-1;ca[1]='\0';                       stepm, weightopt,\
             if(itimes==1){                       model,imx,p,matcov,agemortsup);
               if(mle>=1)      
                 printf("#%1d%1d%d",i,j,k);      free_vector(lsurv,1,AGESUP);
               fprintf(ficlog,"#%1d%1d%d",i,j,k);      free_vector(lpop,1,AGESUP);
               fprintf(ficres,"#%1d%1d%d",i,j,k);      free_vector(tpop,1,AGESUP);
             }else{    } /* Endof if mle==-3 */
               if(mle>=1)    
                 printf("%1d%1d%d",i,j,k);    else{ /* For mle >=1 */
               fprintf(ficlog,"%1d%1d%d",i,j,k);      globpr=0;/* debug */
               fprintf(ficres,"%1d%1d%d",i,j,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);
             ll=0;      for (k=1; k<=npar;k++)
             for(li=1;li <=nlstate; li++){        printf(" %d %8.5f",k,p[k]);
               for(lj=1;lj <=nlstate+ndeath; lj++){      printf("\n");
                 if(lj==li) continue;      globpr=1; /* to print the contributions */
                 for(lk=1;lk<=ncovmodel;lk++){      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   ll++;      printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   if(ll<=jj){      for (k=1; k<=npar;k++)
                     cb[0]= lk +'a'-1;cb[1]='\0';        printf(" %d %8.5f",k,p[k]);
                     if(ll<jj){      printf("\n");
                       if(itimes==1){      if(mle>=1){ /* Could be 1 or 2 */
                         if(mle>=1)        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      }
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);      /*--------- results files --------------*/
                       }else{      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);
                         if(mle>=1)      
                           printf(" %.5e",matcov[jj][ll]);      
                         fprintf(ficlog," %.5e",matcov[jj][ll]);      fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                         fprintf(ficres," %.5e",matcov[jj][ll]);      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                       }      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                     }else{      for(i=1,jk=1; i <=nlstate; i++){
                       if(itimes==1){        for(k=1; k <=(nlstate+ndeath); k++){
                         if(mle>=1)          if (k != i) {
                           printf(" Var(%s%1d%1d)",ca,i,j);            printf("%d%d ",i,k);
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);            fprintf(ficlog,"%d%d ",i,k);
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);            fprintf(ficres,"%1d%1d ",i,k);
                       }else{            for(j=1; j <=ncovmodel; j++){
                         if(mle>=1)              printf("%lf ",p[jk]);
                           printf(" %.5e",matcov[jj][ll]);              fprintf(ficlog,"%lf ",p[jk]);
                         fprintf(ficlog," %.5e",matcov[jj][ll]);              fprintf(ficres,"%lf ",p[jk]);
                         fprintf(ficres," %.5e",matcov[jj][ll]);              jk++; 
                       }            }
                     }            printf("\n");
                   }            fprintf(ficlog,"\n");
                 } /* end lk */            fprintf(ficres,"\n");
               } /* end lj */          }
             } /* end li */        }
             if(mle>=1)      }
               printf("\n");      if(mle!=0){
             fprintf(ficlog,"\n");        /* Computing hessian and covariance matrix */
             fprintf(ficres,"\n");        ftolhess=ftol; /* Usually correct */
             numlinepar++;        hesscov(matcov, p, npar, delti, ftolhess, func);
           } /* end k*/      }
         } /*end j */      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
       } /* end i */      printf("# Scales (for hessian or gradient estimation)\n");
     } /* end itimes */      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
          for(i=1,jk=1; i <=nlstate; i++){
     fflush(ficlog);        for(j=1; j <=nlstate+ndeath; j++){
     fflush(ficres);          if (j!=i) {
                fprintf(ficres,"%1d%1d",i,j);
     while((c=getc(ficpar))=='#' && c!= EOF){            printf("%1d%1d",i,j);
       ungetc(c,ficpar);            fprintf(ficlog,"%1d%1d",i,j);
       fgets(line, MAXLINE, ficpar);            for(k=1; k<=ncovmodel;k++){
       puts(line);              printf(" %.5e",delti[jk]);
       fputs(line,ficparo);              fprintf(ficlog," %.5e",delti[jk]);
     }              fprintf(ficres," %.5e",delti[jk]);
     ungetc(c,ficpar);              jk++;
                }
     estepm=0;            printf("\n");
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);            fprintf(ficlog,"\n");
     if (estepm==0 || estepm < stepm) estepm=stepm;            fprintf(ficres,"\n");
     if (fage <= 2) {          }
       bage = ageminpar;        }
       fage = agemaxpar;      }
     }      
          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,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");      if(mle>=1)
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);        printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);      fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
          /* # 121 Var(a12)\n\ */
     while((c=getc(ficpar))=='#' && c!= EOF){      /* # 122 Cov(b12,a12) Var(b12)\n\ */
       ungetc(c,ficpar);      /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
       fgets(line, MAXLINE, ficpar);      /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
       puts(line);      /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
       fputs(line,ficparo);      /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
     }      /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
     ungetc(c,ficpar);      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
          
     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);      
     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);      /* Just to have a covariance matrix which will be more understandable
     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);         even is we still don't want to manage dictionary of variables
     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);      */
     fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);      for(itimes=1;itimes<=2;itimes++){
            jj=0;
     while((c=getc(ficpar))=='#' && c!= EOF){        for(i=1; i <=nlstate; i++){
       ungetc(c,ficpar);          for(j=1; j <=nlstate+ndeath; j++){
       fgets(line, MAXLINE, ficpar);            if(j==i) continue;
       puts(line);            for(k=1; k<=ncovmodel;k++){
       fputs(line,ficparo);              jj++;
     }              ca[0]= k+'a'-1;ca[1]='\0';
     ungetc(c,ficpar);              if(itimes==1){
                    if(mle>=1)
                      printf("#%1d%1d%d",i,j,k);
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;                fprintf(ficlog,"#%1d%1d%d",i,j,k);
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;                fprintf(ficres,"#%1d%1d%d",i,j,k);
                  }else{
     fscanf(ficpar,"pop_based=%d\n",&popbased);                if(mle>=1)
     fprintf(ficparo,"pop_based=%d\n",popbased);                    printf("%1d%1d%d",i,j,k);
     fprintf(ficres,"pop_based=%d\n",popbased);                  fprintf(ficlog,"%1d%1d%d",i,j,k);
                    fprintf(ficres,"%1d%1d%d",i,j,k);
     while((c=getc(ficpar))=='#' && c!= EOF){              }
       ungetc(c,ficpar);              ll=0;
       fgets(line, MAXLINE, ficpar);              for(li=1;li <=nlstate; li++){
       puts(line);                for(lj=1;lj <=nlstate+ndeath; lj++){
       fputs(line,ficparo);                  if(lj==li) continue;
     }                  for(lk=1;lk<=ncovmodel;lk++){
     ungetc(c,ficpar);                    ll++;
                        if(ll<=jj){
     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);                      cb[0]= lk +'a'-1;cb[1]='\0';
     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);                      if(ll<jj){
     printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);                        if(itimes==1){
     fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);                          if(mle>=1)
     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);                            printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
     /* day and month of proj2 are not used but only year anproj2.*/                          fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                              fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                            }else{
                              if(mle>=1)
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/                            printf(" %.5e",matcov[jj][ll]); 
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/                          fprintf(ficlog," %.5e",matcov[jj][ll]); 
                              fprintf(ficres," %.5e",matcov[jj][ll]); 
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */                        }
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);                      }else{
                            if(itimes==1){
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\                          if(mle>=1)
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\                            printf(" Var(%s%1d%1d)",ca,i,j);
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);                          fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                                fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
    /*------------ free_vector  -------------*/                        }else{
    /*  chdir(path); */                          if(mle>=1)
                              printf(" %.5e",matcov[jj][ll]); 
     free_ivector(wav,1,imx);                          fprintf(ficlog," %.5e",matcov[jj][ll]); 
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);                          fprintf(ficres," %.5e",matcov[jj][ll]); 
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);                        }
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);                        }
     free_lvector(num,1,n);                    }
     free_vector(agedc,1,n);                  } /* end lk */
     /*free_matrix(covar,0,NCOVMAX,1,n);*/                } /* end lj */
     /*free_matrix(covar,1,NCOVMAX,1,n);*/              } /* end li */
     fclose(ficparo);              if(mle>=1)
     fclose(ficres);                printf("\n");
               fprintf(ficlog,"\n");
               fprintf(ficres,"\n");
     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/              numlinepar++;
              } /* end k*/
     strcpy(filerespl,"pl");          } /*end j */
     strcat(filerespl,fileres);        } /* end i */
     if((ficrespl=fopen(filerespl,"w"))==NULL) {      } /* end itimes */
       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;      fflush(ficlog);
     }      fflush(ficres);
     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);      
     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);      while((c=getc(ficpar))=='#' && c!= EOF){
     pstamp(ficrespl);        ungetc(c,ficpar);
     fprintf(ficrespl,"# Period (stable) prevalence \n");        fgets(line, MAXLINE, ficpar);
     fprintf(ficrespl,"#Age ");        puts(line);
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);        fputs(line,ficparo);
     fprintf(ficrespl,"\n");      }
        ungetc(c,ficpar);
     prlim=matrix(1,nlstate,1,nlstate);      
       estepm=0;
     agebase=ageminpar;      fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
     agelim=agemaxpar;      if (estepm==0 || estepm < stepm) estepm=stepm;
     ftolpl=1.e-10;      if (fage <= 2) {
     i1=cptcoveff;        bage = ageminpar;
     if (cptcovn < 1){i1=1;}        fage = agemaxpar;
       }
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
         k=k+1;      fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/      fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
         fprintf(ficrespl,"\n#******");      
         printf("\n#******");      while((c=getc(ficpar))=='#' && c!= EOF){
         fprintf(ficlog,"\n#******");        ungetc(c,ficpar);
         for(j=1;j<=cptcoveff;j++) {        fgets(line, MAXLINE, ficpar);
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        puts(line);
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        fputs(line,ficparo);
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      }
         }      ungetc(c,ficpar);
         fprintf(ficrespl,"******\n");      
         printf("******\n");      fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
         fprintf(ficlog,"******\n");      fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
              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);
         for (age=agebase; age<=agelim; age++){      printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);      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(ficrespl,"%.0f ",age );      
           for(j=1;j<=cptcoveff;j++)      while((c=getc(ficpar))=='#' && c!= EOF){
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        ungetc(c,ficpar);
           for(i=1; i<=nlstate;i++)        fgets(line, MAXLINE, ficpar);
             fprintf(ficrespl," %.5f", prlim[i][i]);        puts(line);
           fprintf(ficrespl,"\n");        fputs(line,ficparo);
         }      }
       }      ungetc(c,ficpar);
     }      
     fclose(ficrespl);      
       dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
     /*------------- h Pij x at various ages ------------*/      dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
        
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);      fscanf(ficpar,"pop_based=%d\n",&popbased);
     if((ficrespij=fopen(filerespij,"w"))==NULL) {      fprintf(ficparo,"pop_based=%d\n",popbased);   
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;      fprintf(ficres,"pop_based=%d\n",popbased);   
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;      
     }      while((c=getc(ficpar))=='#' && c!= EOF){
     printf("Computing pij: result on file '%s' \n", filerespij);        ungetc(c,ficpar);
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);        fgets(line, MAXLINE, ficpar);
          puts(line);
     stepsize=(int) (stepm+YEARM-1)/YEARM;        fputs(line,ficparo);
     /*if (stepm<=24) stepsize=2;*/      }
       ungetc(c,ficpar);
     agelim=AGESUP;      
     hstepm=stepsize*YEARM; /* Every year of age */      fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */      fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
       printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
     /* hstepm=1;   aff par mois*/      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);
     pstamp(ficrespij);      fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");      /* day and month of proj2 are not used but only year anproj2.*/
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      
         k=k+1;      
         fprintf(ficrespij,"\n#****** ");      /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
         for(j=1;j<=cptcoveff;j++)      /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      
         fprintf(ficrespij,"******\n");      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
              printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */      
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */      printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */                   model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                    jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
           /*      nhstepm=nhstepm*YEARM; aff par mois*/        
      /*------------ free_vector  -------------*/
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);     /*  chdir(path); */
           oldm=oldms;savm=savms;   
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);        free_ivector(wav,1,imx);
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");      free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
           for(i=1; i<=nlstate;i++)      free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
             for(j=1; j<=nlstate+ndeath;j++)      free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
               fprintf(ficrespij," %1d-%1d",i,j);      free_lvector(num,1,n);
           fprintf(ficrespij,"\n");      free_vector(agedc,1,n);
           for (h=0; h<=nhstepm; h++){      /*free_matrix(covar,0,NCOVMAX,1,n);*/
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );      /*free_matrix(covar,1,NCOVMAX,1,n);*/
             for(i=1; i<=nlstate;i++)      fclose(ficparo);
               for(j=1; j<=nlstate+ndeath;j++)      fclose(ficres);
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);  
             fprintf(ficrespij,"\n");  
           }      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    
           fprintf(ficrespij,"\n");      strcpy(filerespl,"pl");
         }      strcat(filerespl,fileres);
       }      if((ficrespl=fopen(filerespl,"w"))==NULL) {
     }        printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
         fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);      }
       printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
     fclose(ficrespij);      fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
       pstamp(ficrespl);
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);      fprintf(ficrespl,"# Period (stable) prevalence \n");
     for(i=1;i<=AGESUP;i++)      fprintf(ficrespl,"#Age ");
       for(j=1;j<=NCOVMAX;j++)      for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
         for(k=1;k<=NCOVMAX;k++)      fprintf(ficrespl,"\n");
           probs[i][j][k]=0.;    
       prlim=matrix(1,nlstate,1,nlstate);
     /*---------- Forecasting ------------------*/  
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/      agebase=ageminpar;
     if(prevfcast==1){      agelim=agemaxpar;
       /*    if(stepm ==1){*/      ftolpl=1.e-10;
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);      i1=cptcoveff;
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/      if (cptcovn < 1){i1=1;}
       /*      }  */  
       /*      else{ */      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
       /*        erreur=108; */        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
       /*        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); */          k=k+1;
       /*        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); */          /* to clean */
       /*      } */          printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,codtab[cptcod][cptcov],nbcode);
     }          fprintf(ficrespl,"\n#******");
            printf("\n#******");
           fprintf(ficlog,"\n#******");
     /*---------- Health expectancies and variances ------------*/          for(j=1;j<=cptcoveff;j++) {
             fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     strcpy(filerest,"t");            printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     strcat(filerest,fileres);            fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     if((ficrest=fopen(filerest,"w"))==NULL) {          }
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;          fprintf(ficrespl,"******\n");
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;          printf("******\n");
     }          fprintf(ficlog,"******\n");
     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);          
     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);          for (age=agebase; age<=agelim; age++){
             prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
             fprintf(ficrespl,"%.0f ",age );
     strcpy(filerese,"e");            for(j=1;j<=cptcoveff;j++)
     strcat(filerese,fileres);              fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     if((ficreseij=fopen(filerese,"w"))==NULL) {            for(i=1; i<=nlstate;i++)
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);              fprintf(ficrespl," %.5f", prlim[i][i]);
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);            fprintf(ficrespl,"\n");
     }          }
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);        }
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);      }
       fclose(ficrespl);
     strcpy(fileresstde,"stde");  
     strcat(fileresstde,fileres);      /*------------- h Pij x at various ages ------------*/
     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {    
       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);      strcpy(filerespij,"pij");  strcat(filerespij,fileres);
       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);      if((ficrespij=fopen(filerespij,"w"))==NULL) {
     }        printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);        fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);      }
       printf("Computing pij: result on file '%s' \n", filerespij);
     strcpy(filerescve,"cve");      fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
     strcat(filerescve,fileres);    
     if((ficrescveij=fopen(filerescve,"w"))==NULL) {      stepsize=(int) (stepm+YEARM-1)/YEARM;
       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);      /*if (stepm<=24) stepsize=2;*/
       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);  
     }      agelim=AGESUP;
     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      hstepm=stepsize*YEARM; /* Every year of age */
     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
   
     strcpy(fileresv,"v");      /* hstepm=1;   aff par mois*/
     strcat(fileresv,fileres);      pstamp(ficrespij);
     if((ficresvij=fopen(fileresv,"w"))==NULL) {      fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
     }          k=k+1;
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);          fprintf(ficrespij,"\n#****** ");
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);          for(j=1;j<=cptcoveff;j++) 
             fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */          fprintf(ficrespij,"******\n");
     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);          
     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\          for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
     */            nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
   
     if (mobilav!=0) {            /*      nhstepm=nhstepm*YEARM; aff par mois*/
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);            oldm=oldms;savm=savms;
         printf(" Error in movingaverage mobilav=%d\n",mobilav);            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
       }            fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
     }            for(i=1; i<=nlstate;i++)
               for(j=1; j<=nlstate+ndeath;j++)
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){                fprintf(ficrespij," %1d-%1d",i,j);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){            fprintf(ficrespij,"\n");
         k=k+1;            for (h=0; h<=nhstepm; h++){
         fprintf(ficrest,"\n#****** ");              fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
         for(j=1;j<=cptcoveff;j++)              for(i=1; i<=nlstate;i++)
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);                for(j=1; j<=nlstate+ndeath;j++)
         fprintf(ficrest,"******\n");                  fprintf(ficrespij," %.5f", p3mat[i][j][h]);
               fprintf(ficrespij,"\n");
         fprintf(ficreseij,"\n#****** ");            }
         fprintf(ficresstdeij,"\n#****** ");            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
         fprintf(ficrescveij,"\n#****** ");            fprintf(ficrespij,"\n");
         for(j=1;j<=cptcoveff;j++) {          }
           fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);        }
           fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      }
           fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
         }      varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
         fprintf(ficreseij,"******\n");  
         fprintf(ficresstdeij,"******\n");      fclose(ficrespij);
         fprintf(ficrescveij,"******\n");  
       probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
         fprintf(ficresvij,"\n#****** ");      for(i=1;i<=AGESUP;i++)
         for(j=1;j<=cptcoveff;j++)        for(j=1;j<=NCOVMAX;j++)
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          for(k=1;k<=NCOVMAX;k++)
         fprintf(ficresvij,"******\n");            probs[i][j][k]=0.;
   
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);      /*---------- Forecasting ------------------*/
         oldm=oldms;savm=savms;      /*if((stepm == 1) && (strcmp(model,".")==0)){*/
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);        if(prevfcast==1){
         cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);          /*    if(stepm ==1){*/
          prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);        /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
         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);        /*      else{ */
         if(popbased==1){        /*        erreur=108; */
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);        /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
         }        /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
         /*      } */
         pstamp(ficrest);      }
         fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# Age ( e.. (std) ");    
         for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);  
         fprintf(ficrest,"\n");      /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
   
         epj=vector(1,nlstate+1);      prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
         for(age=bage; age <=fage ;age++){      /*  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",\
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);          ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
           if (popbased==1) {      */
             if(mobilav ==0){  
               for(i=1; i<=nlstate;i++)      if (mobilav!=0) {
                 prlim[i][i]=probs[(int)age][i][k];        mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
             }else{ /* mobilav */        if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
               for(i=1; i<=nlstate;i++)          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                 prlim[i][i]=mobaverage[(int)age][i][k];          printf(" Error in movingaverage mobilav=%d\n",mobilav);
             }        }
           }      }
          
           fprintf(ficrest," %4.0f",age);  
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){      /*---------- Health expectancies, no variances ------------*/
             for(i=1, epj[j]=0.;i <=nlstate;i++) {  
               epj[j] += prlim[i][i]*eij[i][j][(int)age];      strcpy(filerese,"e");
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/      strcat(filerese,fileres);
             }      if((ficreseij=fopen(filerese,"w"))==NULL) {
             epj[nlstate+1] +=epj[j];        printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
           }        fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
       }
           for(i=1, vepp=0.;i <=nlstate;i++)      printf("Computing Health Expectancies: result on file '%s' \n", filerese);
             for(j=1;j <=nlstate;j++)      fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
               vepp += vareij[i][j][(int)age];      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           for(j=1;j <=nlstate;j++){          k=k+1; 
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));          fprintf(ficreseij,"\n#****** ");
           }          for(j=1;j<=cptcoveff;j++) {
           fprintf(ficrest,"\n");            fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         }          }
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);          fprintf(ficreseij,"******\n");
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);  
         free_vector(epj,1,nlstate+1);          eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
       }          oldm=oldms;savm=savms;
     }          evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
     free_vector(weight,1,n);        
     free_imatrix(Tvard,1,15,1,2);          free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     free_imatrix(s,1,maxwav+1,1,n);        }
     free_matrix(anint,1,maxwav,1,n);      }
     free_matrix(mint,1,maxwav,1,n);      fclose(ficreseij);
     free_ivector(cod,1,n);  
     free_ivector(tab,1,NCOVMAX);  
     fclose(ficreseij);      /*---------- Health expectancies and variances ------------*/
     fclose(ficresstdeij);  
     fclose(ficrescveij);  
     fclose(ficresvij);      strcpy(filerest,"t");
     fclose(ficrest);      strcat(filerest,fileres);
     fclose(ficpar);      if((ficrest=fopen(filerest,"w"))==NULL) {
          printf("Problem with total LE resultfile: %s\n", filerest);goto end;
     /*------- Variance of period (stable) prevalence------*/          fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
       }
     strcpy(fileresvpl,"vpl");      printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
     strcat(fileresvpl,fileres);      fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {  
       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);  
       exit(0);      strcpy(fileresstde,"stde");
     }      strcat(fileresstde,fileres);
     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);      if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
         printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){        fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      }
         k=k+1;      printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
         fprintf(ficresvpl,"\n#****** ");      fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
         for(j=1;j<=cptcoveff;j++)  
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      strcpy(filerescve,"cve");
         fprintf(ficresvpl,"******\n");      strcat(filerescve,fileres);
            if((ficrescveij=fopen(filerescve,"w"))==NULL) {
         varpl=matrix(1,nlstate,(int) bage, (int) fage);        printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
         oldm=oldms;savm=savms;        fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);      }
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);      printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
       }      fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
     }  
       strcpy(fileresv,"v");
     fclose(ficresvpl);      strcat(fileresv,fileres);
       if((ficresvij=fopen(fileresv,"w"))==NULL) {
     /*---------- End : free ----------------*/        printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);        fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);      }
       printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
   }  /* mle==-3 arrives here for freeing */      fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
   free_matrix(prlim,1,nlstate,1,nlstate);  
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);          k=k+1; 
     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);          fprintf(ficrest,"\n#****** ");
     free_matrix(covar,0,NCOVMAX,1,n);          for(j=1;j<=cptcoveff;j++) 
     free_matrix(matcov,1,npar,1,npar);            fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     /*free_vector(delti,1,npar);*/          fprintf(ficrest,"******\n");
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);  
     free_matrix(agev,1,maxwav,1,imx);          fprintf(ficresstdeij,"\n#****** ");
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);          fprintf(ficrescveij,"\n#****** ");
           for(j=1;j<=cptcoveff;j++) {
     free_ivector(ncodemax,1,8);            fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_ivector(Tvar,1,15);            fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     free_ivector(Tprod,1,15);          }
     free_ivector(Tvaraff,1,15);          fprintf(ficresstdeij,"******\n");
     free_ivector(Tage,1,15);          fprintf(ficrescveij,"******\n");
     free_ivector(Tcode,1,100);  
           fprintf(ficresvij,"\n#****** ");
     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);          for(j=1;j<=cptcoveff;j++) 
     free_imatrix(codtab,1,100,1,10);            fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
   fflush(fichtm);          fprintf(ficresvij,"******\n");
   fflush(ficgp);  
            eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
   if((nberr >0) || (nbwarn>0)){          cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
     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);          vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
   }else{          pstamp(ficrest);
     printf("End of Imach\n");          for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
     fprintf(ficlog,"End of Imach\n");            oldm=oldms;savm=savms;
   }            varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);   fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
   printf("See log file on %s\n",filelog);            if(vpopbased==1)
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */              fprintf(ficrest,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d)\n",mobilav);
   (void) gettimeofday(&end_time,&tzp);            else
   tm = *localtime(&end_time.tv_sec);              fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
   tmg = *gmtime(&end_time.tv_sec);            fprintf(ficrest,"# Age e.. (std) ");
   strcpy(strtend,asctime(&tm));            for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);            fprintf(ficrest,"\n");
   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));            epj=vector(1,nlstate+1);
             for(age=bage; age <=fage ;age++){
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);              prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));              if (vpopbased==1) {
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);                if(mobilav ==0){
   /*  printf("Total time was %d uSec.\n", total_usecs);*/                  for(i=1; i<=nlstate;i++)
 /*   if(fileappend(fichtm,optionfilehtm)){ */                    prlim[i][i]=probs[(int)age][i][k];
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);                }else{ /* mobilav */ 
   fclose(fichtm);                  for(i=1; i<=nlstate;i++)
   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);                    prlim[i][i]=mobaverage[(int)age][i][k];
   fclose(fichtmcov);                }
   fclose(ficgp);              }
   fclose(ficlog);          
   /*------ End -----------*/              fprintf(ficrest," %4.0f",age);
               for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                 for(i=1, epj[j]=0.;i <=nlstate;i++) {
    printf("Before Current directory %s!\n",pathcd);                  epj[j] += prlim[i][i]*eij[i][j][(int)age];
    if(chdir(pathcd) != 0)                  /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
     printf("Can't move to directory %s!\n",path);                }
   if(getcwd(pathcd,MAXLINE) > 0)                epj[nlstate+1] +=epj[j];
     printf("Current directory %s!\n",pathcd);              }
   /*strcat(plotcmd,CHARSEPARATOR);*/  
   sprintf(plotcmd,"gnuplot");              for(i=1, vepp=0.;i <=nlstate;i++)
 #ifndef UNIX                for(j=1;j <=nlstate;j++)
   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);                  vepp += vareij[i][j][(int)age];
 #endif              fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
   if(!stat(plotcmd,&info)){              for(j=1;j <=nlstate;j++){
     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);                fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
     if(!stat(getenv("GNUPLOTBIN"),&info)){              }
       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);              fprintf(ficrest,"\n");
     }else            }
       strcpy(pplotcmd,plotcmd);          }
 #ifdef UNIX          free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     strcpy(plotcmd,GNUPLOTPROGRAM);          free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     if(!stat(plotcmd,&info)){          free_vector(epj,1,nlstate+1);
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);        }
     }else      }
       strcpy(pplotcmd,plotcmd);      free_vector(weight,1,n);
 #endif      free_imatrix(Tvard,1,15,1,2);
   }else      free_imatrix(s,1,maxwav+1,1,n);
     strcpy(pplotcmd,plotcmd);      free_matrix(anint,1,maxwav,1,n); 
        free_matrix(mint,1,maxwav,1,n);
   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);      free_ivector(cod,1,n);
   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);      free_ivector(tab,1,NCOVMAX);
       fclose(ficresstdeij);
   if((outcmd=system(plotcmd)) != 0){      fclose(ficrescveij);
     printf("\n Problem with gnuplot\n");      fclose(ficresvij);
   }      fclose(ficrest);
   printf(" Wait...");      fclose(ficpar);
   while (z[0] != 'q') {    
     /* chdir(path); */      /*------- Variance of period (stable) prevalence------*/   
     printf("\nType e to edit output files, g to graph again and q for exiting: ");  
     scanf("%s",z);      strcpy(fileresvpl,"vpl");
 /*     if (z[0] == 'c') system("./imach"); */      strcat(fileresvpl,fileres);
     if (z[0] == 'e') {      if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);        printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
       system(optionfilehtm);        exit(0);
     }      }
     else if (z[0] == 'g') system(plotcmd);      printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
     else if (z[0] == 'q') exit(0);  
   }      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
   end:        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
   while (z[0] != 'q') {          k=k+1;
     printf("\nType  q for exiting: ");          fprintf(ficresvpl,"\n#****** ");
     scanf("%s",z);          for(j=1;j<=cptcoveff;j++) 
   }            fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 }          fprintf(ficresvpl,"******\n");
         
           varpl=matrix(1,nlstate,(int) bage, (int) fage);
           oldm=oldms;savm=savms;
           varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
           free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
         }
       }
   
       fclose(ficresvpl);
   
       /*---------- End : free ----------------*/
       if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
   
     }  /* mle==-3 arrives here for freeing */
    endfree:
     free_matrix(prlim,1,nlstate,1,nlstate);
       free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(covar,0,NCOVMAX,1,n);
       free_matrix(matcov,1,npar,1,npar);
       /*free_vector(delti,1,npar);*/
       free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
       free_matrix(agev,1,maxwav,1,imx);
       free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
   
       free_ivector(ncodemax,1,8);
       free_ivector(Tvar,1,15);
       free_ivector(Tprod,1,15);
       free_ivector(Tvaraff,1,15);
       free_ivector(Tage,1,15);
   
       free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
       free_imatrix(codtab,1,100,1,10);
     fflush(fichtm);
     fflush(ficgp);
     
   
     if((nberr >0) || (nbwarn>0)){
       printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
       fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
     }else{
       printf("End of Imach\n");
       fprintf(ficlog,"End of Imach\n");
     }
     printf("See log file on %s\n",filelog);
     /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
     (void) gettimeofday(&end_time,&tzp);
     tm = *localtime(&end_time.tv_sec);
     tmg = *gmtime(&end_time.tv_sec);
     strcpy(strtend,asctime(&tm));
     printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
     fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
     printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
   
     printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
     /*  printf("Total time was %d uSec.\n", total_usecs);*/
   /*   if(fileappend(fichtm,optionfilehtm)){ */
     fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     fclose(fichtm);
     fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
     fclose(fichtmcov);
     fclose(ficgp);
     fclose(ficlog);
     /*------ End -----------*/
   
   
      printf("Before Current directory %s!\n",pathcd);
      if(chdir(pathcd) != 0)
       printf("Can't move to directory %s!\n",path);
     if(getcwd(pathcd,MAXLINE) > 0)
       printf("Current directory %s!\n",pathcd);
     /*strcat(plotcmd,CHARSEPARATOR);*/
     sprintf(plotcmd,"gnuplot");
   #ifndef UNIX
     sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
   #endif
     if(!stat(plotcmd,&info)){
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       if(!stat(getenv("GNUPLOTBIN"),&info)){
         printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #ifdef UNIX
       strcpy(plotcmd,GNUPLOTPROGRAM);
       if(!stat(plotcmd,&info)){
         printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
       }else
         strcpy(pplotcmd,plotcmd);
   #endif
     }else
       strcpy(pplotcmd,plotcmd);
     
     sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
     printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
   
     if((outcmd=system(plotcmd)) != 0){
       printf("\n Problem with gnuplot\n");
     }
     printf(" Wait...");
     while (z[0] != 'q') {
       /* chdir(path); */
       printf("\nType e to edit output files, g to graph again and q for exiting: ");
       scanf("%s",z);
   /*     if (z[0] == 'c') system("./imach"); */
       if (z[0] == 'e') {
         printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
         system(optionfilehtm);
       }
       else if (z[0] == 'g') system(plotcmd);
       else if (z[0] == 'q') exit(0);
     }
     end:
     while (z[0] != 'q') {
       printf("\nType  q for exiting: ");
       scanf("%s",z);
     }
   }
   
   
   

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


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