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

version 1.123, 2006/03/20 10:52:43 version 1.125, 2006/04/04 15:20:31
Line 1 Line 1
 /* $Id$  /* $Id$
   $State$    $State$
   $Log$    $Log$
   Revision 1.123  2006/03/20 10:52:43  brouard    Revision 1.125  2006/04/04 15:20:31  lievre
   * imach.c (Module): <title> changed, corresponds to .htm file    Errors in calculation of health expectancies. Age was not initialized.
   name. <head> headers where missing.    Forecasting file added.
   
   * imach.c (Module): Weights can have a decimal point as for    Revision 1.124  2006/03/22 17:13:53  lievre
   English (a comma might work with a correct LC_NUMERIC environment,    Parameters are printed with %lf instead of %f (more numbers after the comma).
   otherwise the weight is truncated).    The log-likelihood is printed in the log file
   Modification of warning when the covariates values are not 0 or  
   1.    Revision 1.123  2006/03/20 10:52:43  brouard
   Version 0.98g    * imach.c (Module): <title> changed, corresponds to .htm file
     name. <head> headers where missing.
   Revision 1.122  2006/03/20 09:45:41  brouard  
   (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.121  2006/03/16 17:45:01  lievre    Revision 1.122  2006/03/20 09:45:41  brouard
   * imach.c (Module): Comments concerning covariates added    (Module): Weights can have a decimal point as for
     English (a comma might work with a correct LC_NUMERIC environment,
   * imach.c (Module): refinements in the computation of lli if    otherwise the weight is truncated).
   status=-2 in order to have more reliable computation if stepm is    Modification of warning when the covariates values are not 0 or
   not 1 month. Version 0.98f    1.
     Version 0.98g
   Revision 1.120  2006/03/16 15:10:38  lievre  
   (Module): refinements in the computation of lli if    Revision 1.121  2006/03/16 17:45:01  lievre
   status=-2 in order to have more reliable computation if stepm is    * imach.c (Module): Comments concerning covariates added
   not 1 month. Version 0.98f  
     * imach.c (Module): refinements in the computation of lli if
   Revision 1.119  2006/03/15 17:42:26  brouard    status=-2 in order to have more reliable computation if stepm is
   (Module): Bug if status = -2, the loglikelihood was    not 1 month. Version 0.98f
   computed as likelihood omitting the logarithm. Version O.98e  
     Revision 1.120  2006/03/16 15:10:38  lievre
   Revision 1.118  2006/03/14 18:20:07  brouard    (Module): refinements in the computation of lli if
   (Module): varevsij Comments added explaining the second    status=-2 in order to have more reliable computation if stepm is
   table of variances if popbased=1 .    not 1 month. Version 0.98f
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.  
   (Module): Function pstamp added    Revision 1.119  2006/03/15 17:42:26  brouard
   (Module): Version 0.98d    (Module): Bug if status = -2, the loglikelihood was
     computed as likelihood omitting the logarithm. Version O.98e
   Revision 1.117  2006/03/14 17:16:22  brouard  
   (Module): varevsij Comments added explaining the second    Revision 1.118  2006/03/14 18:20:07  brouard
   table of variances if popbased=1 .    (Module): varevsij Comments added explaining the second
   (Module): Covariances of eij, ekl added, graphs fixed, new html link.    table of variances if popbased=1 .
   (Module): Function pstamp added    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   (Module): Version 0.98d    (Module): Function pstamp added
     (Module): Version 0.98d
   Revision 1.116  2006/03/06 10:29:27  brouard  
   (Module): Variance-covariance wrong links and    Revision 1.117  2006/03/14 17:16:22  brouard
   varian-covariance of ej. is needed (Saito).    (Module): varevsij Comments added explaining the second
     table of variances if popbased=1 .
   Revision 1.115  2006/02/27 12:17:45  brouard    (Module): Covariances of eij, ekl added, graphs fixed, new html link.
   (Module): One freematrix added in mlikeli! 0.98c    (Module): Function pstamp added
     (Module): Version 0.98d
   Revision 1.114  2006/02/26 12:57:58  brouard  
   (Module): Some improvements in processing parameter    Revision 1.116  2006/03/06 10:29:27  brouard
   filename with strsep.    (Module): Variance-covariance wrong links and
     varian-covariance of ej. is needed (Saito).
   Revision 1.113  2006/02/24 14:20:24  brouard  
   (Module): Memory leaks checks with valgrind and:    Revision 1.115  2006/02/27 12:17:45  brouard
   datafile was not closed, some imatrix were not freed and on matrix    (Module): One freematrix added in mlikeli! 0.98c
   allocation too.  
     Revision 1.114  2006/02/26 12:57:58  brouard
   Revision 1.112  2006/01/30 09:55:26  brouard    (Module): Some improvements in processing parameter
   (Module): Back to gnuplot.exe instead of wgnuplot.exe    filename with strsep.
   
   Revision 1.111  2006/01/25 20:38:18  brouard    Revision 1.113  2006/02/24 14:20:24  brouard
   (Module): Lots of cleaning and bugs added (Gompertz)    (Module): Memory leaks checks with valgrind and:
   (Module): Comments can be added in data file. Missing date values    datafile was not closed, some imatrix were not freed and on matrix
   can be a simple dot '.'.    allocation too.
   
   Revision 1.110  2006/01/25 00:51:50  brouard    Revision 1.112  2006/01/30 09:55:26  brouard
   (Module): Lots of cleaning and bugs added (Gompertz)    (Module): Back to gnuplot.exe instead of wgnuplot.exe
   
   Revision 1.109  2006/01/24 19:37:15  brouard    Revision 1.111  2006/01/25 20:38:18  brouard
   (Module): Comments (lines starting with a #) are allowed in data.    (Module): Lots of cleaning and bugs added (Gompertz)
     (Module): Comments can be added in data file. Missing date values
   Revision 1.108  2006/01/19 18:05:42  lievre    can be a simple dot '.'.
   Gnuplot problem appeared...  
   To be fixed    Revision 1.110  2006/01/25 00:51:50  brouard
     (Module): Lots of cleaning and bugs added (Gompertz)
   Revision 1.107  2006/01/19 16:20:37  brouard  
   Test existence of gnuplot in imach path    Revision 1.109  2006/01/24 19:37:15  brouard
     (Module): Comments (lines starting with a #) are allowed in data.
   Revision 1.106  2006/01/19 13:24:36  brouard  
   Some cleaning and links added in html output    Revision 1.108  2006/01/19 18:05:42  lievre
     Gnuplot problem appeared...
   Revision 1.105  2006/01/05 20:23:19  lievre    To be fixed
   *** empty log message ***  
     Revision 1.107  2006/01/19 16:20:37  brouard
   Revision 1.104  2005/09/30 16:11:43  lievre    Test existence of gnuplot in imach path
   (Module): sump fixed, loop imx fixed, and simplifications.  
   (Module): If the status is missing at the last wave but we know    Revision 1.106  2006/01/19 13:24:36  brouard
   that the person is alive, then we can code his/her status as -2    Some cleaning and links added in html output
   (instead of missing=-1 in earlier versions) and his/her  
   contributions to the likelihood is 1 - Prob of dying from last    Revision 1.105  2006/01/05 20:23:19  lievre
   health status (= 1-p13= p11+p12 in the easiest case of somebody in    *** empty log message ***
   the healthy state at last known wave). Version is 0.98  
     Revision 1.104  2005/09/30 16:11:43  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.    (Module): If the status is missing at the last wave but we know
     that the person is alive, then we can code his/her status as -2
   Revision 1.102  2004/09/15 17:31:30  brouard    (instead of missing=-1 in earlier versions) and his/her
   Add the possibility to read data file including tab characters.    contributions to the likelihood is 1 - Prob of dying from last
     health status (= 1-p13= p11+p12 in the easiest case of somebody in
   Revision 1.101  2004/09/15 10:38:38  brouard    the healthy state at last known wave). Version is 0.98
   Fix on curr_time  
     Revision 1.103  2005/09/30 15:54:49  lievre
   Revision 1.100  2004/07/12 18:29:06  brouard    (Module): sump fixed, loop imx fixed, and simplifications.
   Add version for Mac OS X. Just define UNIX in Makefile  
     Revision 1.102  2004/09/15 17:31:30  brouard
   Revision 1.99  2004/06/05 08:57:40  brouard    Add the possibility to read data file including tab characters.
   *** empty log message ***  
     Revision 1.101  2004/09/15 10:38:38  brouard
   Revision 1.98  2004/05/16 15:05:56  brouard    Fix on curr_time
   New version 0.97 . First attempt to estimate force of mortality  
   directly from the data i.e. without the need of knowing the health    Revision 1.100  2004/07/12 18:29:06  brouard
   state at each age, but using a Gompertz model: log u =a + b*age .    Add version for Mac OS X. Just define UNIX in Makefile
   This is the basic analysis of mortality and should be done before any  
   other analysis, in order to test if the mortality estimated from the    Revision 1.99  2004/06/05 08:57:40  brouard
   cross-longitudinal survey is different from the mortality estimated    *** empty log message ***
   from other sources like vital statistic data.  
     Revision 1.98  2004/05/16 15:05:56  brouard
   The same imach parameter file can be used but the option for mle should be -3.    New version 0.97 . First attempt to estimate force of mortality
     directly from the data i.e. without the need of knowing the health
   Agnès, who wrote this part of the code, tried to keep most of the    state at each age, but using a Gompertz model: log u =a + b*age .
   former routines in order to include the new code within the former code.    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
   The output is very simple: only an estimate of the intercept and of    cross-longitudinal survey is different from the mortality estimated
   the slope with 95% confident intervals.    from other sources like vital statistic data.
   
   Current limitations:    The same imach parameter file can be used but the option for mle should be -3.
   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.    Agnès, who wrote this part of the code, tried to keep most of the
   B) There is no computation of Life Expectancy nor Life Table.    former routines in order to include the new code within the former code.
   
   Revision 1.97  2004/02/20 13:25:42  lievre    The output is very simple: only an estimate of the intercept and of
   Version 0.96d. Population forecasting command line is (temporarily)    the slope with 95% confident intervals.
   suppressed.  
     Current limitations:
   Revision 1.96  2003/07/15 15:38:55  brouard    A) Even if you enter covariates, i.e. with the
   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is    model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
   rewritten within the same printf. Workaround: many printfs.    B) There is no computation of Life Expectancy nor Life Table.
   
   Revision 1.95  2003/07/08 07:54:34  brouard    Revision 1.97  2004/02/20 13:25:42  lievre
   * imach.c (Repository):    Version 0.96d. Population forecasting command line is (temporarily)
   (Repository): Using imachwizard code to output a more meaningful covariance    suppressed.
   matrix (cov(a12,c31) instead of numbers.  
     Revision 1.96  2003/07/15 15:38:55  brouard
   Revision 1.94  2003/06/27 13:00:02  brouard    * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
   Just cleaning    rewritten within the same printf. Workaround: many printfs.
   
   Revision 1.93  2003/06/25 16:33:55  brouard    Revision 1.95  2003/07/08 07:54:34  brouard
   (Module): On windows (cygwin) function asctime_r doesn't    * imach.c (Repository):
   exist so I changed back to asctime which exists.    (Repository): Using imachwizard code to output a more meaningful covariance
   (Module): Version 0.96b    matrix (cov(a12,c31) instead of numbers.
   
   Revision 1.92  2003/06/25 16:30:45  brouard    Revision 1.94  2003/06/27 13:00:02  brouard
   (Module): On windows (cygwin) function asctime_r doesn't    Just cleaning
   exist so I changed back to asctime which exists.  
     Revision 1.93  2003/06/25 16:33:55  brouard
   Revision 1.91  2003/06/25 15:30:29  brouard    (Module): On windows (cygwin) function asctime_r doesn't
   * imach.c (Repository): Duplicated warning errors corrected.    exist so I changed back to asctime which exists.
   (Repository): Elapsed time after each iteration is now output. It    (Module): Version 0.96b
   helps to forecast when convergence will be reached. Elapsed time  
   is stamped in powell.  We created a new html file for the graphs    Revision 1.92  2003/06/25 16:30:45  brouard
   concerning matrix of covariance. It has extension -cov.htm.    (Module): On windows (cygwin) function asctime_r doesn't
     exist so I changed back to asctime which exists.
   Revision 1.90  2003/06/24 12:34:15  brouard  
   (Module): Some bugs corrected for windows. Also, when    Revision 1.91  2003/06/25 15:30:29  brouard
   mle=-1 a template is output in file "or"mypar.txt with the design    * imach.c (Repository): Duplicated warning errors corrected.
   of the covariance matrix to be input.    (Repository): Elapsed time after each iteration is now output. It
     helps to forecast when convergence will be reached. Elapsed time
   Revision 1.89  2003/06/24 12:30:52  brouard    is stamped in powell.  We created a new html file for the graphs
   (Module): Some bugs corrected for windows. Also, when    concerning matrix of covariance. It has extension -cov.htm.
   mle=-1 a template is output in file "or"mypar.txt with the design  
   of the covariance matrix to be input.    Revision 1.90  2003/06/24 12:34:15  brouard
     (Module): Some bugs corrected for windows. Also, when
   Revision 1.88  2003/06/23 17:54:56  brouard    mle=-1 a template is output in file "or"mypar.txt with the design
   * 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.    of the covariance matrix to be input.
   
   Revision 1.87  2003/06/18 12:26:01  brouard    Revision 1.89  2003/06/24 12:30:52  brouard
   Version 0.96    (Module): Some bugs corrected for windows. Also, when
     mle=-1 a template is output in file "or"mypar.txt with the design
   Revision 1.86  2003/06/17 20:04:08  brouard    of the covariance matrix to be input.
   (Module): Change position of html and gnuplot routines and added  
   routine fileappend.    Revision 1.88  2003/06/23 17:54:56  brouard
     * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.
   Revision 1.85  2003/06/17 13:12:43  brouard  
   * imach.c (Repository): Check when date of death was earlier that    Revision 1.87  2003/06/18 12:26:01  brouard
   current date of interview. It may happen when the death was just    Version 0.96
   prior to the death. In this case, dh was negative and likelihood  
   was wrong (infinity). We still send an "Error" but patch by    Revision 1.86  2003/06/17 20:04:08  brouard
   assuming that the date of death was just one stepm after the    (Module): Change position of html and gnuplot routines and added
   interview.    routine fileappend.
   (Repository): Because some people have very long ID (first column)  
   we changed int to long in num[] and we added a new lvector for    Revision 1.85  2003/06/17 13:12:43  brouard
   memory allocation. But we also truncated to 8 characters (left    * imach.c (Repository): Check when date of death was earlier that
   truncation)    current date of interview. It may happen when the death was just
   (Repository): No more line truncation errors.    prior to the death. In this case, dh was negative and likelihood
     was wrong (infinity). We still send an "Error" but patch by
   Revision 1.84  2003/06/13 21:44:43  brouard    assuming that the date of death was just one stepm after the
   * imach.c (Repository): Replace "freqsummary" at a correct    interview.
   place. It differs from routine "prevalence" which may be called    (Repository): Because some people have very long ID (first column)
   many times. Probs is memory consuming and must be used with    we changed int to long in num[] and we added a new lvector for
   parcimony.    memory allocation. But we also truncated to 8 characters (left
   Version 0.95a3 (should output exactly the same maximization than 0.8a2)    truncation)
     (Repository): No more line truncation errors.
   Revision 1.83  2003/06/10 13:39:11  lievre  
   *** empty log message ***    Revision 1.84  2003/06/13 21:44:43  brouard
     * imach.c (Repository): Replace "freqsummary" at a correct
   Revision 1.82  2003/06/05 15:57:20  brouard    place. It differs from routine "prevalence" which may be called
   Add log in  imach.c and  fullversion number is now printed.    many times. Probs is memory consuming and must be used with
     parcimony.
 */    Version 0.95a3 (should output exactly the same maximization than 0.8a2)
 /*  
    Interpolated Markov Chain    Revision 1.83  2003/06/10 13:39:11  lievre
     *** empty log message ***
   Short summary of the programme:  
       Revision 1.82  2003/06/05 15:57:20  brouard
   This program computes Healthy Life Expectancies from    Add log in  imach.c and  fullversion number is now printed.
   cross-longitudinal data. Cross-longitudinal data consist in: -1- a  
   first survey ("cross") where individuals from different ages are  */
   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     Interpolated Markov Chain
   second wave of interviews ("longitudinal") which measure each change  
   (if any) in individual health status.  Health expectancies are    Short summary of the programme:
   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    This program computes Healthy Life Expectancies from
   Maximum Likelihood of the parameters involved in the model.  The    cross-longitudinal data. Cross-longitudinal data consist in: -1- a
   simplest model is the multinomial logistic model where pij is the    first survey ("cross") where individuals from different ages are
   probability to be observed in state j at the second wave    interviewed on their health status or degree of disability (in the
   conditional to be observed in state i at the first wave. Therefore    case of a health survey which is our main interest) -2- at least a
   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where    second wave of interviews ("longitudinal") which measure each change
   'age' is age and 'sex' is a covariate. If you want to have a more    (if any) in individual health status.  Health expectancies are
   complex model than "constant and age", you should modify the program    computed from the time spent in each health state according to a
   where the markup *Covariates have to be included here again* invites    model. More health states you consider, more time is necessary to reach the
   you to do it.  More covariates you add, slower the    Maximum Likelihood of the parameters involved in the model.  The
   convergence.    simplest model is the multinomial logistic model where pij is the
     probability to be observed in state j at the second wave
   The advantage of this computer programme, compared to a simple    conditional to be observed in state i at the first wave. Therefore
   multinomial logistic model, is clear when the delay between waves is not    the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
   identical for each individual. Also, if a individual missed an    'age' is age and 'sex' is a covariate. If you want to have a more
   intermediate interview, the information is lost, but taken into    complex model than "constant and age", you should modify the program
   account using an interpolation or extrapolation.      where the markup *Covariates have to be included here again* invites
     you to do it.  More covariates you add, slower the
   hPijx is the probability to be observed in state i at age x+h    convergence.
   conditional to the observed state i at age x. The delay 'h' can be  
   split into an exact number (nh*stepm) of unobserved intermediate    The advantage of this computer programme, compared to a simple
   states. This elementary transition (by month, quarter,    multinomial logistic model, is clear when the delay between waves is not
   semester or year) is modelled as a multinomial logistic.  The hPx    identical for each individual. Also, if a individual missed an
   matrix is simply the matrix product of nh*stepm elementary matrices    intermediate interview, the information is lost, but taken into
   and the contribution of each individual to the likelihood is simply    account using an interpolation or extrapolation.  
   hPijx.  
     hPijx is the probability to be observed in state i at age x+h
   Also this programme outputs the covariance matrix of the parameters but also    conditional to the observed state i at age x. The delay 'h' can be
   of the life expectancies. It also computes the period (stable) prevalence.     split into an exact number (nh*stepm) of unobserved intermediate
       states. This elementary transition (by month, quarter,
   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).    semester or year) is modelled as a multinomial logistic.  The hPx
            Institut national d'études démographiques, Paris.    matrix is simply the matrix product of nh*stepm elementary matrices
   This software have been partly granted by Euro-REVES, a concerted action    and the contribution of each individual to the likelihood is simply
   from the European Union.    hPijx.
   It is copyrighted identically to a GNU software product, ie programme and  
   software can be distributed freely for non commercial use. Latest version    Also this programme outputs the covariance matrix of the parameters but also
   can be accessed at http://euroreves.ined.fr/imach .    of the life expectancies. It also computes the period (stable) prevalence.
    
   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach    Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so             Institut national d'études démographiques, Paris.
       This software have been partly granted by Euro-REVES, a concerted action
   **********************************************************************/    from the European Union.
 /*    It is copyrighted identically to a GNU software product, ie programme and
   main    software can be distributed freely for non commercial use. Latest version
   read parameterfile    can be accessed at http://euroreves.ined.fr/imach .
   read datafile  
   concatwav    Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
   freqsummary    or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
   if (mle >= 1)   
     mlikeli    **********************************************************************/
   print results files  /*
   if mle==1     main
      computes hessian    read parameterfile
   read end of parameter file: agemin, agemax, bage, fage, estepm    read datafile
       begin-prev-date,...    concatwav
   open gnuplot file    freqsummary
   open html file    if (mle >= 1)
   period (stable) prevalence      mlikeli
    for age prevalim()    print results files
   h Pij x    if mle==1
   variance of p varprob       computes hessian
   forecasting if prevfcast==1 prevforecast call prevalence()    read end of parameter file: agemin, agemax, bage, fage, estepm
   health expectancies        begin-prev-date,...
   Variance-covariance of DFLE    open gnuplot file
   prevalence()    open html file
    movingaverage()    period (stable) prevalence
   varevsij()      for age prevalim()
   if popbased==1 varevsij(,popbased)    h Pij x
   total life expectancies    variance of p varprob
   Variance of period (stable) prevalence    forecasting if prevfcast==1 prevforecast call prevalence()
  end    health expectancies
 */    Variance-covariance of DFLE
     prevalence()
      movingaverage()
     varevsij()
      if popbased==1 varevsij(,popbased)
 #include <math.h>    total life expectancies
 #include <stdio.h>    Variance of period (stable) prevalence
 #include <stdlib.h>   end
 #include <string.h>  */
 #include <unistd.h>  
   
 #include <limits.h>  
 #include <sys/types.h>   
 #include <sys/stat.h>  #include <math.h>
 #include <errno.h>  #include <stdio.h>
 extern int errno;  #include <stdlib.h>
   #include <string.h>
 /* #include <sys/time.h> */  #include <unistd.h>
 #include <time.h>  
 #include "timeval.h"  #include <limits.h>
   #include <sys/types.h>
 /* #include <libintl.h> */  #include <sys/stat.h>
 /* #define _(String) gettext (String) */  #include <errno.h>
   extern int errno;
 #define MAXLINE 256  
   /* #include <sys/time.h> */
 #define GNUPLOTPROGRAM "gnuplot"  #include <time.h>
 /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/  #include "timeval.h"
 #define FILENAMELENGTH 132  
   /* #include <libintl.h> */
 #define GLOCK_ERROR_NOPATH              -1      /* empty path */  /* #define _(String) gettext (String) */
 #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */  
   #define MAXLINE 256
 #define MAXPARM 30 /* Maximum number of parameters for the optimization */  
 #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */  #define GNUPLOTPROGRAM "gnuplot"
   /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 #define NINTERVMAX 8  #define FILENAMELENGTH 132
 #define NLSTATEMAX 8 /* Maximum number of live states (for func) */  
 #define NDEATHMAX 8 /* Maximum number of dead states (for func) */  #define GLOCK_ERROR_NOPATH              -1      /* empty path */
 #define NCOVMAX 8 /* Maximum number of covariates */  #define GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
 #define MAXN 20000  
 #define YEARM 12. /* Number of months per year */  #define MAXPARM 30 /* Maximum number of parameters for the optimization */
 #define AGESUP 130  #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
 #define AGEBASE 40  
 #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */  #define NINTERVMAX 8
 #ifdef UNIX  #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
 #define DIRSEPARATOR '/'  #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
 #define CHARSEPARATOR "/"  #define NCOVMAX 8 /* Maximum number of covariates */
 #define ODIRSEPARATOR '\\'  #define MAXN 20000
 #else  #define YEARM 12. /* Number of months per year */
 #define DIRSEPARATOR '\\'  #define AGESUP 130
 #define CHARSEPARATOR "\\"  #define AGEBASE 40
 #define ODIRSEPARATOR '/'  #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
 #endif  #ifdef UNIX
   #define DIRSEPARATOR '/'
 /* $Id$ */  #define CHARSEPARATOR "/"
 /* $State$ */  #define ODIRSEPARATOR '\\'
   #else
 char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";  #define DIRSEPARATOR '\\'
 char fullversion[]="$Revision$ $Date$";   #define CHARSEPARATOR "\\"
 char strstart[80];  #define ODIRSEPARATOR '/'
 char optionfilext[10], optionfilefiname[FILENAMELENGTH];  #endif
 int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */  
 int nvar;  /* $Id$ */
 int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;  /* $State$ */
 int npar=NPARMAX;  
 int nlstate=2; /* Number of live states */  char version[]="Imach version 0.98g, March 2006, INED-EUROREVES-Institut de longevite ";
 int ndeath=1; /* Number of dead states */  char fullversion[]="$Revision$ $Date$";
 int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */  char strstart[80];
 int popbased=0;  char optionfilext[10], optionfilefiname[FILENAMELENGTH];
   int erreur, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 int *wav; /* Number of waves for this individuual 0 is possible */  int nvar;
 int maxwav; /* Maxim number of waves */  int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov;
 int jmin, jmax; /* min, max spacing between 2 waves */  int npar=NPARMAX;
 int ijmin, ijmax; /* Individuals having jmin and jmax */   int nlstate=2; /* Number of live states */
 int gipmx, gsw; /* Global variables on the number of contributions   int ndeath=1; /* Number of dead states */
                    to the likelihood and the sum of weights (done by funcone)*/  int ncovmodel, ncovcol;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 int mle, weightopt;  int popbased=0;
 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 *wav; /* Number of waves for this individuual 0 is possible */
 int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between  int maxwav; /* Maxim number of waves */
            * wave mi and wave mi+1 is not an exact multiple of stepm. */  int jmin, jmax; /* min, max spacing between 2 waves */
 double jmean; /* Mean space between 2 waves */  int ijmin, ijmax; /* Individuals having jmin and jmax */
 double **oldm, **newm, **savm; /* Working pointers to matrices */  int gipmx, gsw; /* Global variables on the number of contributions
 double **oldms, **newms, **savms; /* Fixed working pointers to matrices */                     to the likelihood and the sum of weights (done by funcone)*/
 FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;  int mle, weightopt;
 FILE *ficlog, *ficrespow;  int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 int globpr; /* Global variable for printing or not */  int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 double fretone; /* Only one call to likelihood */  int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
 long ipmx; /* Number of contributions */             * wave mi and wave mi+1 is not an exact multiple of stepm. */
 double sw; /* Sum of weights */  double jmean; /* Mean space between 2 waves */
 char filerespow[FILENAMELENGTH];  double **oldm, **newm, **savm; /* Working pointers to matrices */
 char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */  double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 FILE *ficresilk;  FILE *fic,*ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
 FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;  FILE *ficlog, *ficrespow;
 FILE *ficresprobmorprev;  int globpr; /* Global variable for printing or not */
 FILE *fichtm, *fichtmcov; /* Html File */  double fretone; /* Only one call to likelihood */
 FILE *ficreseij;  long ipmx; /* Number of contributions */
 char filerese[FILENAMELENGTH];  double sw; /* Sum of weights */
 FILE *ficresstdeij;  char filerespow[FILENAMELENGTH];
 char fileresstde[FILENAMELENGTH];  char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 FILE *ficrescveij;  FILE *ficresilk;
 char filerescve[FILENAMELENGTH];  FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 FILE  *ficresvij;  FILE *ficresprobmorprev;
 char fileresv[FILENAMELENGTH];  FILE *fichtm, *fichtmcov; /* Html File */
 FILE  *ficresvpl;  FILE *ficreseij;
 char fileresvpl[FILENAMELENGTH];  char filerese[FILENAMELENGTH];
 char title[MAXLINE];  FILE *ficresstdeij;
 char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];  char fileresstde[FILENAMELENGTH];
 char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];  FILE *ficrescveij;
 char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];   char filerescve[FILENAMELENGTH];
 char command[FILENAMELENGTH];  FILE  *ficresvij;
 int  outcmd=0;  char fileresv[FILENAMELENGTH];
   FILE  *ficresvpl;
 char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];  char fileresvpl[FILENAMELENGTH];
   char title[MAXLINE];
 char filelog[FILENAMELENGTH]; /* Log file */  char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
 char filerest[FILENAMELENGTH];  char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 char fileregp[FILENAMELENGTH];  char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH];
 char popfile[FILENAMELENGTH];  char command[FILENAMELENGTH];
   int  outcmd=0;
 char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;  
   char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
 struct timeval start_time, end_time, curr_time, last_time, forecast_time;  
 struct timezone tzp;  char filelog[FILENAMELENGTH]; /* Log file */
 extern int gettimeofday();  char filerest[FILENAMELENGTH];
 struct tm tmg, tm, tmf, *gmtime(), *localtime();  char fileregp[FILENAMELENGTH];
 long time_value;  char popfile[FILENAMELENGTH];
 extern long time();  
 char strcurr[80], strfor[80];  char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
   
 char *endptr;  struct timeval start_time, end_time, curr_time, last_time, forecast_time;
 long lval;  struct timezone tzp;
 double dval;  extern int gettimeofday();
   struct tm tmg, tm, tmf, *gmtime(), *localtime();
 #define NR_END 1  long time_value;
 #define FREE_ARG char*  extern long time();
 #define FTOL 1.0e-10  char strcurr[80], strfor[80];
   
 #define NRANSI   char *endptr;
 #define ITMAX 200   long lval;
   double dval;
 #define TOL 2.0e-4   
   #define NR_END 1
 #define CGOLD 0.3819660   #define FREE_ARG char*
 #define ZEPS 1.0e-10   #define FTOL 1.0e-10
 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);   
   #define NRANSI
 #define GOLD 1.618034   #define ITMAX 200
 #define GLIMIT 100.0   
 #define TINY 1.0e-20   #define TOL 2.0e-4
   
 static double maxarg1,maxarg2;  #define CGOLD 0.3819660
 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))  #define ZEPS 1.0e-10
 #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))  #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
     
 #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))  #define GOLD 1.618034
 #define rint(a) floor(a+0.5)  #define GLIMIT 100.0
   #define TINY 1.0e-20
 static double sqrarg;  
 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)  static double maxarg1,maxarg2;
 #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}   #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 int agegomp= AGEGOMP;  #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
    
 int imx;   #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 int stepm=1;  #define rint(a) floor(a+0.5)
 /* Stepm, step in month: minimum step interpolation*/  
   static double sqrarg;
 int estepm;  #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/  #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
   int agegomp= AGEGOMP;
 int m,nb;  
 long *num;  int imx;
 int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;  int stepm=1;
 double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;  /* Stepm, step in month: minimum step interpolation*/
 double **pmmij, ***probs;  
 double *ageexmed,*agecens;  int estepm;
 double dateintmean=0;  /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
   
 double *weight;  int m,nb;
 int **s; /* Status */  long *num;
 double *agedc, **covar, idx;  int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
 int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;  double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 double *lsurv, *lpop, *tpop;  double **pmmij, ***probs;
   double *ageexmed,*agecens;
 double ftol=FTOL; /* Tolerance for computing Max Likelihood */  double dateintmean=0;
 double ftolhess; /* Tolerance for computing hessian */  
   double *weight;
 /**************** split *************************/  int **s; /* Status */
 static  int split( char *path, char *dirc, char *name, char *ext, char *finame )  double *agedc, **covar, idx;
 {  int **nbcode, *Tcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)  double *lsurv, *lpop, *tpop;
      the name of the file (name), its extension only (ext) and its first part of the name (finame)  
   */   double ftol=FTOL; /* Tolerance for computing Max Likelihood */
   char  *ss;                            /* pointer */  double ftolhess; /* Tolerance for computing hessian */
   int   l1, l2;                         /* length counters */  
   /**************** split *************************/
   l1 = strlen(path );                   /* length of path */  static  int split( char *path, char *dirc, char *name, char *ext, char *finame )
   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );  {
   ss= strrchr( path, DIRSEPARATOR );            /* find last / */    /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
   if ( ss == NULL ) {                   /* no directory, so determine current directory */       the name of the file (name), its extension only (ext) and its first part of the name (finame)
     strcpy( name, path );               /* we got the fullname name because no directory */    */
     /*if(strrchr(path, ODIRSEPARATOR )==NULL)    char  *ss;                            /* pointer */
       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/    int   l1, l2;                         /* length counters */
     /* get current working directory */  
     /*    extern  char* getcwd ( char *buf , int len);*/    l1 = strlen(path );                   /* length of path */
     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {    if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
       return( GLOCK_ERROR_GETCWD );    ss= strrchr( path, DIRSEPARATOR );            /* find last / */
     }    if ( ss == NULL ) {                   /* no directory, so determine current directory */
     /* got dirc from getcwd*/      strcpy( name, path );               /* we got the fullname name because no directory */
     printf(" DIRC = %s \n",dirc);      /*if(strrchr(path, ODIRSEPARATOR )==NULL)
   } else {                              /* strip direcotry from path */        printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
     ss++;                               /* after this, the filename */      /* get current working directory */
     l2 = strlen( ss );                  /* length of filename */      /*    extern  char* getcwd ( char *buf , int len);*/
     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );      if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
     strcpy( name, ss );         /* save file name */        return( GLOCK_ERROR_GETCWD );
     strncpy( dirc, path, l1 - l2 );     /* now the directory */      }
     dirc[l1-l2] = 0;                    /* add zero */      /* got dirc from getcwd*/
     printf(" DIRC2 = %s \n",dirc);      printf(" DIRC = %s \n",dirc);
   }    } else {                              /* strip direcotry from path */
   /* We add a separator at the end of dirc if not exists */      ss++;                               /* after this, the filename */
   l1 = strlen( dirc );                  /* length of directory */      l2 = strlen( ss );                  /* length of filename */
   if( dirc[l1-1] != DIRSEPARATOR ){      if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
     dirc[l1] =  DIRSEPARATOR;      strcpy( name, ss );         /* save file name */
     dirc[l1+1] = 0;       strncpy( dirc, path, l1 - l2 );     /* now the directory */
     printf(" DIRC3 = %s \n",dirc);      dirc[l1-l2] = 0;                    /* add zero */
   }      printf(" DIRC2 = %s \n",dirc);
   ss = strrchr( name, '.' );            /* find last / */    }
   if (ss >0){    /* We add a separator at the end of dirc if not exists */
     ss++;    l1 = strlen( dirc );                  /* length of directory */
     strcpy(ext,ss);                     /* save extension */    if( dirc[l1-1] != DIRSEPARATOR ){
     l1= strlen( name);      dirc[l1] =  DIRSEPARATOR;
     l2= strlen(ss)+1;      dirc[l1+1] = 0;
     strncpy( finame, name, l1-l2);      printf(" DIRC3 = %s \n",dirc);
     finame[l1-l2]= 0;    }
   }    ss = strrchr( name, '.' );            /* find last / */
     if (ss >0){
   return( 0 );                          /* we're done */      ss++;
 }      strcpy(ext,ss);                     /* save extension */
       l1= strlen( name);
       l2= strlen(ss)+1;
 /******************************************/      strncpy( finame, name, l1-l2);
       finame[l1-l2]= 0;
 void replace_back_to_slash(char *s, char*t)    }
 {  
   int i;    return( 0 );                          /* we're done */
   int lg=0;  }
   i=0;  
   lg=strlen(t);  
   for(i=0; i<= lg; i++) {  /******************************************/
     (s[i] = t[i]);  
     if (t[i]== '\\') s[i]='/';  void replace_back_to_slash(char *s, char*t)
   }  {
 }    int i;
     int lg=0;
 int nbocc(char *s, char occ)    i=0;
 {    lg=strlen(t);
   int i,j=0;    for(i=0; i<= lg; i++) {
   int lg=20;      (s[i] = t[i]);
   i=0;      if (t[i]== '\\') s[i]='/';
   lg=strlen(s);    }
   for(i=0; i<= lg; i++) {  }
   if  (s[i] == occ ) j++;  
   }  int nbocc(char *s, char occ)
   return j;  {
 }    int i,j=0;
     int lg=20;
 void cutv(char *u,char *v, char*t, char occ)    i=0;
 {    lg=strlen(s);
   /* cuts string t into u and v where u ends before first occurence of char 'occ'     for(i=0; i<= lg; i++) {
      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')    if  (s[i] == occ ) j++;
      gives u="abcedf" and v="ghi2j" */    }
   int i,lg,j,p=0;    return j;
   i=0;  }
   for(j=0; j<=strlen(t)-1; j++) {  
     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;  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'
   lg=strlen(t);       and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
   for(j=0; j<p; j++) {       gives u="abcedf" and v="ghi2j" */
     (u[j] = t[j]);    int i,lg,j,p=0;
   }    i=0;
      u[p]='\0';    for(j=0; j<=strlen(t)-1; j++) {
       if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
    for(j=0; j<= lg; j++) {    }
     if (j>=(p+1))(v[j-p-1] = t[j]);  
   }    lg=strlen(t);
 }    for(j=0; j<p; j++) {
       (u[j] = t[j]);
 /********************** nrerror ********************/    }
        u[p]='\0';
 void nrerror(char error_text[])  
 {     for(j=0; j<= lg; j++) {
   fprintf(stderr,"ERREUR ...\n");      if (j>=(p+1))(v[j-p-1] = t[j]);
   fprintf(stderr,"%s\n",error_text);    }
   exit(EXIT_FAILURE);  }
 }  
 /*********************** vector *******************/  /********************** nrerror ********************/
 double *vector(int nl, int nh)  
 {  void nrerror(char error_text[])
   double *v;  {
   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));    fprintf(stderr,"ERREUR ...\n");
   if (!v) nrerror("allocation failure in vector");    fprintf(stderr,"%s\n",error_text);
   return v-nl+NR_END;    exit(EXIT_FAILURE);
 }  }
   /*********************** vector *******************/
 /************************ free vector ******************/  double *vector(int nl, int nh)
 void free_vector(double*v, int nl, int nh)  {
 {    double *v;
   free((FREE_ARG)(v+nl-NR_END));    v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 }    if (!v) nrerror("allocation failure in vector");
     return v-nl+NR_END;
 /************************ivector *******************************/  }
 int *ivector(long nl,long nh)  
 {  /************************ free vector ******************/
   int *v;  void free_vector(double*v, int nl, int nh)
   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));  {
   if (!v) nrerror("allocation failure in ivector");    free((FREE_ARG)(v+nl-NR_END));
   return v-nl+NR_END;  }
 }  
   /************************ivector *******************************/
 /******************free ivector **************************/  int *ivector(long nl,long nh)
 void free_ivector(int *v, long nl, long nh)  {
 {    int *v;
   free((FREE_ARG)(v+nl-NR_END));    v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 }    if (!v) nrerror("allocation failure in ivector");
     return v-nl+NR_END;
 /************************lvector *******************************/  }
 long *lvector(long nl,long nh)  
 {  /******************free ivector **************************/
   long *v;  void free_ivector(int *v, long nl, long nh)
   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));  {
   if (!v) nrerror("allocation failure in ivector");    free((FREE_ARG)(v+nl-NR_END));
   return v-nl+NR_END;  }
 }  
   /************************lvector *******************************/
 /******************free lvector **************************/  long *lvector(long nl,long nh)
 void free_lvector(long *v, long nl, long nh)  {
 {    long *v;
   free((FREE_ARG)(v+nl-NR_END));    v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 }    if (!v) nrerror("allocation failure in ivector");
     return v-nl+NR_END;
 /******************* imatrix *******************************/  }
 int **imatrix(long nrl, long nrh, long ncl, long nch)   
      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */   /******************free lvector **************************/
 {   void free_lvector(long *v, long nl, long nh)
   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;   {
   int **m;     free((FREE_ARG)(v+nl-NR_END));
     }
   /* allocate pointers to rows */   
   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));   /******************* imatrix *******************************/
   if (!m) nrerror("allocation failure 1 in matrix()");   int **imatrix(long nrl, long nrh, long ncl, long nch)
   m += NR_END;        /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
   m -= nrl;   {
       long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
       int **m;
   /* allocate rows and set pointers to them */    
   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));     /* allocate pointers to rows */
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");     m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
   m[nrl] += NR_END;     if (!m) nrerror("allocation failure 1 in matrix()");
   m[nrl] -= ncl;     m += NR_END;
       m -= nrl;
   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;    
      
   /* return pointer to array of pointers to rows */     /* allocate rows and set pointers to them */
   return m;     m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
 }     if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     m[nrl] += NR_END;
 /****************** free_imatrix *************************/    m[nrl] -= ncl;
 void free_imatrix(m,nrl,nrh,ncl,nch)   
       int **m;    for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
       long nch,ncl,nrh,nrl;    
      /* free an int matrix allocated by imatrix() */     /* return pointer to array of pointers to rows */
 {     return m;
   free((FREE_ARG) (m[nrl]+ncl-NR_END));   }
   free((FREE_ARG) (m+nrl-NR_END));   
 }   /****************** free_imatrix *************************/
   void free_imatrix(m,nrl,nrh,ncl,nch)
 /******************* matrix *******************************/        int **m;
 double **matrix(long nrl, long nrh, long ncl, long nch)        long nch,ncl,nrh,nrl;
 {       /* free an int matrix allocated by imatrix() */
   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;  {
   double **m;    free((FREE_ARG) (m[nrl]+ncl-NR_END));
     free((FREE_ARG) (m+nrl-NR_END));
   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  }
   if (!m) nrerror("allocation failure 1 in matrix()");  
   m += NR_END;  /******************* matrix *******************************/
   m -= nrl;  double **matrix(long nrl, long nrh, long ncl, long nch)
   {
   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));    long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    double **m;
   m[nrl] += NR_END;  
   m[nrl] -= ncl;    m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
     if (!m) nrerror("allocation failure 1 in matrix()");
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    m += NR_END;
   return m;    m -= nrl;
   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])   
    */    m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 }    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
     m[nrl] += NR_END;
 /*************************free matrix ************************/    m[nrl] -= ncl;
 void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)  
 {    for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   free((FREE_ARG)(m[nrl]+ncl-NR_END));    return m;
   free((FREE_ARG)(m+nrl-NR_END));    /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1])
 }     */
   }
 /******************* ma3x *******************************/  
 double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)  /*************************free matrix ************************/
 {  void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;  {
   double ***m;    free((FREE_ARG)(m[nrl]+ncl-NR_END));
     free((FREE_ARG)(m+nrl-NR_END));
   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));  }
   if (!m) nrerror("allocation failure 1 in matrix()");  
   m += NR_END;  /******************* ma3x *******************************/
   m -= nrl;  double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
   {
   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));    long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");    double ***m;
   m[nrl] += NR_END;  
   m[nrl] -= ncl;    m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
     if (!m) nrerror("allocation failure 1 in matrix()");
   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;    m += NR_END;
     m -= nrl;
   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]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
   m[nrl][ncl] += NR_END;    if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
   m[nrl][ncl] -= nll;    m[nrl] += NR_END;
   for (j=ncl+1; j<=nch; j++)     m[nrl] -= ncl;
     m[nrl][j]=m[nrl][j-1]+nlay;  
       for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
   for (i=nrl+1; i<=nrh; i++) {  
     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;    m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
     for (j=ncl+1; j<=nch; j++)     if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
       m[i][j]=m[i][j-1]+nlay;    m[nrl][ncl] += NR_END;
   }    m[nrl][ncl] -= nll;
   return m;     for (j=ncl+1; j<=nch; j++)
   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])      m[nrl][j]=m[nrl][j-1]+nlay;
            &(m[i][j][k]) <=> *((*(m+i) + j)+k)   
   */    for (i=nrl+1; i<=nrh; i++) {
 }      m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
       for (j=ncl+1; j<=nch; j++)
 /*************************free ma3x ************************/        m[i][j]=m[i][j-1]+nlay;
 void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)    }
 {    return m;
   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));    /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
   free((FREE_ARG)(m[nrl]+ncl-NR_END));             &(m[i][j][k]) <=> *((*(m+i) + j)+k)
   free((FREE_ARG)(m+nrl-NR_END));    */
 }  }
   
 /*************** function subdirf ***********/  /*************************free ma3x ************************/
 char *subdirf(char fileres[])  void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 {  {
   /* Caution optionfilefiname is hidden */    free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
   strcpy(tmpout,optionfilefiname);    free((FREE_ARG)(m[nrl]+ncl-NR_END));
   strcat(tmpout,"/"); /* Add to the right */    free((FREE_ARG)(m+nrl-NR_END));
   strcat(tmpout,fileres);  }
   return tmpout;  
 }  /*************** function subdirf ***********/
   char *subdirf(char fileres[])
 /*************** function subdirf2 ***********/  {
 char *subdirf2(char fileres[], char *preop)    /* Caution optionfilefiname is hidden */
 {    strcpy(tmpout,optionfilefiname);
       strcat(tmpout,"/"); /* Add to the right */
   /* Caution optionfilefiname is hidden */    strcat(tmpout,fileres);
   strcpy(tmpout,optionfilefiname);    return tmpout;
   strcat(tmpout,"/");  }
   strcat(tmpout,preop);  
   strcat(tmpout,fileres);  /*************** function subdirf2 ***********/
   return tmpout;  char *subdirf2(char fileres[], char *preop)
 }  {
    
 /*************** function subdirf3 ***********/    /* Caution optionfilefiname is hidden */
 char *subdirf3(char fileres[], char *preop, char *preop2)    strcpy(tmpout,optionfilefiname);
 {    strcat(tmpout,"/");
       strcat(tmpout,preop);
   /* Caution optionfilefiname is hidden */    strcat(tmpout,fileres);
   strcpy(tmpout,optionfilefiname);    return tmpout;
   strcat(tmpout,"/");  }
   strcat(tmpout,preop);  
   strcat(tmpout,preop2);  /*************** function subdirf3 ***********/
   strcat(tmpout,fileres);  char *subdirf3(char fileres[], char *preop, char *preop2)
   return tmpout;  {
 }   
     /* Caution optionfilefiname is hidden */
 /***************** f1dim *************************/    strcpy(tmpout,optionfilefiname);
 extern int ncom;     strcat(tmpout,"/");
 extern double *pcom,*xicom;    strcat(tmpout,preop);
 extern double (*nrfunc)(double []);     strcat(tmpout,preop2);
      strcat(tmpout,fileres);
 double f1dim(double x)     return tmpout;
 {   }
   int j;   
   double f;  /***************** f1dim *************************/
   double *xt;   extern int ncom;
    extern double *pcom,*xicom;
   xt=vector(1,ncom);   extern double (*nrfunc)(double []);
   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];    
   f=(*nrfunc)(xt);   double f1dim(double x)
   free_vector(xt,1,ncom);   {
   return f;     int j;
 }     double f;
     double *xt;
 /*****************brent *************************/   
 double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)     xt=vector(1,ncom);
 {     for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
   int iter;     f=(*nrfunc)(xt);
   double a,b,d,etemp;    free_vector(xt,1,ncom);
   double fu,fv,fw,fx;    return f;
   double ftemp;  }
   double p,q,r,tol1,tol2,u,v,w,x,xm;   
   double e=0.0;   /*****************brent *************************/
    double brent(double ax, double bx, double cx, double (*f)(double), double tol,  double *xmin)
   a=(ax < cx ? ax : cx);   {
   b=(ax > cx ? ax : cx);     int iter;
   x=w=v=bx;     double a,b,d,etemp;
   fw=fv=fx=(*f)(x);     double fu,fv,fw,fx;
   for (iter=1;iter<=ITMAX;iter++) {     double ftemp;
     xm=0.5*(a+b);     double p,q,r,tol1,tol2,u,v,w,x,xm;
     tol2=2.0*(tol1=tol*fabs(x)+ZEPS);     double e=0.0;
     /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/   
     printf(".");fflush(stdout);    a=(ax < cx ? ax : cx);
     fprintf(ficlog,".");fflush(ficlog);    b=(ax > cx ? ax : cx);
 #ifdef DEBUG    x=w=v=bx;
     printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);    fw=fv=fx=(*f)(x);
     fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);    for (iter=1;iter<=ITMAX;iter++) {
     /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */      xm=0.5*(a+b);
 #endif      tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
     if (fabs(x-xm) <= (tol2-0.5*(b-a))){       /*          if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
       *xmin=x;       printf(".");fflush(stdout);
       return fx;       fprintf(ficlog,".");fflush(ficlog);
     }   #ifdef DEBUG
     ftemp=fu;      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);
     if (fabs(e) > tol1) {       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);
       r=(x-w)*(fx-fv);       /*          if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
       q=(x-v)*(fx-fw);   #endif
       p=(x-v)*q-(x-w)*r;       if (fabs(x-xm) <= (tol2-0.5*(b-a))){
       q=2.0*(q-r);         *xmin=x;
       if (q > 0.0) p = -p;         return fx;
       q=fabs(q);       }
       etemp=e;       ftemp=fu;
       e=d;       if (fabs(e) > tol1) {
       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))         r=(x-w)*(fx-fv);
         d=CGOLD*(e=(x >= xm ? a-x : b-x));         q=(x-v)*(fx-fw);
       else {         p=(x-v)*q-(x-w)*r;
         d=p/q;         q=2.0*(q-r);
         u=x+d;         if (q > 0.0) p = -p;
         if (u-a < tol2 || b-u < tol2)         q=fabs(q);
           d=SIGN(tol1,xm-x);         etemp=e;
       }         e=d;
     } else {         if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
       d=CGOLD*(e=(x >= xm ? a-x : b-x));           d=CGOLD*(e=(x >= xm ? a-x : b-x));
     }         else {
     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));           d=p/q;
     fu=(*f)(u);           u=x+d;
     if (fu <= fx) {           if (u-a < tol2 || b-u < tol2)
       if (u >= x) a=x; else b=x;             d=SIGN(tol1,xm-x);
       SHFT(v,w,x,u)         }
         SHFT(fv,fw,fx,fu)       } else {
         } else {         d=CGOLD*(e=(x >= xm ? a-x : b-x));
           if (u < x) a=u; else b=u;       }
           if (fu <= fw || w == x) {       u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
             v=w;       fu=(*f)(u);
             w=u;       if (fu <= fx) {
             fv=fw;         if (u >= x) a=x; else b=x;
             fw=fu;         SHFT(v,w,x,u)
           } else if (fu <= fv || v == x || v == w) {           SHFT(fv,fw,fx,fu)
             v=u;           } else {
             fv=fu;             if (u < x) a=u; else b=u;
           }             if (fu <= fw || w == x) {
         }               v=w;
   }               w=u;
   nrerror("Too many iterations in brent");               fv=fw;
   *xmin=x;               fw=fu;
   return fx;             } else if (fu <= fv || v == x || v == w) {
 }               v=u;
               fv=fu;
 /****************** mnbrak ***********************/            }
           }
 void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,     }
             double (*func)(double))     nrerror("Too many iterations in brent");
 {     *xmin=x;
   double ulim,u,r,q, dum;    return fx;
   double fu;   }
    
   *fa=(*func)(*ax);   /****************** mnbrak ***********************/
   *fb=(*func)(*bx);   
   if (*fb > *fa) {   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
     SHFT(dum,*ax,*bx,dum)               double (*func)(double))
       SHFT(dum,*fb,*fa,dum)   {
       }     double ulim,u,r,q, dum;
   *cx=(*bx)+GOLD*(*bx-*ax);     double fu;
   *fc=(*func)(*cx);    
   while (*fb > *fc) {     *fa=(*func)(*ax);
     r=(*bx-*ax)*(*fb-*fc);     *fb=(*func)(*bx);
     q=(*bx-*cx)*(*fb-*fa);     if (*fb > *fa) {
     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/       SHFT(dum,*ax,*bx,dum)
       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));         SHFT(dum,*fb,*fa,dum)
     ulim=(*bx)+GLIMIT*(*cx-*bx);         }
     if ((*bx-u)*(u-*cx) > 0.0) {     *cx=(*bx)+GOLD*(*bx-*ax);
       fu=(*func)(u);     *fc=(*func)(*cx);
     } else if ((*cx-u)*(u-ulim) > 0.0) {     while (*fb > *fc) {
       fu=(*func)(u);       r=(*bx-*ax)*(*fb-*fc);
       if (fu < *fc) {       q=(*bx-*cx)*(*fb-*fa);
         SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))       u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
           SHFT(*fb,*fc,fu,(*func)(u))         (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
           }       ulim=(*bx)+GLIMIT*(*cx-*bx);
     } else if ((u-ulim)*(ulim-*cx) >= 0.0) {       if ((*bx-u)*(u-*cx) > 0.0) {
       u=ulim;         fu=(*func)(u);
       fu=(*func)(u);       } else if ((*cx-u)*(u-ulim) > 0.0) {
     } else {         fu=(*func)(u);
       u=(*cx)+GOLD*(*cx-*bx);         if (fu < *fc) {
       fu=(*func)(u);           SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
     }             SHFT(*fb,*fc,fu,(*func)(u))
     SHFT(*ax,*bx,*cx,u)             }
       SHFT(*fa,*fb,*fc,fu)       } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
       }         u=ulim;
 }         fu=(*func)(u);
       } else {
 /*************** linmin ************************/        u=(*cx)+GOLD*(*cx-*bx);
         fu=(*func)(u);
 int ncom;       }
 double *pcom,*xicom;      SHFT(*ax,*bx,*cx,u)
 double (*nrfunc)(double []);         SHFT(*fa,*fb,*fc,fu)
          }
 void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))   }
 {   
   double brent(double ax, double bx, double cx,   /*************** linmin ************************/
                double (*f)(double), double tol, double *xmin);   
   double f1dim(double x);   int ncom;
   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,   double *pcom,*xicom;
               double *fc, double (*func)(double));   double (*nrfunc)(double []);
   int j;    
   double xx,xmin,bx,ax;   void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
   double fx,fb,fa;  {
      double brent(double ax, double bx, double cx,
   ncom=n;                  double (*f)(double), double tol, double *xmin);
   pcom=vector(1,n);     double f1dim(double x);
   xicom=vector(1,n);     void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
   nrfunc=func;                 double *fc, double (*func)(double));
   for (j=1;j<=n;j++) {     int j;
     pcom[j]=p[j];     double xx,xmin,bx,ax;
     xicom[j]=xi[j];     double fx,fb,fa;
   }    
   ax=0.0;     ncom=n;
   xx=1.0;     pcom=vector(1,n);
   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);     xicom=vector(1,n);
   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);     nrfunc=func;
 #ifdef DEBUG    for (j=1;j<=n;j++) {
   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);      pcom[j]=p[j];
   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);      xicom[j]=xi[j];
 #endif    }
   for (j=1;j<=n;j++) {     ax=0.0;
     xi[j] *= xmin;     xx=1.0;
     p[j] += xi[j];     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
   }     *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
   free_vector(xicom,1,n);   #ifdef DEBUG
   free_vector(pcom,1,n);     printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 }     fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
   #endif
 char *asc_diff_time(long time_sec, char ascdiff[])    for (j=1;j<=n;j++) {
 {      xi[j] *= xmin;
   long sec_left, days, hours, minutes;      p[j] += xi[j];
   days = (time_sec) / (60*60*24);    }
   sec_left = (time_sec) % (60*60*24);    free_vector(xicom,1,n);
   hours = (sec_left) / (60*60) ;    free_vector(pcom,1,n);
   sec_left = (sec_left) %(60*60);  }
   minutes = (sec_left) /60;  
   sec_left = (sec_left) % (60);  char *asc_diff_time(long time_sec, char ascdiff[])
   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);    {
   return ascdiff;    long sec_left, days, hours, minutes;
 }    days = (time_sec) / (60*60*24);
     sec_left = (time_sec) % (60*60*24);
 /*************** powell ************************/    hours = (sec_left) / (60*60) ;
 void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,     sec_left = (sec_left) %(60*60);
             double (*func)(double []))     minutes = (sec_left) /60;
 {     sec_left = (sec_left) % (60);
   void linmin(double p[], double xi[], int n, double *fret,     sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
               double (*func)(double []));     return ascdiff;
   int i,ibig,j;   }
   double del,t,*pt,*ptt,*xit;  
   double fp,fptt;  /*************** powell ************************/
   double *xits;  void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
   int niterf, itmp;              double (*func)(double []))
   {
   pt=vector(1,n);     void linmin(double p[], double xi[], int n, double *fret,
   ptt=vector(1,n);                 double (*func)(double []));
   xit=vector(1,n);     int i,ibig,j;
   xits=vector(1,n);     double del,t,*pt,*ptt,*xit;
   *fret=(*func)(p);     double fp,fptt;
   for (j=1;j<=n;j++) pt[j]=p[j];     double *xits;
   for (*iter=1;;++(*iter)) {     int niterf, itmp;
     fp=(*fret);   
     ibig=0;     pt=vector(1,n);
     del=0.0;     ptt=vector(1,n);
     last_time=curr_time;    xit=vector(1,n);
     (void) gettimeofday(&curr_time,&tzp);    xits=vector(1,n);
     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);    *fret=(*func)(p);
     /*    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);    for (j=1;j<=n;j++) pt[j]=p[j];
     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec);    for (*iter=1;;++(*iter)) {
     */      fp=(*fret);
    for (i=1;i<=n;i++) {      ibig=0;
       printf(" %d %.12f",i, p[i]);      del=0.0;
       fprintf(ficlog," %d %.12lf",i, p[i]);      last_time=curr_time;
       fprintf(ficrespow," %.12lf", p[i]);      (void) gettimeofday(&curr_time,&tzp);
     }      printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
     printf("\n");      fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
     fprintf(ficlog,"\n");  /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
     fprintf(ficrespow,"\n");fflush(ficrespow);     for (i=1;i<=n;i++) {
     if(*iter <=3){        printf(" %d %.12f",i, p[i]);
       tm = *localtime(&curr_time.tv_sec);        fprintf(ficlog," %d %.12lf",i, p[i]);
       strcpy(strcurr,asctime(&tm));        fprintf(ficrespow," %.12lf", p[i]);
 /*       asctime_r(&tm,strcurr); */      }
       forecast_time=curr_time;       printf("\n");
       itmp = strlen(strcurr);      fprintf(ficlog,"\n");
       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */      fprintf(ficrespow,"\n");fflush(ficrespow);
         strcurr[itmp-1]='\0';      if(*iter <=3){
       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);        tm = *localtime(&curr_time.tv_sec);
       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);        strcpy(strcurr,asctime(&tm));
       for(niterf=10;niterf<=30;niterf+=10){  /*       asctime_r(&tm,strcurr); */
         forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);        forecast_time=curr_time;
         tmf = *localtime(&forecast_time.tv_sec);        itmp = strlen(strcurr);
 /*      asctime_r(&tmf,strfor); */        if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
         strcpy(strfor,asctime(&tmf));          strcurr[itmp-1]='\0';
         itmp = strlen(strfor);        printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
         if(strfor[itmp-1]=='\n')        fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
         strfor[itmp-1]='\0';        for(niterf=10;niterf<=30;niterf+=10){
         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.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
         fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);          tmf = *localtime(&forecast_time.tv_sec);
       }  /*      asctime_r(&tmf,strfor); */
     }          strcpy(strfor,asctime(&tmf));
     for (i=1;i<=n;i++) {           itmp = strlen(strfor);
       for (j=1;j<=n;j++) xit[j]=xi[j][i];           if(strfor[itmp-1]=='\n')
       fptt=(*fret);           strfor[itmp-1]='\0';
 #ifdef DEBUG          printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
       printf("fret=%lf \n",*fret);          fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
       fprintf(ficlog,"fret=%lf \n",*fret);        }
 #endif      }
       printf("%d",i);fflush(stdout);      for (i=1;i<=n;i++) {
       fprintf(ficlog,"%d",i);fflush(ficlog);        for (j=1;j<=n;j++) xit[j]=xi[j][i];
       linmin(p,xit,n,fret,func);         fptt=(*fret);
       if (fabs(fptt-(*fret)) > del) {   #ifdef DEBUG
         del=fabs(fptt-(*fret));         printf("fret=%lf \n",*fret);
         ibig=i;         fprintf(ficlog,"fret=%lf \n",*fret);
       }   #endif
 #ifdef DEBUG        printf("%d",i);fflush(stdout);
       printf("%d %.12e",i,(*fret));        fprintf(ficlog,"%d",i);fflush(ficlog);
       fprintf(ficlog,"%d %.12e",i,(*fret));        linmin(p,xit,n,fret,func);
       for (j=1;j<=n;j++) {        if (fabs(fptt-(*fret)) > del) {
         xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);          del=fabs(fptt-(*fret));
         printf(" x(%d)=%.12e",j,xit[j]);          ibig=i;
         fprintf(ficlog," x(%d)=%.12e",j,xit[j]);        }
       }  #ifdef DEBUG
       for(j=1;j<=n;j++) {        printf("%d %.12e",i,(*fret));
         printf(" p=%.12e",p[j]);        fprintf(ficlog,"%d %.12e",i,(*fret));
         fprintf(ficlog," p=%.12e",p[j]);        for (j=1;j<=n;j++) {
       }          xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
       printf("\n");          printf(" x(%d)=%.12e",j,xit[j]);
       fprintf(ficlog,"\n");          fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 #endif        }
     }         for(j=1;j<=n;j++) {
     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {          printf(" p=%.12e",p[j]);
 #ifdef DEBUG          fprintf(ficlog," p=%.12e",p[j]);
       int k[2],l;        }
       k[0]=1;        printf("\n");
       k[1]=-1;        fprintf(ficlog,"\n");
       printf("Max: %.12e",(*func)(p));  #endif
       fprintf(ficlog,"Max: %.12e",(*func)(p));      }
       for (j=1;j<=n;j++) {      if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
         printf(" %.12e",p[j]);  #ifdef DEBUG
         fprintf(ficlog," %.12e",p[j]);        int k[2],l;
       }        k[0]=1;
       printf("\n");        k[1]=-1;
       fprintf(ficlog,"\n");        printf("Max: %.12e",(*func)(p));
       for(l=0;l<=1;l++) {        fprintf(ficlog,"Max: %.12e",(*func)(p));
         for (j=1;j<=n;j++) {        for (j=1;j<=n;j++) {
           ptt[j]=p[j]+(p[j]-pt[j])*k[l];          printf(" %.12e",p[j]);
           printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);          fprintf(ficlog," %.12e",p[j]);
           fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);        }
         }        printf("\n");
         printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        fprintf(ficlog,"\n");
         fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));        for(l=0;l<=1;l++) {
       }          for (j=1;j<=n;j++) {
 #endif            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]);
             fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
       free_vector(xit,1,n);           }
       free_vector(xits,1,n);           printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       free_vector(ptt,1,n);           fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
       free_vector(pt,1,n);         }
       return;   #endif
     }   
     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");   
     for (j=1;j<=n;j++) {         free_vector(xit,1,n);
       ptt[j]=2.0*p[j]-pt[j];         free_vector(xits,1,n);
       xit[j]=p[j]-pt[j];         free_vector(ptt,1,n);
       pt[j]=p[j];         free_vector(pt,1,n);
     }         return;
     fptt=(*func)(ptt);       }
     if (fptt < fp) {       if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);       for (j=1;j<=n;j++) {
       if (t < 0.0) {         ptt[j]=2.0*p[j]-pt[j];
         linmin(p,xit,n,fret,func);         xit[j]=p[j]-pt[j];
         for (j=1;j<=n;j++) {         pt[j]=p[j];
           xi[j][ibig]=xi[j][n];       }
           xi[j][n]=xit[j];       fptt=(*func)(ptt);
         }      if (fptt < fp) {
 #ifdef DEBUG        t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
         printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);        if (t < 0.0) {
         fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);          linmin(p,xit,n,fret,func);
         for(j=1;j<=n;j++){          for (j=1;j<=n;j++) {
           printf(" %.12e",xit[j]);            xi[j][ibig]=xi[j][n];
           fprintf(ficlog," %.12e",xit[j]);            xi[j][n]=xit[j];
         }          }
         printf("\n");  #ifdef DEBUG
         fprintf(ficlog,"\n");          printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 #endif          fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
       }          for(j=1;j<=n;j++){
     }             printf(" %.12e",xit[j]);
   }             fprintf(ficlog," %.12e",xit[j]);
 }           }
           printf("\n");
 /**** Prevalence limit (stable or period prevalence)  ****************/          fprintf(ficlog,"\n");
   #endif
 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    }
      matrix by transitions matrix until convergence is reached */  }
   
   int i, ii,j,k;  /**** Prevalence limit (stable or period prevalence)  ****************/
   double min, max, maxmin, maxmax,sumnew=0.;  
   double **matprod2();  double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
   double **out, cov[NCOVMAX], **pmij();  {
   double **newm;    /* Computes the prevalence limit in each live state at age x by left multiplying the unit
   double agefin, delaymax=50 ; /* Max number of years to converge */       matrix by transitions matrix until convergence is reached */
   
   for (ii=1;ii<=nlstate+ndeath;ii++)    int i, ii,j,k;
     for (j=1;j<=nlstate+ndeath;j++){    double min, max, maxmin, maxmax,sumnew=0.;
       oldm[ii][j]=(ii==j ? 1.0 : 0.0);    double **matprod2();
     }    double **out, cov[NCOVMAX], **pmij();
     double **newm;
    cov[1]=1.;    double agefin, delaymax=50 ; /* Max number of years to converge */
    
  /* Even if hstepm = 1, at least one multiplication by the unit matrix */    for (ii=1;ii<=nlstate+ndeath;ii++)
   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){      for (j=1;j<=nlstate+ndeath;j++){
     newm=savm;        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
     /* Covariates have to be included here again */      }
      cov[2]=agefin;  
        cov[1]=1.;
       for (k=1; k<=cptcovn;k++) {   
         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
         /*      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(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
       }      newm=savm;
       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];      /* Covariates have to be included here again */
       for (k=1; k<=cptcovprod;k++)       cov[2]=agefin;
         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<=cptcovn;k++) {
       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/          cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/          /*      printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
       /*printf("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);        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
         for (k=1; k<=cptcovprod;k++)
     savm=oldm;          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
     oldm=newm;  
     maxmax=0.;        /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
     for(j=1;j<=nlstate;j++){        /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
       min=1.;        /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
       max=0.;      out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
       for(i=1; i<=nlstate; i++) {  
         sumnew=0;      savm=oldm;
         for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];      oldm=newm;
         prlim[i][j]= newm[i][j]/(1-sumnew);      maxmax=0.;
         max=FMAX(max,prlim[i][j]);      for(j=1;j<=nlstate;j++){
         min=FMIN(min,prlim[i][j]);        min=1.;
       }        max=0.;
       maxmin=max-min;        for(i=1; i<=nlstate; i++) {
       maxmax=FMAX(maxmax,maxmin);          sumnew=0;
     }          for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
     if(maxmax < ftolpl){          prlim[i][j]= newm[i][j]/(1-sumnew);
       return prlim;          max=FMAX(max,prlim[i][j]);
     }          min=FMIN(min,prlim[i][j]);
   }        }
 }        maxmin=max-min;
         maxmax=FMAX(maxmax,maxmin);
 /*************** transition probabilities ***************/       }
       if(maxmax < ftolpl){
 double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )        return prlim;
 {      }
   double s1, s2;    }
   /*double t34;*/  }
   int i,j,j1, nc, ii, jj;  
   /*************** transition probabilities ***************/
     for(i=1; i<= nlstate; i++){  
       for(j=1; j<i;j++){  double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){  {
           /*s2 += param[i][j][nc]*cov[nc];*/    double s1, s2;
           s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];    /*double t34;*/
 /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */    int i,j,j1, nc, ii, jj;
         }  
         ps[i][j]=s2;      for(i=1; i<= nlstate; i++){
 /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */        for(j=1; j<i;j++){
       }          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
       for(j=i+1; j<=nlstate+ndeath;j++){            /*s2 += param[i][j][nc]*cov[nc];*/
         for (nc=1, s2=0.;nc <=ncovmodel; nc++){            s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
           s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];  /*       printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
 /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */          }
         }          ps[i][j]=s2;
         ps[i][j]=s2;  /*      printf("s1=%.17e, s2=%.17e\n",s1,s2); */
       }        }
     }        for(j=i+1; j<=nlstate+ndeath;j++){
     /*ps[3][2]=1;*/          for (nc=1, s2=0.;nc <=ncovmodel; nc++){
                 s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
     for(i=1; i<= nlstate; i++){  /*        printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
       s1=0;          }
       for(j=1; j<i; j++)          ps[i][j]=s2;
         s1+=exp(ps[i][j]);        }
       for(j=i+1; j<=nlstate+ndeath; j++)      }
         s1+=exp(ps[i][j]);      /*ps[3][2]=1;*/
       ps[i][i]=1./(s1+1.);     
       for(j=1; j<i; j++)      for(i=1; i<= nlstate; i++){
         ps[i][j]= exp(ps[i][j])*ps[i][i];        s1=0;
       for(j=i+1; j<=nlstate+ndeath; j++)        for(j=1; j<i; j++)
         ps[i][j]= exp(ps[i][j])*ps[i][i];          s1+=exp(ps[i][j]);
       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */        for(j=i+1; j<=nlstate+ndeath; j++)
     } /* end i */          s1+=exp(ps[i][j]);
             ps[i][i]=1./(s1+1.);
     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){        for(j=1; j<i; j++)
       for(jj=1; jj<= nlstate+ndeath; jj++){          ps[i][j]= exp(ps[i][j])*ps[i][i];
         ps[ii][jj]=0;        for(j=i+1; j<=nlstate+ndeath; j++)
         ps[ii][ii]=1;          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 */
          
       for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */        for(jj=1; jj<= nlstate+ndeath; jj++){
 /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */          ps[ii][jj]=0;
 /*         printf("ddd %lf ",ps[ii][jj]); */          ps[ii][ii]=1;
 /*       } */        }
 /*       printf("\n "); */      }
 /*        } */     
 /*        printf("\n ");printf("%lf ",cov[2]); */  
        /*  /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
       for(i=1; i<= npar; i++) printf("%f ",x[i]);  /*       for(jj=1; jj<= nlstate+ndeath; jj++){ */
       goto end;*/  /*         printf("ddd %lf ",ps[ii][jj]); */
     return ps;  /*       } */
 }  /*       printf("\n "); */
   /*        } */
 /**************** Product of 2 matrices ******************/  /*        printf("\n ");printf("%lf ",cov[2]); */
          /*
 double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)        for(i=1; i<= npar; i++) printf("%f ",x[i]);
 {        goto end;*/
   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times      return ps;
      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */  }
   /* in, b, out are matrice of pointers which should have been initialized   
      before: only the contents of out is modified. The function returns  /**************** Product of 2 matrices ******************/
      a pointer to pointers identical to out */  
   long i, j, k;  double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
   for(i=nrl; i<= nrh; i++)  {
     for(k=ncolol; k<=ncoloh; k++)    /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
       for(j=ncl,out[i][k]=0.; j<=nch; j++)       b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
         out[i][k] +=in[i][j]*b[j][k];    /* in, b, out are matrice of pointers which should have been initialized
        before: only the contents of out is modified. The function returns
   return out;       a pointer to pointers identical to out */
 }    long i, j, k;
     for(i=nrl; i<= nrh; i++)
       for(k=ncolol; k<=ncoloh; k++)
 /************* Higher Matrix Product ***************/        for(j=ncl,out[i][k]=0.; j<=nch; j++)
           out[i][k] +=in[i][j]*b[j][k];
 double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )  
 {    return out;
   /* Computes the transition matrix starting at age 'age' over   }
      'nhstepm*hstepm*stepm' months (i.e. until  
      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying   
      nhstepm*hstepm matrices.   /************* Higher Matrix Product ***************/
      Output is stored in matrix po[i][j][h] for h every 'hstepm' step   
      (typically every 2 years instead of every month which is too big   double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
      for the memory).  {
      Model is determined by parameters x and covariates have to be     /* Computes the transition matrix starting at age 'age' over
      included manually here.        'nhstepm*hstepm*stepm' months (i.e. until
        age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
      */       nhstepm*hstepm matrices.
        Output is stored in matrix po[i][j][h] for h every 'hstepm' step
   int i, j, d, h, k;       (typically every 2 years instead of every month which is too big
   double **out, cov[NCOVMAX];       for the memory).
   double **newm;       Model is determined by parameters x and covariates have to be
        included manually here.
   /* Hstepm could be zero and should return the unit matrix */  
   for (i=1;i<=nlstate+ndeath;i++)       */
     for (j=1;j<=nlstate+ndeath;j++){  
       oldm[i][j]=(i==j ? 1.0 : 0.0);    int i, j, d, h, k;
       po[i][j][0]=(i==j ? 1.0 : 0.0);    double **out, cov[NCOVMAX];
     }    double **newm;
   /* Even if hstepm = 1, at least one multiplication by the unit matrix */  
   for(h=1; h <=nhstepm; h++){    /* Hstepm could be zero and should return the unit matrix */
     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 */        oldm[i][j]=(i==j ? 1.0 : 0.0);
       cov[1]=1.;        po[i][j][0]=(i==j ? 1.0 : 0.0);
       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]]];    /* Even if hstepm = 1, at least one multiplication by the unit matrix */
       for (k=1; k<=cptcovage;k++)    for(h=1; h <=nhstepm; h++){
         cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];      for(d=1; d <=hstepm; d++){
       for (k=1; k<=cptcovprod;k++)        newm=savm;
         cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];        /* Covariates have to be included here again */
         cov[1]=1.;
         cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/        for (k=1; k<=cptcovn;k++) cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/        for (k=1; k<=cptcovage;k++)
       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,           cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                    pmij(pmmij,cov,ncovmodel,x,nlstate));        for (k=1; k<=cptcovprod;k++)
       savm=oldm;          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
       oldm=newm;  
     }  
     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]);*/
         po[i][j][h]=newm[i][j];        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
         /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);                     pmij(pmmij,cov,ncovmodel,x,nlstate));
          */        savm=oldm;
       }        oldm=newm;
   } /* end h */      }
   return po;      for(i=1; i<=nlstate+ndeath; i++)
 }        for(j=1;j<=nlstate+ndeath;j++) {
           po[i][j][h]=newm[i][j];
           /*printf("i=%d j=%d h=%d po[i][j][h]=%f ",i,j,h,po[i][j][h]);
 /*************** log-likelihood *************/           */
 double func( double *x)        }
 {    } /* end h */
   int i, ii, j, k, mi, d, kk;    return po;
   double l, ll[NLSTATEMAX], cov[NCOVMAX];  }
   double **out;  
   double sw; /* Sum of weights */  
   double lli; /* Individual log likelihood */  /*************** log-likelihood *************/
   int s1, s2;  double func( double *x)
   double bbh, survp;  {
   long ipmx;    int i, ii, j, k, mi, d, kk;
   /*extern weight */    double l, ll[NLSTATEMAX], cov[NCOVMAX];
   /* We are differentiating ll according to initial status */    double **out;
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/    double sw; /* Sum of weights */
   /*for(i=1;i<imx;i++)     double lli; /* Individual log likelihood */
     printf(" %d\n",s[4][i]);    int s1, s2;
   */    double bbh, survp;
   cov[1]=1.;    long ipmx;
     /*extern weight */
   for(k=1; k<=nlstate; k++) ll[k]=0.;    /* We are differentiating ll according to initial status */
     /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
   if(mle==1){    /*for(i=1;i<imx;i++)
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){      printf(" %d\n",s[4][i]);
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];    */
       for(mi=1; mi<= wav[i]-1; mi++){    cov[1]=1.;
         for (ii=1;ii<=nlstate+ndeath;ii++)  
           for (j=1;j<=nlstate+ndeath;j++){    for(k=1; k<=nlstate; k++) ll[k]=0.;
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);  
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    if(mle==1){
           }      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         for(d=0; d<dh[mi][i]; d++){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           newm=savm;        for(mi=1; mi<= wav[i]-1; mi++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          for (ii=1;ii<=nlstate+ndeath;ii++)
           for (kk=1; kk<=cptcovage;kk++) {            for (j=1;j<=nlstate+ndeath;j++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           }              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,            }
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          for(d=0; d<dh[mi][i]; d++){
           savm=oldm;            newm=savm;
           oldm=newm;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         } /* end mult */            for (kk=1; kk<=cptcovage;kk++) {
                     cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
         /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */            }
         /* But now since version 0.9 we anticipate for bias at large stepm.            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
          * If stepm is larger than one month (smallest stepm) and if the exact delay                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
          * (in months) between two waves is not a multiple of stepm, we rounded to             savm=oldm;
          * the nearest (and in case of equal distance, to the lowest) interval but now            oldm=newm;
          * we keep into memory the bias bh[mi][i] and also the previous matrix product          } /* end mult */
          * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the       
          * probability in order to take into account the bias as a fraction of the way          /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
          * from savm to out if bh is negative or even beyond if bh is positive. bh varies          /* But now since version 0.9 we anticipate for bias at large stepm.
          * -stepm/2 to stepm/2 .           * If stepm is larger than one month (smallest stepm) and if the exact delay
          * For stepm=1 the results are the same as for previous versions of Imach.           * (in months) between two waves is not a multiple of stepm, we rounded to
          * For stepm > 1 the results are less biased than in previous versions.            * the nearest (and in case of equal distance, to the lowest) interval but now
          */           * we keep into memory the bias bh[mi][i] and also the previous matrix product
         s1=s[mw[mi][i]][i];           * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
         s2=s[mw[mi+1][i]][i];           * probability in order to take into account the bias as a fraction of the way
         bbh=(double)bh[mi][i]/(double)stepm;            * from savm to out if bh is negative or even beyond if bh is positive. bh varies
         /* bias bh is positive if real duration           * -stepm/2 to stepm/2 .
          * is higher than the multiple of stepm and negative otherwise.           * For stepm=1 the results are the same as for previous versions of Imach.
          */           * For stepm > 1 the results are less biased than in previous versions.
         /* 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){           s1=s[mw[mi][i]][i];
           /* i.e. if s2 is a death state and if the date of death is known           s2=s[mw[mi+1][i]][i];
              then the contribution to the likelihood is the probability to           bbh=(double)bh[mi][i]/(double)stepm;
              die between last step unit time and current  step unit time,           /* bias bh is positive if real duration
              which is also equal to probability to die before dh            * is higher than the multiple of stepm and negative otherwise.
              minus probability to die before dh-stepm .            */
              In version up to 0.92 likelihood was computed          /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
         as if date of death was unknown. Death was treated as any other          if( s2 > nlstate){
         health state: the date of the interview describes the actual state            /* i.e. if s2 is a death state and if the date of death is known
         and not the date of a change in health state. The former idea was               then the contribution to the likelihood is the probability to
         to consider that at each interview the state was recorded               die between last step unit time and current  step unit time,
         (healthy, disable or death) and IMaCh was corrected; but when we               which is also equal to probability to die before dh
         introduced the exact date of death then we should have modified               minus probability to die before dh-stepm .
         the contribution of an exact death to the likelihood. This new               In version up to 0.92 likelihood was computed
         contribution is smaller and very dependent of the step unit          as if date of death was unknown. Death was treated as any other
         stepm. It is no more the probability to die between last interview          health state: the date of the interview describes the actual state
         and month of death but the probability to survive from last          and not the date of a change in health state. The former idea was
         interview up to one month before death multiplied by the          to consider that at each interview the state was recorded
         probability to die within a month. Thanks to Chris          (healthy, disable or death) and IMaCh was corrected; but when we
         Jackson for correcting this bug.  Former versions increased          introduced the exact date of death then we should have modified
         mortality artificially. The bad side is that we add another loop          the contribution of an exact death to the likelihood. This new
         which slows down the processing. The difference can be up to 10%          contribution is smaller and very dependent of the step unit
         lower mortality.          stepm. It is no more the probability to die between last interview
           */          and month of death but the probability to survive from last
           lli=log(out[s1][s2] - savm[s1][s2]);          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==-2) {          mortality artificially. The bad side is that we add another loop
           for (j=1,survp=0. ; j<=nlstate; 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.
           /*survp += out[s1][j]; */            */
           lli= log(survp);            lli=log(out[s1][s2] - savm[s1][s2]);
         }  
           
         else if  (s2==-4) {           } else if  (s2==-2) {
           for (j=3,survp=0. ; j<=nlstate; j++)              for (j=1,survp=0. ; j<=nlstate; j++)
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];              survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
           lli= log(survp);             /*survp += out[s1][j]; */
         }             lli= log(survp);
           }
         else if  (s2==-5) {          
           for (j=1,survp=0. ; j<=2; j++)            else if  (s2==-4) {
             survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];            for (j=3,survp=0. ; j<=nlstate; j++)  
           lli= log(survp);               survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         }             lli= log(survp);
                   }
         else{  
           lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */          else if  (s2==-5) {
           /*  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<=2; j++)  
         }               survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
         /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/            lli= log(survp);
         /*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); */         
         ipmx +=1;          else{
         sw += weight[i];            lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;            /*  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 */
       } /* end of wave */          }
     } /* end of individual */          /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
   }  else if(mle==2){          /*if(lli ==000.0)*/
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          ipmx +=1;
       for(mi=1; mi<= wav[i]-1; mi++){          sw += weight[i];
         for (ii=1;ii<=nlstate+ndeath;ii++)          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           for (j=1;j<=nlstate+ndeath;j++){        } /* end of wave */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);      } /* end of individual */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    }  else if(mle==2){
           }      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         for(d=0; d<=dh[mi][i]; d++){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           newm=savm;        for(mi=1; mi<= wav[i]-1; mi++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          for (ii=1;ii<=nlstate+ndeath;ii++)
           for (kk=1; kk<=cptcovage;kk++) {            for (j=1;j<=nlstate+ndeath;j++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           }              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,            }
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          for(d=0; d<=dh[mi][i]; d++){
           savm=oldm;            newm=savm;
           oldm=newm;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         } /* end mult */            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));
         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 */            savm=oldm;
         ipmx +=1;            oldm=newm;
         sw += weight[i];          } /* end mult */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;       
       } /* end of wave */          s1=s[mw[mi][i]][i];
     } /* end of individual */          s2=s[mw[mi+1][i]][i];
   }  else if(mle==3){  /* exponential inter-extrapolation */          bbh=(double)bh[mi][i]/(double)stepm;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          ipmx +=1;
       for(mi=1; mi<= wav[i]-1; mi++){          sw += weight[i];
         for (ii=1;ii<=nlstate+ndeath;ii++)          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           for (j=1;j<=nlstate+ndeath;j++){        } /* end of wave */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);      } /* end of individual */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    }  else if(mle==3){  /* exponential inter-extrapolation */
           }      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         for(d=0; d<dh[mi][i]; d++){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           newm=savm;        for(mi=1; mi<= wav[i]-1; mi++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          for (ii=1;ii<=nlstate+ndeath;ii++)
           for (kk=1; kk<=cptcovage;kk++) {            for (j=1;j<=nlstate+ndeath;j++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           }              savm[ii][j]=(ii==j ? 1.0 : 0.0);
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,            }
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));          for(d=0; d<dh[mi][i]; d++){
           savm=oldm;            newm=savm;
           oldm=newm;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
         } /* end mult */            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));
         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 */            savm=oldm;
         ipmx +=1;            oldm=newm;
         sw += weight[i];          } /* end mult */
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;       
       } /* end of wave */          s1=s[mw[mi][i]][i];
     } /* end of individual */          s2=s[mw[mi+1][i]][i];
   }else if (mle==4){  /* ml=4 no inter-extrapolation */          bbh=(double)bh[mi][i]/(double)stepm;
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          ipmx +=1;
       for(mi=1; mi<= wav[i]-1; mi++){          sw += weight[i];
         for (ii=1;ii<=nlstate+ndeath;ii++)          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           for (j=1;j<=nlstate+ndeath;j++){        } /* end of wave */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);      } /* end of individual */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    }else if (mle==4){  /* ml=4 no inter-extrapolation */
           }      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         for(d=0; d<dh[mi][i]; d++){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           newm=savm;        for(mi=1; mi<= wav[i]-1; mi++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          for (ii=1;ii<=nlstate+ndeath;ii++)
           for (kk=1; kk<=cptcovage;kk++) {            for (j=1;j<=nlstate+ndeath;j++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           }              savm[ii][j]=(ii==j ? 1.0 : 0.0);
                     }
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          for(d=0; d<dh[mi][i]; d++){
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            newm=savm;
           savm=oldm;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
           oldm=newm;            for (kk=1; kk<=cptcovage;kk++) {
         } /* end mult */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   }
         s1=s[mw[mi][i]][i];         
         s2=s[mw[mi+1][i]][i];            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         if( s2 > nlstate){                          1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
           lli=log(out[s1][s2] - savm[s1][s2]);            savm=oldm;
         }else{            oldm=newm;
           lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */          } /* end mult */
         }       
         ipmx +=1;          s1=s[mw[mi][i]][i];
         sw += weight[i];          s2=s[mw[mi+1][i]][i];
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          if( s2 > 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]); */            lli=log(out[s1][s2] - savm[s1][s2]);
       } /* end of wave */          }else{
     } /* end of individual */            lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */          }
     for (i=1,ipmx=0, sw=0.; i<=imx; i++){          ipmx +=1;
       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];          sw += weight[i];
       for(mi=1; mi<= wav[i]-1; mi++){          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
         for (ii=1;ii<=nlstate+ndeath;ii++)  /*      printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
           for (j=1;j<=nlstate+ndeath;j++){        } /* end of wave */
             oldm[ii][j]=(ii==j ? 1.0 : 0.0);      } /* end of individual */
             savm[ii][j]=(ii==j ? 1.0 : 0.0);    }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
           }      for (i=1,ipmx=0, sw=0.; i<=imx; i++){
         for(d=0; d<dh[mi][i]; d++){        for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
           newm=savm;        for(mi=1; mi<= wav[i]-1; mi++){
           cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;          for (ii=1;ii<=nlstate+ndeath;ii++)
           for (kk=1; kk<=cptcovage;kk++) {            for (j=1;j<=nlstate+ndeath;j++){
             cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];              oldm[ii][j]=(ii==j ? 1.0 : 0.0);
           }              savm[ii][j]=(ii==j ? 1.0 : 0.0);
                     }
           out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          for(d=0; d<dh[mi][i]; d++){
                        1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));            newm=savm;
           savm=oldm;            cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
           oldm=newm;            for (kk=1; kk<=cptcovage;kk++) {
         } /* end mult */              cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   }
         s1=s[mw[mi][i]][i];         
         s2=s[mw[mi+1][i]][i];            out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
         lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
         ipmx +=1;            savm=oldm;
         sw += weight[i];            oldm=newm;
         ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;          } /* end mult */
         /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/       
       } /* end of wave */          s1=s[mw[mi][i]][i];
     } /* end of individual */          s2=s[mw[mi+1][i]][i];
   } /* End of if */          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];          ipmx +=1;
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */          sw += weight[i];
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
   return -l;          /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/
 }        } /* end of wave */
       } /* end of individual */
 /*************** log-likelihood *************/    } /* End of if */
 double funcone( double *x)    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 {    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
   /* Same as likeli but slower because of a lot of printf and if */    l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
   int i, ii, j, k, mi, d, kk;    return -l;
   double l, ll[NLSTATEMAX], cov[NCOVMAX];  }
   double **out;  
   double lli; /* Individual log likelihood */  /*************** log-likelihood *************/
   double llt;  double funcone( double *x)
   int s1, s2;  {
   double bbh, survp;    /* Same as likeli but slower because of a lot of printf and if */
   /*extern weight */    int i, ii, j, k, mi, d, kk;
   /* We are differentiating ll according to initial status */    double l, ll[NLSTATEMAX], cov[NCOVMAX];
   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/    double **out;
   /*for(i=1;i<imx;i++)     double lli; /* Individual log likelihood */
     printf(" %d\n",s[4][i]);    double llt;
   */    int s1, s2;
   cov[1]=1.;    double bbh, survp;
     /*extern weight */
   for(k=1; k<=nlstate; k++) ll[k]=0.;    /* We are differentiating ll according to initial status */
     /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
   for (i=1,ipmx=0, sw=0.; i<=imx; i++){    /*for(i=1;i<imx;i++)
     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];      printf(" %d\n",s[4][i]);
     for(mi=1; mi<= wav[i]-1; mi++){    */
       for (ii=1;ii<=nlstate+ndeath;ii++)    cov[1]=1.;
         for (j=1;j<=nlstate+ndeath;j++){  
           oldm[ii][j]=(ii==j ? 1.0 : 0.0);    for(k=1; k<=nlstate; k++) ll[k]=0.;
           savm[ii][j]=(ii==j ? 1.0 : 0.0);  
         }    for (i=1,ipmx=0, sw=0.; i<=imx; i++){
       for(d=0; d<dh[mi][i]; d++){      for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
         newm=savm;      for(mi=1; mi<= wav[i]-1; mi++){
         cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;        for (ii=1;ii<=nlstate+ndeath;ii++)
         for (kk=1; kk<=cptcovage;kk++) {          for (j=1;j<=nlstate+ndeath;j++){
           cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
         }            savm[ii][j]=(ii==j ? 1.0 : 0.0);
         out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,          }
                      1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));        for(d=0; d<dh[mi][i]; d++){
         savm=oldm;          newm=savm;
         oldm=newm;          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
       } /* end mult */          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 is positive if real duration          savm=oldm;
        * is higher than the multiple of stepm and negative otherwise.          oldm=newm;
        */        } /* end mult */
       if( s2 > nlstate && (mle <5) ){  /* Jackson */       
         lli=log(out[s1][s2] - savm[s1][s2]);        s1=s[mw[mi][i]][i];
       } else if  (s2==-2) {        s2=s[mw[mi+1][i]][i];
         for (j=1,survp=0. ; j<=nlstate; j++)         bbh=(double)bh[mi][i]/(double)stepm;
           survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];        /* bias is positive if real duration
         lli= log(survp);         * is higher than the multiple of stepm and negative otherwise.
       }else if (mle==1){         */
         lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */        if( s2 > nlstate && (mle <5) ){  /* Jackson */
       } else if(mle==2){          lli=log(out[s1][s2] - savm[s1][s2]);
         lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */        } else if  (s2==-2) {
       } else if(mle==3){  /* exponential inter-extrapolation */          for (j=1,survp=0. ; j<=nlstate; j++)
         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 */            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
       } else if (mle==4){  /* mle=4 no inter-extrapolation */          lli= log(survp);
         lli=log(out[s1][s2]); /* Original formula */        }else if (mle==1){
       } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
         lli=log(out[s1][s2]); /* Original formula */        } else if(mle==2){
       } /* End of if */          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 */
       ipmx +=1;        } else if(mle==3){  /* exponential inter-extrapolation */
       sw += weight[i];          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 */
       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;        } else if (mle==4){  /* mle=4 no inter-extrapolation */
 /*       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]); */          lli=log(out[s1][s2]); /* Original formula */
       if(globpr){        } else{  /* ml>=5 no inter-extrapolation no jackson =0.8a */
         fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\          lli=log(out[s1][s2]); /* Original formula */
  %11.6f %11.6f %11.6f ", \        } /* End of if */
                 num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],        ipmx +=1;
                 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);        sw += weight[i];
         for(k=1,llt=0.,l=0.; k<=nlstate; k++){        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
           llt +=ll[k]*gipmx/gsw;  /*       printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
           fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);        if(globpr){
         }          fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
         fprintf(ficresilk," %10.6f\n", -llt);   %11.6f %11.6f %11.6f ", \
       }                  num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
     } /* end of wave */                  2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
   } /* end of individual */          for(k=1,llt=0.,l=0.; k<=nlstate; k++){
   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];            llt +=ll[k]*gipmx/gsw;
   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */            fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */          }
   if(globpr==0){ /* First time we count the contributions and weights */          fprintf(ficresilk," %10.6f\n", -llt);
     gipmx=ipmx;        }
     gsw=sw;      } /* end of wave */
   }    } /* end of individual */
   return -l;    for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 }    /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
     l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
     if(globpr==0){ /* First time we count the contributions and weights */
 /*************** function likelione ***********/      gipmx=ipmx;
 void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))      gsw=sw;
 {    }
   /* This routine should help understanding what is done with     return -l;
      the selection of individuals/waves and  }
      to check the exact contribution to the likelihood.  
      Plotting could be done.  
    */  /*************** function likelione ***********/
   int k;  void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
   {
   if(*globpri !=0){ /* Just counts and sums, no printings */    /* This routine should help understanding what is done with
     strcpy(fileresilk,"ilk");        the selection of individuals/waves and
     strcat(fileresilk,fileres);       to check the exact contribution to the likelihood.
     if((ficresilk=fopen(fileresilk,"w"))==NULL) {       Plotting could be done.
       printf("Problem with resultfile: %s\n", fileresilk);     */
       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);    int k;
     }  
     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");    if(*globpri !=0){ /* Just counts and sums, no printings */
     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");      strcpy(fileresilk,"ilk");
     /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */      strcat(fileresilk,fileres);
     for(k=1; k<=nlstate; k++)       if((ficresilk=fopen(fileresilk,"w"))==NULL) {
       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);        printf("Problem with resultfile: %s\n", fileresilk);
     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");        fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
   }      }
       fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
   *fretone=(*funcone)(p);      fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
   if(*globpri !=0){      /*  i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
     fclose(ficresilk);      for(k=1; k<=nlstate; k++)
     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));        fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
     fflush(fichtm);       fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
   }     }
   return;  
 }    *fretone=(*funcone)(p);
     if(*globpri !=0){
       fclose(ficresilk);
 /*********** Maximum Likelihood Estimation ***************/      fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
       fflush(fichtm);
 void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))    }
 {    return;
   int i,j, iter;  }
   double **xi;  
   double fret;  
   double fretone; /* Only one call to likelihood */  /*********** Maximum Likelihood Estimation ***************/
   /*  char filerespow[FILENAMELENGTH];*/  
   xi=matrix(1,npar,1,npar);  void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
   for (i=1;i<=npar;i++)  {
     for (j=1;j<=npar;j++)    int i,j, iter;
       xi[i][j]=(i==j ? 1.0 : 0.0);    double **xi;
   printf("Powell\n");  fprintf(ficlog,"Powell\n");    double fret;
   strcpy(filerespow,"pow");     double fretone; /* Only one call to likelihood */
   strcat(filerespow,fileres);    /*  char filerespow[FILENAMELENGTH];*/
   if((ficrespow=fopen(filerespow,"w"))==NULL) {    xi=matrix(1,npar,1,npar);
     printf("Problem with resultfile: %s\n", filerespow);    for (i=1;i<=npar;i++)
     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);      for (j=1;j<=npar;j++)
   }        xi[i][j]=(i==j ? 1.0 : 0.0);
   fprintf(ficrespow,"# Powell\n# iter -2*LL");    printf("Powell\n");  fprintf(ficlog,"Powell\n");
   for (i=1;i<=nlstate;i++)    strcpy(filerespow,"pow");
     for(j=1;j<=nlstate+ndeath;j++)    strcat(filerespow,fileres);
       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);    if((ficrespow=fopen(filerespow,"w"))==NULL) {
   fprintf(ficrespow,"\n");      printf("Problem with resultfile: %s\n", filerespow);
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
   powell(p,xi,npar,ftol,&iter,&fret,func);    }
     fprintf(ficrespow,"# Powell\n# iter -2*LL");
   free_matrix(xi,1,npar,1,npar);    for (i=1;i<=nlstate;i++)
   fclose(ficrespow);      for(j=1;j<=nlstate+ndeath;j++)
   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));    fprintf(ficrespow,"\n");
   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));  
     powell(p,xi,npar,ftol,&iter,&fret,func);
 }  
     free_matrix(xi,1,npar,1,npar);
 /**** Computes Hessian and covariance matrix ***/    fclose(ficrespow);
 void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))    printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
 {    fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
   double  **a,**y,*x,pd;    fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
   double **hess;  
   int i, j,jk;  }
   int *indx;  
   /**** Computes Hessian and covariance matrix ***/
   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);  void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
   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[]) ;    double  **a,**y,*x,pd;
   void ludcmp(double **a, int npar, int *indx, double *d) ;    double **hess;
   double gompertz(double p[]);    int i, j,jk;
   hess=matrix(1,npar,1,npar);    int *indx;
   
   printf("\nCalculation of the hessian matrix. Wait...\n");    double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");    double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
   for (i=1;i<=npar;i++){    void lubksb(double **a, int npar, int *indx, double b[]) ;
     printf("%d",i);fflush(stdout);    void ludcmp(double **a, int npar, int *indx, double *d) ;
     fprintf(ficlog,"%d",i);fflush(ficlog);    double gompertz(double p[]);
        hess=matrix(1,npar,1,npar);
      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);  
         printf("\nCalculation of the hessian matrix. Wait...\n");
     /*  printf(" %f ",p[i]);    fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
         printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/    for (i=1;i<=npar;i++){
   }      printf("%d",i);fflush(stdout);
         fprintf(ficlog,"%d",i);fflush(ficlog);
   for (i=1;i<=npar;i++) {     
     for (j=1;j<=npar;j++)  {       hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
       if (j>i) {      
         printf(".%d%d",i,j);fflush(stdout);      /*  printf(" %f ",p[i]);
         fprintf(ficlog,".%d%d",i,j);fflush(ficlog);          printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
         hess[i][j]=hessij(p,delti,i,j,func,npar);    }
            
         hess[j][i]=hess[i][j];        for (i=1;i<=npar;i++) {
         /*printf(" %lf ",hess[i][j]);*/      for (j=1;j<=npar;j++)  {
       }        if (j>i) {
     }          printf(".%d%d",i,j);fflush(stdout);
   }          fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
   printf("\n");          hess[i][j]=hessij(p,delti,i,j,func,npar);
   fprintf(ficlog,"\n");         
           hess[j][i]=hess[i][j];    
   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");          /*printf(" %lf ",hess[i][j]);*/
   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");        }
         }
   a=matrix(1,npar,1,npar);    }
   y=matrix(1,npar,1,npar);    printf("\n");
   x=vector(1,npar);    fprintf(ficlog,"\n");
   indx=ivector(1,npar);  
   for (i=1;i<=npar;i++)    printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];    fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
   ludcmp(a,npar,indx,&pd);   
     a=matrix(1,npar,1,npar);
   for (j=1;j<=npar;j++) {    y=matrix(1,npar,1,npar);
     for (i=1;i<=npar;i++) x[i]=0;    x=vector(1,npar);
     x[j]=1;    indx=ivector(1,npar);
     lubksb(a,npar,indx,x);    for (i=1;i<=npar;i++)
     for (i=1;i<=npar;i++){       for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
       matcov[i][j]=x[i];    ludcmp(a,npar,indx,&pd);
     }  
   }    for (j=1;j<=npar;j++) {
       for (i=1;i<=npar;i++) x[i]=0;
   printf("\n#Hessian matrix#\n");      x[j]=1;
   fprintf(ficlog,"\n#Hessian matrix#\n");      lubksb(a,npar,indx,x);
   for (i=1;i<=npar;i++) {       for (i=1;i<=npar;i++){
     for (j=1;j<=npar;j++) {         matcov[i][j]=x[i];
       printf("%.3e ",hess[i][j]);      }
       fprintf(ficlog,"%.3e ",hess[i][j]);    }
     }  
     printf("\n");    printf("\n#Hessian matrix#\n");
     fprintf(ficlog,"\n");    fprintf(ficlog,"\n#Hessian matrix#\n");
   }    for (i=1;i<=npar;i++) {
       for (j=1;j<=npar;j++) {
   /* Recompute Inverse */        printf("%.3e ",hess[i][j]);
   for (i=1;i<=npar;i++)        fprintf(ficlog,"%.3e ",hess[i][j]);
     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];      }
   ludcmp(a,npar,indx,&pd);      printf("\n");
       fprintf(ficlog,"\n");
   /*  printf("\n#Hessian matrix recomputed#\n");    }
   
   for (j=1;j<=npar;j++) {    /* Recompute Inverse */
     for (i=1;i<=npar;i++) x[i]=0;    for (i=1;i<=npar;i++)
     x[j]=1;      for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
     lubksb(a,npar,indx,x);    ludcmp(a,npar,indx,&pd);
     for (i=1;i<=npar;i++){   
       y[i][j]=x[i];    /*  printf("\n#Hessian matrix recomputed#\n");
       printf("%.3e ",y[i][j]);  
       fprintf(ficlog,"%.3e ",y[i][j]);    for (j=1;j<=npar;j++) {
     }      for (i=1;i<=npar;i++) x[i]=0;
     printf("\n");      x[j]=1;
     fprintf(ficlog,"\n");      lubksb(a,npar,indx,x);
   }      for (i=1;i<=npar;i++){
   */        y[i][j]=x[i];
         printf("%.3e ",y[i][j]);
   free_matrix(a,1,npar,1,npar);        fprintf(ficlog,"%.3e ",y[i][j]);
   free_matrix(y,1,npar,1,npar);      }
   free_vector(x,1,npar);      printf("\n");
   free_ivector(indx,1,npar);      fprintf(ficlog,"\n");
   free_matrix(hess,1,npar,1,npar);    }
     */
   
 }    free_matrix(a,1,npar,1,npar);
     free_matrix(y,1,npar,1,npar);
 /*************** hessian matrix ****************/    free_vector(x,1,npar);
 double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)    free_ivector(indx,1,npar);
 {    free_matrix(hess,1,npar,1,npar);
   int i;  
   int l=1, lmax=20;  
   double k1,k2;  }
   double p2[NPARMAX+1];  
   double res;  /*************** hessian matrix ****************/
   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;  double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
   double fx;  {
   int k=0,kmax=10;    int i;
   double l1;    int l=1, lmax=20;
     double k1,k2;
   fx=func(x);    double p2[NPARMAX+1];
   for (i=1;i<=npar;i++) p2[i]=x[i];    double res;
   for(l=0 ; l <=lmax; l++){    double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
     l1=pow(10,l);    double fx;
     delts=delt;    int k=0,kmax=10;
     for(k=1 ; k <kmax; k=k+1){    double l1;
       delt = delta*(l1*k);  
       p2[theta]=x[theta] +delt;    fx=func(x);
       k1=func(p2)-fx;    for (i=1;i<=npar;i++) p2[i]=x[i];
       p2[theta]=x[theta]-delt;    for(l=0 ; l <=lmax; l++){
       k2=func(p2)-fx;      l1=pow(10,l);
       /*res= (k1-2.0*fx+k2)/delt/delt; */      delts=delt;
       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */      for(k=1 ; k <kmax; k=k+1){
               delt = delta*(l1*k);
 #ifdef DEBUG        p2[theta]=x[theta] +delt;
       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);        k1=func(p2)-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);        p2[theta]=x[theta]-delt;
 #endif        k2=func(p2)-fx;
       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */        /*res= (k1-2.0*fx+k2)/delt/delt; */
       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){        res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
         k=kmax;       
       }  #ifdef DEBUG
       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */        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);
         k=kmax; l=lmax*10.;        fprintf(ficlog,"%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
       }  #endif
       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){         /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
         delts=delt;        if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
       }          k=kmax;
     }        }
   }        else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
   delti[theta]=delts;          k=kmax; l=lmax*10.;
   return res;         }
           else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
 }          delts=delt;
         }
 double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)      }
 {    }
   int i;    delti[theta]=delts;
   int l=1, l1, lmax=20;    return res;
   double k1,k2,k3,k4,res,fx;   
   double p2[NPARMAX+1];  }
   int k;  
   double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
   fx=func(x);  {
   for (k=1; k<=2; k++) {    int i;
     for (i=1;i<=npar;i++) p2[i]=x[i];    int l=1, l1, lmax=20;
     p2[thetai]=x[thetai]+delti[thetai]/k;    double k1,k2,k3,k4,res,fx;
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;    double p2[NPARMAX+1];
     k1=func(p2)-fx;    int k;
     
     p2[thetai]=x[thetai]+delti[thetai]/k;    fx=func(x);
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;    for (k=1; k<=2; k++) {
     k2=func(p2)-fx;      for (i=1;i<=npar;i++) p2[i]=x[i];
         p2[thetai]=x[thetai]+delti[thetai]/k;
     p2[thetai]=x[thetai]-delti[thetai]/k;      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
     p2[thetaj]=x[thetaj]+delti[thetaj]/k;      k1=func(p2)-fx;
     k3=func(p2)-fx;   
         p2[thetai]=x[thetai]+delti[thetai]/k;
     p2[thetai]=x[thetai]-delti[thetai]/k;      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
     p2[thetaj]=x[thetaj]-delti[thetaj]/k;      k2=func(p2)-fx;
     k4=func(p2)-fx;   
     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */      p2[thetai]=x[thetai]-delti[thetai]/k;
 #ifdef DEBUG      p2[thetaj]=x[thetaj]+delti[thetaj]/k;
     printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);      k3=func(p2)-fx;
     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      p2[thetai]=x[thetai]-delti[thetai]/k;
   }      p2[thetaj]=x[thetaj]-delti[thetaj]/k;
   return res;      k4=func(p2)-fx;
 }      res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
   #ifdef DEBUG
 /************** Inverse of matrix **************/      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);
 void ludcmp(double **a, int n, int *indx, double *d)       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
   int i,imax,j,k;     }
   double big,dum,sum,temp;     return res;
   double *vv;   }
    
   vv=vector(1,n);   /************** Inverse of matrix **************/
   *d=1.0;   void ludcmp(double **a, int n, int *indx, double *d)
   for (i=1;i<=n;i++) {   {
     big=0.0;     int i,imax,j,k;
     for (j=1;j<=n;j++)     double big,dum,sum,temp;
       if ((temp=fabs(a[i][j])) > big) big=temp;     double *vv;
     if (big == 0.0) nrerror("Singular matrix in routine ludcmp");    
     vv[i]=1.0/big;     vv=vector(1,n);
   }     *d=1.0;
   for (j=1;j<=n;j++) {     for (i=1;i<=n;i++) {
     for (i=1;i<j;i++) {       big=0.0;
       sum=a[i][j];       for (j=1;j<=n;j++)
       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];         if ((temp=fabs(a[i][j])) > big) big=temp;
       a[i][j]=sum;       if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
     }       vv[i]=1.0/big;
     big=0.0;     }
     for (i=j;i<=n;i++) {     for (j=1;j<=n;j++) {
       sum=a[i][j];       for (i=1;i<j;i++) {
       for (k=1;k<j;k++)         sum=a[i][j];
         sum -= a[i][k]*a[k][j];         for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
       a[i][j]=sum;         a[i][j]=sum;
       if ( (dum=vv[i]*fabs(sum)) >= big) {       }
         big=dum;       big=0.0;
         imax=i;       for (i=j;i<=n;i++) {
       }         sum=a[i][j];
     }         for (k=1;k<j;k++)
     if (j != imax) {           sum -= a[i][k]*a[k][j];
       for (k=1;k<=n;k++) {         a[i][j]=sum;
         dum=a[imax][k];         if ( (dum=vv[i]*fabs(sum)) >= big) {
         a[imax][k]=a[j][k];           big=dum;
         a[j][k]=dum;           imax=i;
       }         }
       *d = -(*d);       }
       vv[imax]=vv[j];       if (j != imax) {
     }         for (k=1;k<=n;k++) {
     indx[j]=imax;           dum=a[imax][k];
     if (a[j][j] == 0.0) a[j][j]=TINY;           a[imax][k]=a[j][k];
     if (j != n) {           a[j][k]=dum;
       dum=1.0/(a[j][j]);         }
       for (i=j+1;i<=n;i++) a[i][j] *= dum;         *d = -(*d);
     }         vv[imax]=vv[j];
   }       }
   free_vector(vv,1,n);  /* Doesn't work */      indx[j]=imax;
 ;      if (a[j][j] == 0.0) a[j][j]=TINY;
 }       if (j != n) {
         dum=1.0/(a[j][j]);
 void lubksb(double **a, int n, int *indx, double b[])         for (i=j+1;i<=n;i++) a[i][j] *= dum;
 {       }
   int i,ii=0,ip,j;     }
   double sum;     free_vector(vv,1,n);  /* Doesn't work */
    ;
   for (i=1;i<=n;i++) {   }
     ip=indx[i];   
     sum=b[ip];   void lubksb(double **a, int n, int *indx, double b[])
     b[ip]=b[i];   {
     if (ii)     int i,ii=0,ip,j;
       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];     double sum;
     else if (sum) ii=i;    
     b[i]=sum;     for (i=1;i<=n;i++) {
   }       ip=indx[i];
   for (i=n;i>=1;i--) {       sum=b[ip];
     sum=b[i];       b[ip]=b[i];
     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];       if (ii)
     b[i]=sum/a[i][i];         for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
   }       else if (sum) ii=i;
 }       b[i]=sum;
     }
 void pstamp(FILE *fichier)    for (i=n;i>=1;i--) {
 {      sum=b[i];
   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);      for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
 }      b[i]=sum/a[i][i];
     }
 /************ Frequencies ********************/  }
 void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])  
 {  /* Some frequencies */  void pstamp(FILE *fichier)
     {
   int i, m, jk, k1,i1, j1, bool, z1,z2,j;    fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
   int first;  }
   double ***freq; /* Frequencies */  
   double *pp, **prop;  /************ Frequencies ********************/
   double pos,posprop, k2, dateintsum=0,k2cpt=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[])
   char fileresp[FILENAMELENGTH];  {  /* Some frequencies */
      
   pp=vector(1,nlstate);    int i, m, jk, k1,i1, j1, bool, z1,z2,j;
   prop=matrix(1,nlstate,iagemin,iagemax+3);    int first;
   strcpy(fileresp,"p");    double ***freq; /* Frequencies */
   strcat(fileresp,fileres);    double *pp, **prop;
   if((ficresp=fopen(fileresp,"w"))==NULL) {    double pos,posprop, k2, dateintsum=0,k2cpt=0;
     printf("Problem with prevalence resultfile: %s\n", fileresp);    char fileresp[FILENAMELENGTH];
     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);   
     exit(0);    pp=vector(1,nlstate);
   }    prop=matrix(1,nlstate,iagemin,iagemax+3);
   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);    strcpy(fileresp,"p");
   j1=0;    strcat(fileresp,fileres);
       if((ficresp=fopen(fileresp,"w"))==NULL) {
   j=cptcoveff;      printf("Problem with prevalence resultfile: %s\n", fileresp);
   if (cptcovn<1) {j=1;ncodemax[1]=1;}      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
       exit(0);
   first=1;    }
     freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
   for(k1=1; k1<=j;k1++){    j1=0;
     for(i1=1; i1<=ncodemax[k1];i1++){   
       j1++;    j=cptcoveff;
       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);    if (cptcovn<1) {j=1;ncodemax[1]=1;}
         scanf("%d", i);*/  
       for (i=-5; i<=nlstate+ndeath; i++)      first=1;
         for (jk=-5; jk<=nlstate+ndeath; jk++)    
           for(m=iagemin; m <= iagemax+3; m++)    for(k1=1; k1<=j;k1++){
             freq[i][jk][m]=0;      for(i1=1; i1<=ncodemax[k1];i1++){
         j1++;
     for (i=1; i<=nlstate; i++)          /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
       for(m=iagemin; m <= iagemax+3; m++)          scanf("%d", i);*/
         prop[i][m]=0;        for (i=-5; i<=nlstate+ndeath; i++)  
                 for (jk=-5; jk<=nlstate+ndeath; jk++)  
       dateintsum=0;            for(m=iagemin; m <= iagemax+3; m++)
       k2cpt=0;              freq[i][jk][m]=0;
       for (i=1; i<=imx; i++) {  
         bool=1;      for (i=1; i<=nlstate; i++)  
         if  (cptcovn>0) {        for(m=iagemin; m <= iagemax+3; m++)
           for (z1=1; z1<=cptcoveff; z1++)           prop[i][m]=0;
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])        
               bool=0;        dateintsum=0;
         }        k2cpt=0;
         if (bool==1){        for (i=1; i<=imx; i++) {
           for(m=firstpass; m<=lastpass; m++){          bool=1;
             k2=anint[m][i]+(mint[m][i]/12.);          if  (cptcovn>0) {
             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/            for (z1=1; z1<=cptcoveff; z1++)
               if(agev[m][i]==0) agev[m][i]=iagemax+1;              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
               if(agev[m][i]==1) agev[m][i]=iagemax+2;                bool=0;
               if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];          }
               if (m<lastpass) {          if (bool==1){
                 freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];            for(m=firstpass; m<=lastpass; m++){
                 freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];              k2=anint[m][i]+(mint[m][i]/12.);
               }              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                               if(agev[m][i]==0) agev[m][i]=iagemax+1;
               if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {                if(agev[m][i]==1) agev[m][i]=iagemax+2;
                 dateintsum=dateintsum+k2;                if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                 k2cpt++;                if (m<lastpass) {
               }                  freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
               /*}*/                  freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
           }                }
         }               
       }                if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                          dateintsum=dateintsum+k2;
       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/                  k2cpt++;
       pstamp(ficresp);                }
       if  (cptcovn>0) {                /*}*/
         fprintf(ficresp, "\n#********** Variable ");             }
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          }
         fprintf(ficresp, "**********\n#");        }
       }         
       for(i=1; i<=nlstate;i++)         /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);        pstamp(ficresp);
       fprintf(ficresp, "\n");        if  (cptcovn>0) {
                 fprintf(ficresp, "\n#********** Variable ");
       for(i=iagemin; i <= iagemax+3; i++){          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         if(i==iagemax+3){          fprintf(ficresp, "**********\n#");
           fprintf(ficlog,"Total");        }
         }else{        for(i=1; i<=nlstate;i++)
           if(first==1){          fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
             first=0;        fprintf(ficresp, "\n");
             printf("See log file for details...\n");       
           }        for(i=iagemin; i <= iagemax+3; i++){
           fprintf(ficlog,"Age %d", i);          if(i==iagemax+3){
         }            fprintf(ficlog,"Total");
         for(jk=1; jk <=nlstate ; jk++){          }else{
           for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)            if(first==1){
             pp[jk] += freq[jk][m][i];               first=0;
         }              printf("See log file for details...\n");
         for(jk=1; jk <=nlstate ; jk++){            }
           for(m=-1, pos=0; m <=0 ; m++)            fprintf(ficlog,"Age %d", i);
             pos += freq[jk][m][i];          }
           if(pp[jk]>=1.e-10){          for(jk=1; jk <=nlstate ; jk++){
             if(first==1){            for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);              pp[jk] += freq[jk][m][i];
             }          }
             fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);          for(jk=1; jk <=nlstate ; jk++){
           }else{            for(m=-1, pos=0; m <=0 ; m++)
             if(first==1)              pos += freq[jk][m][i];
               printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);            if(pp[jk]>=1.e-10){
             fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);              if(first==1){
           }              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
         }              }
               fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
         for(jk=1; jk <=nlstate ; jk++){            }else{
           for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)              if(first==1)
             pp[jk] += freq[jk][m][i];                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
         }                     fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
         for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){            }
           pos += pp[jk];          }
           posprop += prop[jk][i];  
         }          for(jk=1; jk <=nlstate ; jk++){
         for(jk=1; jk <=nlstate ; jk++){            for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
           if(pos>=1.e-5){              pp[jk] += freq[jk][m][i];
             if(first==1)          }      
               printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);          for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
             fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);            pos += pp[jk];
           }else{            posprop += prop[jk][i];
             if(first==1)          }
               printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);          for(jk=1; jk <=nlstate ; jk++){
             fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);            if(pos>=1.e-5){
           }              if(first==1)
           if( i <= iagemax){                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
             if(pos>=1.e-5){              fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
               fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);            }else{
               /*probs[i][jk][j1]= pp[jk]/pos;*/              if(first==1)
               /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
             }              fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
             else            }
               fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);            if( i <= iagemax){
           }              if(pos>=1.e-5){
         }                fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                         /*probs[i][jk][j1]= pp[jk]/pos;*/
         for(jk=-1; jk <=nlstate+ndeath; jk++)                /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
           for(m=-1; m <=nlstate+ndeath; m++)              }
             if(freq[jk][m][i] !=0 ) {              else
             if(first==1)                fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
               printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);            }
               fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);          }
             }         
         if(i <= iagemax)          for(jk=-1; jk <=nlstate+ndeath; jk++)
           fprintf(ficresp,"\n");            for(m=-1; m <=nlstate+ndeath; m++)
         if(first==1)              if(freq[jk][m][i] !=0 ) {
           printf("Others in log...\n");              if(first==1)
         fprintf(ficlog,"\n");                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
       }                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
     }              }
   }          if(i <= iagemax)
   dateintmean=dateintsum/k2cpt;             fprintf(ficresp,"\n");
            if(first==1)
   fclose(ficresp);            printf("Others in log...\n");
   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);          fprintf(ficlog,"\n");
   free_vector(pp,1,nlstate);        }
   free_matrix(prop,1,nlstate,iagemin, iagemax+3);      }
   /* End of Freq */    }
 }    dateintmean=dateintsum/k2cpt;
    
 /************ Prevalence ********************/    fclose(ficresp);
 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)    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 {      free_vector(pp,1,nlstate);
   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people    free_matrix(prop,1,nlstate,iagemin, iagemax+3);
      in each health status at the date of interview (if between dateprev1 and dateprev2).    /* End of Freq */
      We still use firstpass and lastpass as another selection.  }
   */  
    /************ Prevalence ********************/
   int i, m, jk, k1, i1, j1, bool, z1,z2,j;  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)
   double ***freq; /* Frequencies */  {  
   double *pp, **prop;    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
   double pos,posprop;        in each health status at the date of interview (if between dateprev1 and dateprev2).
   double  y2; /* in fractional years */       We still use firstpass and lastpass as another selection.
   int iagemin, iagemax;    */
    
   iagemin= (int) agemin;    int i, m, jk, k1, i1, j1, bool, z1,z2,j;
   iagemax= (int) agemax;    double ***freq; /* Frequencies */
   /*pp=vector(1,nlstate);*/    double *pp, **prop;
   prop=matrix(1,nlstate,iagemin,iagemax+3);     double pos,posprop;
   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/    double  y2; /* in fractional years */
   j1=0;    int iagemin, iagemax;
     
   j=cptcoveff;    iagemin= (int) agemin;
   if (cptcovn<1) {j=1;ncodemax[1]=1;}    iagemax= (int) agemax;
       /*pp=vector(1,nlstate);*/
   for(k1=1; k1<=j;k1++){    prop=matrix(1,nlstate,iagemin,iagemax+3);
     for(i1=1; i1<=ncodemax[k1];i1++){    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
       j1++;    j1=0;
          
       for (i=1; i<=nlstate; i++)      j=cptcoveff;
         for(m=iagemin; m <= iagemax+3; m++)    if (cptcovn<1) {j=1;ncodemax[1]=1;}
           prop[i][m]=0.0;   
          for(k1=1; k1<=j;k1++){
       for (i=1; i<=imx; i++) { /* Each individual */      for(i1=1; i1<=ncodemax[k1];i1++){
         bool=1;        j1++;
         if  (cptcovn>0) {       
           for (z1=1; z1<=cptcoveff; z1++)         for (i=1; i<=nlstate; i++)  
             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])           for(m=iagemin; m <= iagemax+3; m++)
               bool=0;            prop[i][m]=0.0;
         }        
         if (bool==1) {         for (i=1; i<=imx; i++) { /* Each individual */
           for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/          bool=1;
             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */          if  (cptcovn>0) {
             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */            for (z1=1; z1<=cptcoveff; z1++)
               if(agev[m][i]==0) agev[m][i]=iagemax+1;              if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
               if(agev[m][i]==1) agev[m][i]=iagemax+2;                bool=0;
               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) {           if (bool==1) {
                 /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/            for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                 prop[s[m][i]][(int)agev[m][i]] += weight[i];              y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                 prop[s[m][i]][iagemax+3] += weight[i];               if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
               }                 if(agev[m][i]==0) agev[m][i]=iagemax+1;
             }                if(agev[m][i]==1) agev[m][i]=iagemax+2;
           } /* end selection of waves */                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) {
       }                  /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
       for(i=iagemin; i <= iagemax+3; i++){                    prop[s[m][i]][(int)agev[m][i]] += weight[i];
                           prop[s[m][i]][iagemax+3] += weight[i];
         for(jk=1,posprop=0; jk <=nlstate ; jk++) {                 }
           posprop += prop[jk][i];               }
         }             } /* end selection of waves */
           }
         for(jk=1; jk <=nlstate ; jk++){             }
           if( i <=  iagemax){         for(i=iagemin; i <= iagemax+3; i++){  
             if(posprop>=1.e-5){          
               probs[i][jk][j1]= prop[jk][i]/posprop;          for(jk=1,posprop=0; jk <=nlstate ; jk++) {
             }             posprop += prop[jk][i];
           }           }
         }/* end jk */   
       }/* end i */           for(jk=1; jk <=nlstate ; jk++){    
     } /* end i1 */            if( i <=  iagemax){
   } /* end k1 */              if(posprop>=1.e-5){
                   probs[i][jk][j1]= prop[jk][i]/posprop;
   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/              }
   /*free_vector(pp,1,nlstate);*/            }
   free_matrix(prop,1,nlstate, iagemin,iagemax+3);          }/* end jk */
 }  /* End of prevalence */        }/* end i */
       } /* end i1 */
 /************* Waves Concatenation ***************/    } /* end k1 */
    
 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)    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 {    /*free_vector(pp,1,nlstate);*/
   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.    free_matrix(prop,1,nlstate, iagemin,iagemax+3);
      Death is a valid wave (if date is known).  }  /* End of prevalence */
      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i  
      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]  /************* Waves Concatenation ***************/
      and mw[mi+1][i]. dh depends on stepm.  
      */  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)
   {
   int i, mi, m;    /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;       Death is a valid wave (if date is known).
      double sum=0., jmean=0.;*/       mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
   int first;       dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
   int j, k=0,jk, ju, jl;       and mw[mi+1][i]. dh depends on stepm.
   double sum=0.;       */
   first=0;  
   jmin=1e+5;    int i, mi, m;
   jmax=-1;    /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
   jmean=0.;       double sum=0., jmean=0.;*/
   for(i=1; i<=imx; i++){    int first;
     mi=0;    int j, k=0,jk, ju, jl;
     m=firstpass;    double sum=0.;
     while(s[m][i] <= nlstate){    first=0;
       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)    jmin=1e+5;
         mw[++mi][i]=m;    jmax=-1;
       if(m >=lastpass)    jmean=0.;
         break;    for(i=1; i<=imx; i++){
       else      mi=0;
         m++;      m=firstpass;
     }/* end while */      while(s[m][i] <= nlstate){
     if (s[m][i] > nlstate){        if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
       mi++;     /* Death is another wave */          mw[++mi][i]=m;
       /* if(mi==0)  never been interviewed correctly before death */        if(m >=lastpass)
          /* Only death is a correct wave */          break;
       mw[mi][i]=m;        else
     }          m++;
       }/* end while */
     wav[i]=mi;      if (s[m][i] > nlstate){
     if(mi==0){        mi++;     /* Death is another wave */
       nbwarn++;        /* if(mi==0)  never been interviewed correctly before death */
       if(first==0){           /* Only death is a correct wave */
         printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);        mw[mi][i]=m;
         first=1;      }
       }  
       if(first==1){      wav[i]=mi;
         fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);      if(mi==0){
       }        nbwarn++;
     } /* end mi==0 */        if(first==0){
   } /* End individuals */          printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
           first=1;
   for(i=1; i<=imx; i++){        }
     for(mi=1; mi<wav[i];mi++){        if(first==1){
       if (stepm <=0)          fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
         dh[mi][i]=1;        }
       else{      } /* end mi==0 */
         if (s[mw[mi+1][i]][i] > nlstate) { /* A death */    } /* End individuals */
           if (agedc[i] < 2*AGESUP) {  
             j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);     for(i=1; i<=imx; i++){
             if(j==0) j=1;  /* Survives at least one month after exam */      for(mi=1; mi<wav[i];mi++){
             else if(j<0){        if (stepm <=0)
               nberr++;          dh[mi][i]=1;
               printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);        else{
               j=1; /* Temporary Dangerous patch */          if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
               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);            if (agedc[i] < 2*AGESUP) {
               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]);              j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
               fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);              if(j==0) j=1;  /* Survives at least one month after exam */
             }              else if(j<0){
             k=k+1;                nberr++;
             if (j >= jmax){                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]);
               jmax=j;                j=1; /* Temporary Dangerous patch */
               ijmax=i;                printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
             }                fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
             if (j <= jmin){                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);
               jmin=j;              }
               ijmin=i;              k=k+1;
             }              if (j >= jmax){
             sum=sum+j;                jmax=j;
             /*if (j<0) printf("j=%d num=%d \n",j,i);*/                ijmax=i;
             /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/              }
           }              if (j <= jmin){
         }                jmin=j;
         else{                ijmin=i;
           j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));              }
 /*        if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */              sum=sum+j;
               /*if (j<0) printf("j=%d num=%d \n",j,i);*/
           k=k+1;              /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
           if (j >= jmax) {            }
             jmax=j;          }
             ijmax=i;          else{
           }            j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
           else if (j <= jmin){  /*        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]); */
             jmin=j;  
             ijmin=i;            k=k+1;
           }            if (j >= jmax) {
           /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */              jmax=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]);*/              ijmax=i;
           if(j<0){            }
             nberr++;            else if (j <= jmin){
             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]);              jmin=j;
             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]);              ijmin=i;
           }            }
           sum=sum+j;            /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
         }            /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
         jk= j/stepm;            if(j<0){
         jl= j -jk*stepm;              nberr++;
         ju= j -(jk+1)*stepm;              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(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */              fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
           if(jl==0){            }
             dh[mi][i]=jk;            sum=sum+j;
             bh[mi][i]=0;          }
           }else{ /* We want a negative bias in order to only have interpolation ie          jk= j/stepm;
                   * at the price of an extra matrix product in likelihood */          jl= j -jk*stepm;
             dh[mi][i]=jk+1;          ju= j -(jk+1)*stepm;
             bh[mi][i]=ju;          if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
           }            if(jl==0){
         }else{              dh[mi][i]=jk;
           if(jl <= -ju){              bh[mi][i]=0;
             dh[mi][i]=jk;            }else{ /* We want a negative bias in order to only have interpolation ie
             bh[mi][i]=jl;       /* bias is positive if real duration                    * at the price of an extra matrix product in likelihood */
                                  * is higher than the multiple of stepm and negative otherwise.              dh[mi][i]=jk+1;
                                  */              bh[mi][i]=ju;
           }            }
           else{          }else{
             dh[mi][i]=jk+1;            if(jl <= -ju){
             bh[mi][i]=ju;              dh[mi][i]=jk;
           }              bh[mi][i]=jl;       /* bias is positive if real duration
           if(dh[mi][i]==0){                                   * is higher than the multiple of stepm and negative otherwise.
             dh[mi][i]=1; /* At least one step */                                   */
             bh[mi][i]=ju; /* At least one step */            }
             /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/            else{
           }              dh[mi][i]=jk+1;
         } /* end if mle */              bh[mi][i]=ju;
       }            }
     } /* end wave */            if(dh[mi][i]==0){
   }              dh[mi][i]=1; /* At least one step */
   jmean=sum/k;              bh[mi][i]=ju; /* At least one step */
   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);              /*  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);*/
   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);            }
  }          } /* end if mle */
         }
 /*********** Tricode ****************************/      } /* end wave */
 void tricode(int *Tvar, int **nbcode, int imx)    }
 {    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);
   int Ndum[20],ij=1, k, j, i, maxncov=19;    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);
   int cptcode=0;   }
   cptcoveff=0;   
    /*********** Tricode ****************************/
   for (k=0; k<maxncov; k++) Ndum[k]=0;  void tricode(int *Tvar, int **nbcode, int imx)
   for (k=1; k<=7; k++) ncodemax[k]=0;  {
    
   for (j=1; j<=(cptcovn+2*cptcovprod); j++) {    int Ndum[20],ij=1, k, j, i, maxncov=19;
     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum     int cptcode=0;
                                modality*/     cptcoveff=0;
       ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/   
       Ndum[ij]++; /*store the modality */    for (k=0; k<maxncov; k++) Ndum[k]=0;
       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/    for (k=1; k<=7; k++) ncodemax[k]=0;
       if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable   
                                        Tvar[j]. If V=sex and male is 0 and     for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
                                        female is 1, then  cptcode=1.*/      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*/
     for (i=0; i<=cptcode; i++) {        Ndum[ij]++; /*store the modality */
       if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
     }        if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
                                          Tvar[j]. If V=sex and male is 0 and
     ij=1;                                          female is 1, then  cptcode=1.*/
     for (i=1; i<=ncodemax[j]; i++) {      }
       for (k=0; k<= maxncov; k++) {  
         if (Ndum[k] != 0) {      for (i=0; i<=cptcode; i++) {
           nbcode[Tvar[j]][ij]=k;         if(Ndum[i]!=0) ncodemax[j]++; /* Nomber of modalities of the j th covariates. In fact ncodemax[j]=2 (dichotom. variables) but it can be more */
           /* 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; */      }
             
           ij++;      ij=1;
         }      for (i=1; i<=ncodemax[j]; i++) {
         if (ij > ncodemax[j]) break;         for (k=0; k<= maxncov; k++) {
       }            if (Ndum[k] != 0) {
     }             nbcode[Tvar[j]][ij]=k;
   }              /* store the modality in an array. k is a modality. If we have model=V1+V1*sex then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
            
  for (k=0; k< maxncov; k++) Ndum[k]=0;            ij++;
           }
  for (i=1; i<=ncovmodel-2; i++) {           if (ij > ncodemax[j]) break;
    /* 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 (k=0; k< maxncov; k++) Ndum[k]=0;
  ij=1;  
  for (i=1; i<= maxncov; i++) {   for (i=1; i<=ncovmodel-2; i++) {
    if((Ndum[i]!=0) && (i<=ncovcol)){     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
      Tvaraff[ij]=i; /*For printing */     ij=Tvar[i];
      ij++;     Ndum[ij]++;
    }   }
  }  
     ij=1;
  cptcoveff=ij-1; /*Number of simple covariates*/   for (i=1; i<= maxncov; i++) {
 }     if((Ndum[i]!=0) && (i<=ncovcol)){
        Tvaraff[ij]=i; /*For printing */
 /*********** Health Expectancies ****************/       ij++;
      }
 void evsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )   }
    
 {   cptcoveff=ij-1; /*Number of simple covariates*/
   /* Health expectancies, no variances */  }
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;  
   double age, agelim, hf;  /*********** Health Expectancies ****************/
   double ***p3mat;  
   double eip;  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[] )
   
   pstamp(ficreseij);  {
   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");    /* Health expectancies, no variances */
   fprintf(ficreseij,"# Age");    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
   for(i=1; i<=nlstate;i++){    double age, agelim, hf;
     for(j=1; j<=nlstate;j++){    double ***p3mat;
       fprintf(ficreseij," e%1d%1d ",i,j);    double eip;
     }  
     fprintf(ficreseij," e%1d. ",i);    pstamp(ficreseij);
   }    fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
   fprintf(ficreseij,"\n");    fprintf(ficreseij,"# Age");
     for(i=1; i<=nlstate;i++){
         for(j=1; j<=nlstate;j++){
   if(estepm < stepm){        fprintf(ficreseij," e%1d%1d ",i,j);
     printf ("Problem %d lower than %d\n",estepm, stepm);      }
   }      fprintf(ficreseij," e%1d. ",i);
   else  hstepm=estepm;       }
   /* We compute the life expectancy from trapezoids spaced every estepm months    fprintf(ficreseij,"\n");
    * This is mainly to measure the difference between two models: for example  
    * if stepm=24 months pijx are given only every 2 years and by summing them   
    * we are calculating an estimate of the Life Expectancy assuming a linear     if(estepm < stepm){
    * progression in between and thus overestimating or underestimating according      printf ("Problem %d lower than %d\n",estepm, stepm);
    * 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    else  hstepm=estepm;  
    * to compare the new estimate of Life expectancy with the same linear     /* We compute the life expectancy from trapezoids spaced every estepm months
    * hypothesis. A more precise result, taking into account a more precise     * This is mainly to measure the difference between two models: for example
    * curvature will be obtained if estepm is as small as stepm. */     * if stepm=24 months pijx are given only every 2 years and by summing them
      * we are calculating an estimate of the Life Expectancy assuming a linear
   /* For example we decided to compute the life expectancy with the smallest unit */     * progression in between and thus overestimating or underestimating according
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.      * to the curvature of the survival function. If, for the same date, we
      nhstepm is the number of hstepm from age to agelim      * estimate the model with stepm=1 month, we can keep estepm to 24 months
      nstepm is the number of stepm from age to agelin.      * to compare the new estimate of Life expectancy with the same linear
      Look at hpijx to understand the reason of that which relies in memory size     * hypothesis. A more precise result, taking into account a more precise
      and note for a fixed period like estepm months */     * curvature will be obtained if estepm is as small as stepm. */
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the  
      survival function given by stepm (the optimization length). Unfortunately it    /* For example we decided to compute the life expectancy with the smallest unit */
      means that if the survival funtion is printed only each two years of age and if    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
      you sum them up and add 1 year (area under the trapezoids) you won't get the same        nhstepm is the number of hstepm from age to agelim
      results. So we changed our mind and took the option of the best precision.       nstepm is the number of stepm from age to agelin.
   */       Look at hpijx to understand the reason of that which relies in memory size
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */        and note for a fixed period like estepm months */
     /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   agelim=AGESUP;       survival function given by stepm (the optimization length). Unfortunately it
   /* nhstepm age range expressed in number of stepm */       means that if the survival funtion is printed only each two years of age and if
   nstepm=(int) rint((agelim-age)*YEARM/stepm);        you sum them up and add 1 year (area under the trapezoids) you won't get the same
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */        results. So we changed our mind and took the option of the best precision.
   /* if (stepm >= YEARM) hstepm=1;*/    */
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);  
     agelim=AGESUP;
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    /* If stepm=6 months */
     /* Computed by stepm unit matrices, product of hstepm matrices, stored      /* Computed by stepm unit matrices, product of hstepm matrices, stored
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
          
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);    /* nhstepm age range expressed in number of stepm */
         nstepm=(int) rint((agelim-bage)*YEARM/stepm);
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    /* Typically if 20 years nstepm = 20*12/6=40 stepm */
         /* if (stepm >= YEARM) hstepm=1;*/
     printf("%d|",(int)age);fflush(stdout);    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       
     /* Computing expectancies */    for (age=bage; age<=fage; age ++){
     for(i=1; i<=nlstate;i++)  
       for(j=1; j<=nlstate;j++)  
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
           eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;     
                 hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
           /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/     
       printf("%d|",(int)age);fflush(stdout);
         }      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
      
     fprintf(ficreseij,"%3.0f",age );  
     for(i=1; i<=nlstate;i++){      /* Computing expectancies */
       eip=0;      for(i=1; i<=nlstate;i++)
       for(j=1; j<=nlstate;j++){        for(j=1; j<=nlstate;j++)
         eip +=eij[i][j][(int)age];          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
         fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );            eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
       }           
       fprintf(ficreseij,"%9.4f", eip );            /*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(ficreseij,"\n");          }
          
   }      fprintf(ficreseij,"%3.0f",age );
   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      for(i=1; i<=nlstate;i++){
   printf("\n");        eip=0;
   fprintf(ficlog,"\n");        for(j=1; j<=nlstate;j++){
             eip +=eij[i][j][(int)age];
 }          fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
         }
 void cvevsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )        fprintf(ficreseij,"%9.4f", eip );
       }
 {      fprintf(ficreseij,"\n");
   /* Covariances of health expectancies eij and of total life expectancies according     
    to initial status i, ei. .    }
   */    free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;    printf("\n");
   double age, agelim, hf;    fprintf(ficlog,"\n");
   double ***p3matp, ***p3matm, ***varhe;   
   double **dnewm,**doldm;  }
   double *xp, *xm;  
   double **gp, **gm;  void cvevsij(char fileres[], double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
   double ***gradg, ***trgradg;  
   int theta;  {
     /* Covariances of health expectancies eij and of total life expectancies according
   double eip, vip;     to initial status i, ei. .
     */
   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);    int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
   xp=vector(1,npar);    double age, agelim, hf;
   xm=vector(1,npar);    double ***p3matp, ***p3matm, ***varhe;
   dnewm=matrix(1,nlstate*nlstate,1,npar);    double **dnewm,**doldm;
   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);    double *xp, *xm;
       double **gp, **gm;
   pstamp(ficresstdeij);    double ***gradg, ***trgradg;
   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");    int theta;
   fprintf(ficresstdeij,"# Age");  
   for(i=1; i<=nlstate;i++){    double eip, vip;
     for(j=1; j<=nlstate;j++)  
       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);    varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
     fprintf(ficresstdeij," e%1d. ",i);    xp=vector(1,npar);
   }    xm=vector(1,npar);
   fprintf(ficresstdeij,"\n");    dnewm=matrix(1,nlstate*nlstate,1,npar);
     doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
   pstamp(ficrescveij);   
   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");    pstamp(ficresstdeij);
   fprintf(ficrescveij,"# Age");    fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
   for(i=1; i<=nlstate;i++)    fprintf(ficresstdeij,"# Age");
     for(j=1; j<=nlstate;j++){    for(i=1; i<=nlstate;i++){
       cptj= (j-1)*nlstate+i;      for(j=1; j<=nlstate;j++)
       for(i2=1; i2<=nlstate;i2++)        fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
         for(j2=1; j2<=nlstate;j2++){      fprintf(ficresstdeij," e%1d. ",i);
           cptj2= (j2-1)*nlstate+i2;    }
           if(cptj2 <= cptj)    fprintf(ficresstdeij,"\n");
             fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);  
         }    pstamp(ficrescveij);
     }    fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
   fprintf(ficrescveij,"\n");    fprintf(ficrescveij,"# Age");
       for(i=1; i<=nlstate;i++)
   if(estepm < stepm){      for(j=1; j<=nlstate;j++){
     printf ("Problem %d lower than %d\n",estepm, stepm);        cptj= (j-1)*nlstate+i;
   }        for(i2=1; i2<=nlstate;i2++)
   else  hstepm=estepm;             for(j2=1; j2<=nlstate;j2++){
   /* We compute the life expectancy from trapezoids spaced every estepm months            cptj2= (j2-1)*nlstate+i2;
    * This is mainly to measure the difference between two models: for example            if(cptj2 <= cptj)
    * if stepm=24 months pijx are given only every 2 years and by summing them              fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
    * 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     fprintf(ficrescveij,"\n");
    * estimate the model with stepm=1 month, we can keep estepm to 24 months   
    * to compare the new estimate of Life expectancy with the same linear     if(estepm < stepm){
    * hypothesis. A more precise result, taking into account a more precise      printf ("Problem %d lower than %d\n",estepm, stepm);
    * curvature will be obtained if estepm is as small as stepm. */    }
     else  hstepm=estepm;  
   /* For example we decided to compute the life expectancy with the smallest unit */    /* We compute the life expectancy from trapezoids spaced every estepm months
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.      * This is mainly to measure the difference between two models: for example
      nhstepm is the number of hstepm from age to agelim      * if stepm=24 months pijx are given only every 2 years and by summing them
      nstepm is the number of stepm from age to agelin.      * we are calculating an estimate of the Life Expectancy assuming a linear
      Look at hpijx to understand the reason of that which relies in memory size     * progression in between and thus overestimating or underestimating according
      and note for a fixed period like estepm months */     * to the curvature of the survival function. If, for the same date, we
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the     * estimate the model with stepm=1 month, we can keep estepm to 24 months
      survival function given by stepm (the optimization length). Unfortunately it     * to compare the new estimate of Life expectancy with the same linear
      means that if the survival funtion is printed only each two years of age and if     * hypothesis. A more precise result, taking into account a more precise
      you sum them up and add 1 year (area under the trapezoids) you won't get the same      * curvature will be obtained if estepm is as small as stepm. */
      results. So we changed our mind and took the option of the best precision.  
   */    /* For example we decided to compute the life expectancy with the smallest unit */
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     /* 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
   /* If stepm=6 months */       nstepm is the number of stepm from age to agelin.
   /* nhstepm age range expressed in number of stepm */       Look at hpijx to understand the reason of that which relies in memory size
   agelim=AGESUP;       and note for a fixed period like estepm months */
   nstepm=(int) rint((agelim-age)*YEARM/stepm);     /* We decided (b) to get a life expectancy respecting the most precise curvature of the
   /* Typically if 20 years nstepm = 20*12/6=40 stepm */        survival function given by stepm (the optimization length). Unfortunately it
   /* if (stepm >= YEARM) hstepm=1;*/       means that if the survival funtion is printed only each two years of age and if
   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */       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.
   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    */
   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);  
   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);    /* If stepm=6 months */
   gp=matrix(0,nhstepm,1,nlstate*nlstate);    /* nhstepm age range expressed in number of stepm */
   gm=matrix(0,nhstepm,1,nlstate*nlstate);    agelim=AGESUP;
     nstepm=(int) rint((agelim-bage)*YEARM/stepm);
   for (age=bage; age<=fage; age ++){     /* Typically if 20 years nstepm = 20*12/6=40 stepm */
     /* if (stepm >= YEARM) hstepm=1;*/
     /* Computed by stepm unit matrices, product of hstepm matrices, stored    nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */   
      p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */    p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
     /* Computing  Variances of health expectancies */    trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to    gp=matrix(0,nhstepm,1,nlstate*nlstate);
        decrease memory allocation */    gm=matrix(0,nhstepm,1,nlstate*nlstate);
     for(theta=1; theta <=npar; theta++){  
       for(i=1; i<=npar; i++){     for (age=bage; age<=fage; age ++){
         xp[i] = x[i] + (i==theta ?delti[theta]:0);  
         xm[i] = x[i] - (i==theta ?delti[theta]:0);      /* Computed by stepm unit matrices, product of hstepm matrices, stored
       }         in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);     
       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);        hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     
       for(j=1; j<= nlstate; j++){      /* Computing  Variances of health expectancies */
         for(i=1; i<=nlstate; i++){      /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
           for(h=0; h<=nhstepm-1; h++){         decrease memory allocation */
             gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;      for(theta=1; theta <=npar; theta++){
             gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;        for(i=1; i<=npar; i++){
           }          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);  
       for(ij=1; ij<= nlstate*nlstate; ij++)        hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
         for(h=0; h<=nhstepm-1; h++){   
           gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];        for(j=1; j<= nlstate; j++){
         }          for(i=1; i<=nlstate; i++){
     }/* End theta */            for(h=0; h<=nhstepm-1; h++){
                   gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
     for(h=0; h<=nhstepm-1; h++)            }
       for(j=1; j<=nlstate*nlstate;j++)          }
         for(theta=1; theta <=npar; theta++)        }
           trgradg[h][j][theta]=gradg[h][theta][j];       
             for(ij=1; ij<= nlstate*nlstate; ij++)
           for(h=0; h<=nhstepm-1; h++){
      for(ij=1;ij<=nlstate*nlstate;ij++)            gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
       for(ji=1;ji<=nlstate*nlstate;ji++)          }
         varhe[ij][ji][(int)age] =0.;      }/* End theta */
      
      printf("%d|",(int)age);fflush(stdout);     
      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);      for(h=0; h<=nhstepm-1; h++)
      for(h=0;h<=nhstepm-1;h++){        for(j=1; j<=nlstate*nlstate;j++)
       for(k=0;k<=nhstepm-1;k++){          for(theta=1; theta <=npar; theta++)
         matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);            trgradg[h][j][theta]=gradg[h][theta][j];
         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++)       for(ij=1;ij<=nlstate*nlstate;ij++)
             varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;        for(ji=1;ji<=nlstate*nlstate;ji++)
       }          varhe[ij][ji][(int)age] =0.;
     }  
     /* Computing expectancies */       printf("%d|",(int)age);fflush(stdout);
     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);         fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
     for(i=1; i<=nlstate;i++)       for(h=0;h<=nhstepm-1;h++){
       for(j=1; j<=nlstate;j++)        for(k=0;k<=nhstepm-1;k++){
         for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){          matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
           eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;          matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                     for(ij=1;ij<=nlstate*nlstate;ij++)
           /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/            for(ji=1;ji<=nlstate*nlstate;ji++)
               varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
         }        }
       }
     fprintf(ficresstdeij,"%3.0f",age );  
     for(i=1; i<=nlstate;i++){      /* Computing expectancies */
       eip=0.;      hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
       vip=0.;      for(i=1; i<=nlstate;i++)
       for(j=1; j<=nlstate;j++){        for(j=1; j<=nlstate;j++)
         eip += eij[i][j][(int)age];          for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
         for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */            eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
           vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];           
         fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );            /* 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," %9.4f (%.4f)", eip, sqrt(vip));          }
     }  
     fprintf(ficresstdeij,"\n");      fprintf(ficresstdeij,"%3.0f",age );
       for(i=1; i<=nlstate;i++){
     fprintf(ficrescveij,"%3.0f",age );        eip=0.;
     for(i=1; i<=nlstate;i++)        vip=0.;
       for(j=1; j<=nlstate;j++){        for(j=1; j<=nlstate;j++){
         cptj= (j-1)*nlstate+i;          eip += eij[i][j][(int)age];
         for(i2=1; i2<=nlstate;i2++)          for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
           for(j2=1; j2<=nlstate;j2++){            vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
             cptj2= (j2-1)*nlstate+i2;          fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
             if(cptj2 <= cptj)        }
               fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);        fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
           }      }
       }      fprintf(ficresstdeij,"\n");
     fprintf(ficrescveij,"\n");  
          fprintf(ficrescveij,"%3.0f",age );
   }      for(i=1; i<=nlstate;i++)
   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);        for(j=1; j<=nlstate;j++){
   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);          cptj= (j-1)*nlstate+i;
   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);          for(i2=1; i2<=nlstate;i2++)
   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);            for(j2=1; j2<=nlstate;j2++){
   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);              cptj2= (j2-1)*nlstate+i2;
   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);              if(cptj2 <= cptj)
   printf("\n");                fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
   fprintf(ficlog,"\n");            }
         }
   free_vector(xm,1,npar);      fprintf(ficrescveij,"\n");
   free_vector(xp,1,npar);     
   free_matrix(dnewm,1,nlstate*nlstate,1,npar);    }
   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);    free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);    free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 }    free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
     free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 /************ Variance ******************/    free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 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[])    free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 {    printf("\n");
   /* Variance of health expectancies */    fprintf(ficlog,"\n");
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/  
   /* double **newm;*/    free_vector(xm,1,npar);
   double **dnewm,**doldm;    free_vector(xp,1,npar);
   double **dnewmp,**doldmp;    free_matrix(dnewm,1,nlstate*nlstate,1,npar);
   int i, j, nhstepm, hstepm, h, nstepm ;    free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
   int k, cptcode;    free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
   double *xp;  }
   double **gp, **gm;  /* for var eij */  
   double ***gradg, ***trgradg; /*for var eij */  /************ Variance ******************/
   double **gradgp, **trgradgp; /* for var p point 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[])
   double *gpp, *gmp; /* for var p point j */  {
   double **varppt; /* for var p point j nlstate to nlstate+ndeath */    /* Variance of health expectancies */
   double ***p3mat;    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
   double age,agelim, hf;    /* double **newm;*/
   double ***mobaverage;    double **dnewm,**doldm;
   int theta;    double **dnewmp,**doldmp;
   char digit[4];    int i, j, nhstepm, hstepm, h, nstepm ;
   char digitp[25];    int k, cptcode;
     double *xp;
   char fileresprobmorprev[FILENAMELENGTH];    double **gp, **gm;  /* for var eij */
     double ***gradg, ***trgradg; /*for var eij */
   if(popbased==1){    double **gradgp, **trgradgp; /* for var p point j */
     if(mobilav!=0)    double *gpp, *gmp; /* for var p point j */
       strcpy(digitp,"-populbased-mobilav-");    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
     else strcpy(digitp,"-populbased-nomobil-");    double ***p3mat;
   }    double age,agelim, hf;
   else     double ***mobaverage;
     strcpy(digitp,"-stablbased-");    int theta;
     char digit[4];
   if (mobilav!=0) {    char digitp[25];
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  
     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){    char fileresprobmorprev[FILENAMELENGTH];
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);  
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    if(popbased==1){
     }      if(mobilav!=0)
   }        strcpy(digitp,"-populbased-mobilav-");
       else strcpy(digitp,"-populbased-nomobil-");
   strcpy(fileresprobmorprev,"prmorprev");     }
   sprintf(digit,"%-d",ij);    else
   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/      strcpy(digitp,"-stablbased-");
   strcat(fileresprobmorprev,digit); /* Tvar to be done */  
   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */    if (mobilav!=0) {
   strcat(fileresprobmorprev,fileres);      mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {      if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
     printf("Problem with resultfile: %s\n", fileresprobmorprev);        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   }      }
   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    }
    
   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);    strcpy(fileresprobmorprev,"prmorprev");
   pstamp(ficresprobmorprev);    sprintf(digit,"%-d",ij);
   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);    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);    strcat(fileresprobmorprev,digit); /* Tvar to be done */
   for(j=nlstate+1; j<=(nlstate+ndeath);j++){    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
     fprintf(ficresprobmorprev," p.%-d SE",j);    strcat(fileresprobmorprev,fileres);
     for(i=1; i<=nlstate;i++)    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);      printf("Problem with resultfile: %s\n", fileresprobmorprev);
   }        fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
   fprintf(ficresprobmorprev,"\n");    }
   fprintf(ficgp,"\n# Routine varevsij");    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   /* 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");    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);    pstamp(ficresprobmorprev);
 /*   } */    fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);
   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
   pstamp(ficresvij);    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");      fprintf(ficresprobmorprev," p.%-d SE",j);
   if(popbased==1)      for(i=1; i<=nlstate;i++)
     fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
   else    }  
     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");    fprintf(ficresprobmorprev,"\n");
   fprintf(ficresvij,"# Age");    fprintf(ficgp,"\n# Routine varevsij");
   for(i=1; i<=nlstate;i++)    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
     for(j=1; j<=nlstate;j++)    fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");
       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
   fprintf(ficresvij,"\n");  /*   } */
     varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   xp=vector(1,npar);    pstamp(ficresvij);
   dnewm=matrix(1,nlstate,1,npar);    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
   doldm=matrix(1,nlstate,1,nlstate);    if(popbased==1)
   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);      fprintf(ficresvij,"the age specific prevalence observed in the population i.e cross-sectionally\n in each health state (popbased=1)");
   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    else
       fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);    fprintf(ficresvij,"# Age");
   gpp=vector(nlstate+1,nlstate+ndeath);    for(i=1; i<=nlstate;i++)
   gmp=vector(nlstate+1,nlstate+ndeath);      for(j=1; j<=nlstate;j++)
   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
       fprintf(ficresvij,"\n");
   if(estepm < stepm){  
     printf ("Problem %d lower than %d\n",estepm, stepm);    xp=vector(1,npar);
   }    dnewm=matrix(1,nlstate,1,npar);
   else  hstepm=estepm;       doldm=matrix(1,nlstate,1,nlstate);
   /* For example we decided to compute the life expectancy with the smallest unit */    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.     doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
      nhstepm is the number of hstepm from age to agelim   
      nstepm is the number of stepm from age to agelin.     gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
      Look at hpijx to understand the reason of that which relies in memory size    gpp=vector(nlstate+1,nlstate+ndeath);
      and note for a fixed period like k years */    gmp=vector(nlstate+1,nlstate+ndeath);
   /* We decided (b) to get a life expectancy respecting the most precise curvature of the    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
      survival function given by stepm (the optimization length). Unfortunately it   
      means that if the survival funtion is printed every two years of age and if    if(estepm < stepm){
      you sum them up and add 1 year (area under the trapezoids) you won't get the same       printf ("Problem %d lower than %d\n",estepm, stepm);
      results. So we changed our mind and took the option of the best precision.    }
   */    else  hstepm=estepm;  
   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */     /* For example we decided to compute the life expectancy with the smallest unit */
   agelim = AGESUP;    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */       nhstepm is the number of hstepm from age to agelim
     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */        nstepm is the number of stepm from age to agelin.
     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */       Look at hpijx to understand the reason of that which relies in memory size
     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);       and note for a fixed period like k years */
     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);    /* We decided (b) to get a life expectancy respecting the most precise curvature of the
     gp=matrix(0,nhstepm,1,nlstate);       survival function given by stepm (the optimization length). Unfortunately it
     gm=matrix(0,nhstepm,1,nlstate);       means that if the survival funtion is printed every two years of age and if
        you sum them up and add 1 year (area under the trapezoids) you won't get the same
        results. So we changed our mind and took the option of the best precision.
     for(theta=1; theta <=npar; theta++){    */
       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    agelim = AGESUP;
       }    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);        nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
       if (popbased==1) {      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
         if(mobilav ==0){      gp=matrix(0,nhstepm,1,nlstate);
           for(i=1; i<=nlstate;i++)      gm=matrix(0,nhstepm,1,nlstate);
             prlim[i][i]=probs[(int)age][i][ij];  
         }else{ /* mobilav */   
           for(i=1; i<=nlstate;i++)      for(theta=1; theta <=npar; theta++){
             prlim[i][i]=mobaverage[(int)age][i][ij];        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
         }          xp[i] = x[i] + (i==theta ?delti[theta]:0);
       }        }
           hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
       for(j=1; j<= nlstate; j++){        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(h=0; h<=nhstepm; h++){  
           for(i=1, gp[h][j]=0.;i<=nlstate;i++)        if (popbased==1) {
             gp[h][j] += prlim[i][i]*p3mat[i][j][h];          if(mobilav ==0){
         }            for(i=1; i<=nlstate;i++)
       }              prlim[i][i]=probs[(int)age][i][ij];
       /* This for computing probability of death (h=1 means          }else{ /* mobilav */
          computed over hstepm matrices product = hstepm*stepm months)             for(i=1; i<=nlstate;i++)
          as a weighted average of prlim.              prlim[i][i]=mobaverage[(int)age][i][ij];
       */          }
       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=1; j<= nlstate; j++){
       }              for(h=0; h<=nhstepm; h++){
       /* end probability of death */            for(i=1, gp[h][j]=0.;i<=nlstate;i++)
               gp[h][j] += prlim[i][i]*p3mat[i][j][h];
       for(i=1; i<=npar; i++) /* Computes gradient x - delta */          }
         xp[i] = x[i] - (i==theta ?delti[theta]:0);        }
       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);          /* This for computing probability of death (h=1 means
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);           computed over hstepm matrices product = hstepm*stepm months)
             as a weighted average of prlim.
       if (popbased==1) {        */
         if(mobilav ==0){        for(j=nlstate+1;j<=nlstate+ndeath;j++){
           for(i=1; i<=nlstate;i++)          for(i=1,gpp[j]=0.; i<= nlstate; i++)
             prlim[i][i]=probs[(int)age][i][ij];            gpp[j] += prlim[i][i]*p3mat[i][j][1];
         }else{ /* mobilav */         }    
           for(i=1; i<=nlstate;i++)        /* end probability of death */
             prlim[i][i]=mobaverage[(int)age][i][ij];  
         }        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
       }          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
       for(j=1; j<= nlstate; j++){        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(h=0; h<=nhstepm; h++){   
           for(i=1, gm[h][j]=0.;i<=nlstate;i++)        if (popbased==1) {
             gm[h][j] += prlim[i][i]*p3mat[i][j][h];          if(mobilav ==0){
         }            for(i=1; i<=nlstate;i++)
       }              prlim[i][i]=probs[(int)age][i][ij];
       /* This for computing probability of death (h=1 means          }else{ /* mobilav */
          computed over hstepm matrices product = hstepm*stepm months)             for(i=1; i<=nlstate;i++)
          as a weighted average of prlim.              prlim[i][i]=mobaverage[(int)age][i][ij];
       */          }
       for(j=nlstate+1;j<=nlstate+ndeath;j++){        }
         for(i=1,gmp[j]=0.; i<= nlstate; i++)  
          gmp[j] += prlim[i][i]*p3mat[i][j][1];        for(j=1; j<= nlstate; j++){
       }              for(h=0; h<=nhstepm; h++){
       /* end probability of death */            for(i=1, gm[h][j]=0.;i<=nlstate;i++)
               gm[h][j] += prlim[i][i]*p3mat[i][j][h];
       for(j=1; j<= nlstate; j++) /* vareij */          }
         for(h=0; h<=nhstepm; h++){        }
           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];        /* This for computing probability of death (h=1 means
         }           computed over hstepm matrices product = hstepm*stepm months)
            as a weighted average of prlim.
       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */        */
         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];        for(j=nlstate+1;j<=nlstate+ndeath;j++){
       }          for(i=1,gmp[j]=0.; i<= nlstate; i++)
            gmp[j] += prlim[i][i]*p3mat[i][j][1];
     } /* End theta */        }    
         /* end probability of death */
     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */  
         for(j=1; j<= nlstate; j++) /* vareij */
     for(h=0; h<=nhstepm; h++) /* veij */          for(h=0; h<=nhstepm; h++){
       for(j=1; j<=nlstate;j++)            gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
         for(theta=1; theta <=npar; theta++)          }
           trgradg[h][j][theta]=gradg[h][theta][j];  
         for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */          gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
       for(theta=1; theta <=npar; theta++)        }
         trgradgp[j][theta]=gradgp[theta][j];  
         } /* End theta */
   
     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
     for(i=1;i<=nlstate;i++)  
       for(j=1;j<=nlstate;j++)      for(h=0; h<=nhstepm; h++) /* veij */
         vareij[i][j][(int)age] =0.;        for(j=1; j<=nlstate;j++)
           for(theta=1; theta <=npar; theta++)
     for(h=0;h<=nhstepm;h++){            trgradg[h][j][theta]=gradg[h][theta][j];
       for(k=0;k<=nhstepm;k++){  
         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);        for(theta=1; theta <=npar; theta++)
         for(i=1;i<=nlstate;i++)          trgradgp[j][theta]=gradgp[theta][j];
           for(j=1;j<=nlstate;j++)   
             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;  
       }      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
     }      for(i=1;i<=nlstate;i++)
           for(j=1;j<=nlstate;j++)
     /* pptj */          vareij[i][j][(int)age] =0.;
     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);  
     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);      for(h=0;h<=nhstepm;h++){
     for(j=nlstate+1;j<=nlstate+ndeath;j++)        for(k=0;k<=nhstepm;k++){
       for(i=nlstate+1;i<=nlstate+ndeath;i++)          matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
         varppt[j][i]=doldmp[j][i];          matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
     /* end ppptj */          for(i=1;i<=nlstate;i++)
     /*  x centered again */            for(j=1;j<=nlstate;j++)
     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);                vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);        }
        }
     if (popbased==1) {   
       if(mobilav ==0){      /* pptj */
         for(i=1; i<=nlstate;i++)      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
           prlim[i][i]=probs[(int)age][i][ij];      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
       }else{ /* mobilav */       for(j=nlstate+1;j<=nlstate+ndeath;j++)
         for(i=1; i<=nlstate;i++)        for(i=nlstate+1;i<=nlstate+ndeath;i++)
           prlim[i][i]=mobaverage[(int)age][i][ij];          varppt[j][i]=doldmp[j][i];
       }      /* end ppptj */
     }      /*  x centered again */
                    hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
     /* This for computing probability of death (h=1 means      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
        computed over hstepm (estepm) matrices product = hstepm*stepm months)    
        as a weighted average of prlim.      if (popbased==1) {
     */        if(mobilav ==0){
     for(j=nlstate+1;j<=nlstate+ndeath;j++){          for(i=1; i<=nlstate;i++)
       for(i=1,gmp[j]=0.;i<= nlstate; i++)             prlim[i][i]=probs[(int)age][i][ij];
         gmp[j] += prlim[i][i]*p3mat[i][j][1];         }else{ /* mobilav */
     }              for(i=1; i<=nlstate;i++)
     /* end probability of death */            prlim[i][i]=mobaverage[(int)age][i][ij];
         }
     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);      }
     for(j=nlstate+1; j<=(nlstate+ndeath);j++){               
       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));      /* This for computing probability of death (h=1 means
       for(i=1; i<=nlstate;i++){         computed over hstepm (estepm) matrices product = hstepm*stepm months)
         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);         as a weighted average of prlim.
       }      */
     }       for(j=nlstate+1;j<=nlstate+ndeath;j++){
     fprintf(ficresprobmorprev,"\n");        for(i=1,gmp[j]=0.;i<= nlstate; i++)
           gmp[j] += prlim[i][i]*p3mat[i][j][1];
     fprintf(ficresvij,"%.0f ",age );      }    
     for(i=1; i<=nlstate;i++)      /* end probability of death */
       for(j=1; j<=nlstate;j++){  
         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
       }      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
     fprintf(ficresvij,"\n");        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
     free_matrix(gp,0,nhstepm,1,nlstate);        for(i=1; i<=nlstate;i++){
     free_matrix(gm,0,nhstepm,1,nlstate);          fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);        }
     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);      }
     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      fprintf(ficresprobmorprev,"\n");
   } /* End age */  
   free_vector(gpp,nlstate+1,nlstate+ndeath);      fprintf(ficresvij,"%.0f ",age );
   free_vector(gmp,nlstate+1,nlstate+ndeath);      for(i=1; i<=nlstate;i++)
   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);        for(j=1; j<=nlstate;j++){
   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/          fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
   fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");        }
   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */      fprintf(ficresvij,"\n");
   fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");      free_matrix(gp,0,nhstepm,1,nlstate);
 /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */      free_matrix(gm,0,nhstepm,1,nlstate);
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));    } /* End age */
   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));    free_vector(gpp,nlstate+1,nlstate+ndeath);
   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));    free_vector(gmp,nlstate+1,nlstate+ndeath);
   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);    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
   /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.png\"> <br>\n", stepm,YEARM,digitp,digit);    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 */    fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
 /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);    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); */
   free_vector(xp,1,npar);  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
   free_matrix(doldm,1,nlstate,1,nlstate);  /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
   free_matrix(dnewm,1,nlstate,1,npar);    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    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);
   fclose(ficresprobmorprev);    /*  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);
   fflush(ficgp);  */
   fflush(fichtm);   /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 }  /* end varevsij */    fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
   
 /************ Variance of prevlim ******************/    free_vector(xp,1,npar);
 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(doldm,1,nlstate,1,nlstate);
 {    free_matrix(dnewm,1,nlstate,1,npar);
   /* Variance of prevalence limit */    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
   double **newm;    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
   double **dnewm,**doldm;    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   int i, j, nhstepm, hstepm;    fclose(ficresprobmorprev);
   int k, cptcode;    fflush(ficgp);
   double *xp;    fflush(fichtm);
   double *gp, *gm;  }  /* end varevsij */
   double **gradg, **trgradg;  
   double age,agelim;  /************ Variance of prevlim ******************/
   int theta;  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[])
     {
   pstamp(ficresvpl);    /* Variance of prevalence limit */
   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
   fprintf(ficresvpl,"# Age");    double **newm;
   for(i=1; i<=nlstate;i++)    double **dnewm,**doldm;
       fprintf(ficresvpl," %1d-%1d",i,i);    int i, j, nhstepm, hstepm;
   fprintf(ficresvpl,"\n");    int k, cptcode;
     double *xp;
   xp=vector(1,npar);    double *gp, *gm;
   dnewm=matrix(1,nlstate,1,npar);    double **gradg, **trgradg;
   doldm=matrix(1,nlstate,1,nlstate);    double age,agelim;
       int theta;
   hstepm=1*YEARM; /* Every year of age */   
   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */     pstamp(ficresvpl);
   agelim = AGESUP;    fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */    fprintf(ficresvpl,"# Age");
     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */     for(i=1; i<=nlstate;i++)
     if (stepm >= YEARM) hstepm=1;        fprintf(ficresvpl," %1d-%1d",i,i);
     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */    fprintf(ficresvpl,"\n");
     gradg=matrix(1,npar,1,nlstate);  
     gp=vector(1,nlstate);    xp=vector(1,npar);
     gm=vector(1,nlstate);    dnewm=matrix(1,nlstate,1,npar);
     doldm=matrix(1,nlstate,1,nlstate);
     for(theta=1; theta <=npar; theta++){   
       for(i=1; i<=npar; i++){ /* Computes gradient */    hstepm=1*YEARM; /* Every year of age */
         xp[i] = x[i] + (i==theta ?delti[theta]:0);    hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
       }    agelim = AGESUP;
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);    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 */
         gp[i] = prlim[i][i];      if (stepm >= YEARM) hstepm=1;
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
       for(i=1; i<=npar; i++) /* Computes gradient */      gradg=matrix(1,npar,1,nlstate);
         xp[i] = x[i] - (i==theta ?delti[theta]:0);      gp=vector(1,nlstate);
       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);      gm=vector(1,nlstate);
       for(i=1;i<=nlstate;i++)  
         gm[i] = prlim[i][i];      for(theta=1; theta <=npar; theta++){
         for(i=1; i<=npar; i++){ /* Computes gradient */
       for(i=1;i<=nlstate;i++)          xp[i] = x[i] + (i==theta ?delti[theta]:0);
         gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];        }
     } /* End theta */        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(i=1;i<=nlstate;i++)
     trgradg =matrix(1,nlstate,1,npar);          gp[i] = prlim[i][i];
      
     for(j=1; j<=nlstate;j++)        for(i=1; i<=npar; i++) /* Computes gradient */
       for(theta=1; theta <=npar; theta++)          xp[i] = x[i] - (i==theta ?delti[theta]:0);
         trgradg[j][theta]=gradg[theta][j];        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
         for(i=1;i<=nlstate;i++)
     for(i=1;i<=nlstate;i++)          gm[i] = prlim[i][i];
       varpl[i][(int)age] =0.;  
     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);        for(i=1;i<=nlstate;i++)
     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);          gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
     for(i=1;i<=nlstate;i++)      } /* End theta */
       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */  
       trgradg =matrix(1,nlstate,1,npar);
     fprintf(ficresvpl,"%.0f ",age );  
     for(i=1; i<=nlstate;i++)      for(j=1; j<=nlstate;j++)
       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));        for(theta=1; theta <=npar; theta++)
     fprintf(ficresvpl,"\n");          trgradg[j][theta]=gradg[theta][j];
     free_vector(gp,1,nlstate);  
     free_vector(gm,1,nlstate);      for(i=1;i<=nlstate;i++)
     free_matrix(gradg,1,npar,1,nlstate);        varpl[i][(int)age] =0.;
     free_matrix(trgradg,1,nlstate,1,npar);      matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
   } /* End age */      matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
       for(i=1;i<=nlstate;i++)
   free_vector(xp,1,npar);        varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
   free_matrix(doldm,1,nlstate,1,npar);  
   free_matrix(dnewm,1,nlstate,1,nlstate);      fprintf(ficresvpl,"%.0f ",age );
       for(i=1; i<=nlstate;i++)
 }        fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
       fprintf(ficresvpl,"\n");
 /************ Variance of one-step probabilities  ******************/      free_vector(gp,1,nlstate);
 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[])      free_vector(gm,1,nlstate);
 {      free_matrix(gradg,1,npar,1,nlstate);
   int i, j=0,  i1, k1, l1, t, tj;      free_matrix(trgradg,1,nlstate,1,npar);
   int k2, l2, j1,  z1;    } /* End age */
   int k=0,l, cptcode;  
   int first=1, first1;    free_vector(xp,1,npar);
   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;    free_matrix(doldm,1,nlstate,1,npar);
   double **dnewm,**doldm;    free_matrix(dnewm,1,nlstate,1,nlstate);
   double *xp;  
   double *gp, *gm;  }
   double **gradg, **trgradg;  
   double **mu;  /************ Variance of one-step probabilities  ******************/
   double age,agelim, cov[NCOVMAX];  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[])
   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */  {
   int theta;    int i, j=0,  i1, k1, l1, t, tj;
   char fileresprob[FILENAMELENGTH];    int k2, l2, j1,  z1;
   char fileresprobcov[FILENAMELENGTH];    int k=0,l, cptcode;
   char fileresprobcor[FILENAMELENGTH];    int first=1, first1;
     double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
   double ***varpij;    double **dnewm,**doldm;
     double *xp;
   strcpy(fileresprob,"prob");     double *gp, *gm;
   strcat(fileresprob,fileres);    double **gradg, **trgradg;
   if((ficresprob=fopen(fileresprob,"w"))==NULL) {    double **mu;
     printf("Problem with resultfile: %s\n", fileresprob);    double age,agelim, cov[NCOVMAX];
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
   }    int theta;
   strcpy(fileresprobcov,"probcov");     char fileresprob[FILENAMELENGTH];
   strcat(fileresprobcov,fileres);    char fileresprobcov[FILENAMELENGTH];
   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {    char fileresprobcor[FILENAMELENGTH];
     printf("Problem with resultfile: %s\n", fileresprobcov);  
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);    double ***varpij;
   }  
   strcpy(fileresprobcor,"probcor");     strcpy(fileresprob,"prob");
   strcat(fileresprobcor,fileres);    strcat(fileresprob,fileres);
   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
     printf("Problem with resultfile: %s\n", fileresprobcor);      printf("Problem with resultfile: %s\n", fileresprob);
     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
   }    }
   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    strcpy(fileresprobcov,"probcov");
   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);    strcat(fileresprobcov,fileres);
   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);      printf("Problem with resultfile: %s\n", fileresprobcov);
   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);    }
   pstamp(ficresprob);    strcpy(fileresprobcor,"probcor");
   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");    strcat(fileresprobcor,fileres);
   fprintf(ficresprob,"# Age");    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
   pstamp(ficresprobcov);      printf("Problem with resultfile: %s\n", fileresprobcor);
   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
   fprintf(ficresprobcov,"# Age");    }
   pstamp(ficresprobcor);    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
   fprintf(ficresprobcor,"# Age");    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
     fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
     printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
   for(i=1; i<=nlstate;i++)    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
     for(j=1; j<=(nlstate+ndeath);j++){    pstamp(ficresprob);
       fprintf(ficresprob," p%1d-%1d (SE)",i,j);    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
       fprintf(ficresprobcov," p%1d-%1d ",i,j);    fprintf(ficresprob,"# Age");
       fprintf(ficresprobcor," p%1d-%1d ",i,j);    pstamp(ficresprobcov);
     }      fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
  /* fprintf(ficresprob,"\n");    fprintf(ficresprobcov,"# Age");
   fprintf(ficresprobcov,"\n");    pstamp(ficresprobcor);
   fprintf(ficresprobcor,"\n");    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
  */    fprintf(ficresprobcor,"# Age");
  xp=vector(1,npar);  
   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);  
   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));    for(i=1; i<=nlstate;i++)
   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);      for(j=1; j<=(nlstate+ndeath);j++){
   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
   first=1;        fprintf(ficresprobcov," p%1d-%1d ",i,j);
   fprintf(ficgp,"\n# Routine varprob");        fprintf(ficresprobcor," p%1d-%1d ",i,j);
   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");      }  
   fprintf(fichtm,"\n");   /* fprintf(ficresprob,"\n");
     fprintf(ficresprobcov,"\n");
   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);    fprintf(ficresprobcor,"\n");
   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\   */
   file %s<br>\n",optionfilehtmcov);   xp=vector(1,npar);
   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 and drawn. It helps understanding how is the covariance between two incidences.\    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
   fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \    first=1;
 would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \    fprintf(ficgp,"\n# Routine varprob");
 standard deviations wide on each axis. <br>\    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\    fprintf(fichtm,"\n");
  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\  
 To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
     fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
   cov[1]=1;    file %s<br>\n",optionfilehtmcov);
   tj=cptcoveff;    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
   if (cptcovn<1) {tj=1;ncodemax[1]=1;}  and drawn. It helps understanding how is the covariance between two incidences.\
   j1=0;   They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
   for(t=1; t<=tj;t++){    fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
     for(i1=1; i1<=ncodemax[t];i1++){   It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
       j1++;  would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
       if  (cptcovn>0) {  standard deviations wide on each axis. <br>\
         fprintf(ficresprob, "\n#********** Variable ");    Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);   and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
         fprintf(ficresprob, "**********\n#\n");  To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
         fprintf(ficresprobcov, "\n#********** Variable ");   
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    cov[1]=1;
         fprintf(ficresprobcov, "**********\n#\n");    tj=cptcoveff;
             if (cptcovn<1) {tj=1;ncodemax[1]=1;}
         fprintf(ficgp, "\n#********** Variable ");     j1=0;
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);    for(t=1; t<=tj;t++){
         fprintf(ficgp, "**********\n#\n");      for(i1=1; i1<=ncodemax[t];i1++){
                 j1++;
                 if  (cptcovn>0) {
         fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");           fprintf(ficresprob, "\n#********** Variable ");
         for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");          fprintf(ficresprob, "**********\n#\n");
                   fprintf(ficresprobcov, "\n#********** Variable ");
         fprintf(ficresprobcor, "\n#********** Variable ");              for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);          fprintf(ficresprobcov, "**********\n#\n");
         fprintf(ficresprobcor, "**********\n#");             
       }          fprintf(ficgp, "\n#********** Variable ");
                 for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
       for (age=bage; age<=fage; age ++){           fprintf(ficgp, "**********\n#\n");
         cov[2]=age;         
         for (k=1; k<=cptcovn;k++) {         
           cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];          fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable ");
         }          for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];          fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
         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]]];          fprintf(ficresprobcor, "\n#********** Variable ");    
                   for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
         gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));          fprintf(ficresprobcor, "**********\n#");    
         trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);        }
         gp=vector(1,(nlstate)*(nlstate+ndeath));       
         gm=vector(1,(nlstate)*(nlstate+ndeath));        for (age=bage; age<=fage; age ++){
               cov[2]=age;
         for(theta=1; theta <=npar; theta++){          for (k=1; k<=cptcovn;k++) {
           for(i=1; i<=npar; i++)            cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
             xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);          }
                     for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
           pmij(pmmij,cov,ncovmodel,xp,nlstate);          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]]];
           k=0;         
           for(i=1; i<= (nlstate); i++){          gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
             for(j=1; j<=(nlstate+ndeath);j++){          trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
               k=k+1;          gp=vector(1,(nlstate)*(nlstate+ndeath));
               gp[k]=pmmij[i][j];          gm=vector(1,(nlstate)*(nlstate+ndeath));
             }     
           }          for(theta=1; theta <=npar; theta++){
                       for(i=1; i<=npar; i++)
           for(i=1; i<=npar; i++)              xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
             xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);           
                 pmij(pmmij,cov,ncovmodel,xp,nlstate);
           pmij(pmmij,cov,ncovmodel,xp,nlstate);           
           k=0;            k=0;
           for(i=1; i<=(nlstate); i++){            for(i=1; i<= (nlstate); i++){
             for(j=1; j<=(nlstate+ndeath);j++){              for(j=1; j<=(nlstate+ndeath);j++){
               k=k+1;                k=k+1;
               gm[k]=pmmij[i][j];                gp[k]=pmmij[i][j];
             }              }
           }            }
                 
           for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)             for(i=1; i<=npar; i++)
             gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];                xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
         }     
             pmij(pmmij,cov,ncovmodel,xp,nlstate);
         for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)            k=0;
           for(theta=1; theta <=npar; theta++)            for(i=1; i<=(nlstate); i++){
             trgradg[j][theta]=gradg[theta][j];              for(j=1; j<=(nlstate+ndeath);j++){
                         k=k+1;
         matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);                 gm[k]=pmmij[i][j];
         matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);              }
         free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));            }
         free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));       
         free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);            for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
         free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);              gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
           }
         pmij(pmmij,cov,ncovmodel,x,nlstate);  
                   for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
         k=0;            for(theta=1; theta <=npar; theta++)
         for(i=1; i<=(nlstate); i++){              trgradg[j][theta]=gradg[theta][j];
           for(j=1; j<=(nlstate+ndeath);j++){         
             k=k+1;          matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
             mu[k][(int) age]=pmmij[i][j];          matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
           }          free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
         }          free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
         for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)          free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
           for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)          free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
             varpij[i][j][(int)age] = doldm[i][j];  
           pmij(pmmij,cov,ncovmodel,x,nlstate);
         /*printf("\n%d ",(int)age);         
           for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){          k=0;
           printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));          for(i=1; i<=(nlstate); i++){
           fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));            for(j=1; j<=(nlstate+ndeath);j++){
           }*/              k=k+1;
               mu[k][(int) age]=pmmij[i][j];
         fprintf(ficresprob,"\n%d ",(int)age);            }
         fprintf(ficresprobcov,"\n%d ",(int)age);          }
         fprintf(ficresprobcor,"\n%d ",(int)age);          for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
             for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)              varpij[i][j][(int)age] = doldm[i][j];
           fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));  
         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){          /*printf("\n%d ",(int)age);
           fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);            for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
           fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);            printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
         }            fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
         i=0;            }*/
         for (k=1; k<=(nlstate);k++){  
           for (l=1; l<=(nlstate+ndeath);l++){           fprintf(ficresprob,"\n%d ",(int)age);
             i=i++;          fprintf(ficresprobcov,"\n%d ",(int)age);
             fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);          fprintf(ficresprobcor,"\n%d ",(int)age);
             fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);  
             for (j=1; j<=i;j++){          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
               fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);            fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
               fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
             }            fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
           }            fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
         }/* end of loop for state */          }
       } /* end of loop for age */          i=0;
           for (k=1; k<=(nlstate);k++){
       /* Confidence intervalle of pij  */            for (l=1; l<=(nlstate+ndeath);l++){
       /*              i=i++;
         fprintf(ficgp,"\nset noparametric;unset label");              fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
         fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");              fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");              for (j=1; j<=i;j++){
         fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
         fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
         fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);              }
         fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);            }
       */          }/* end of loop for state */
         } /* end of loop for age */
       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/  
       first1=1;        /* Confidence intervalle of pij  */
       for (k2=1; k2<=(nlstate);k2++){        /*
         for (l2=1; l2<=(nlstate+ndeath);l2++){           fprintf(ficgp,"\nset noparametric;unset label");
           if(l2==k2) continue;          fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
           j=(k2-1)*(nlstate+ndeath)+l2;          fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
           for (k1=1; k1<=(nlstate);k1++){          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 (l1=1; l1<=(nlstate+ndeath);l1++){           fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
               if(l1==k1) continue;          fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
               i=(k1-1)*(nlstate+ndeath)+l1;          fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
               if(i<=j) continue;        */
               for (age=bage; age<=fage; age ++){   
                 if ((int)age %5==0){        /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;        first1=1;
                   v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;        for (k2=1; k2<=(nlstate);k2++){
                   cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;          for (l2=1; l2<=(nlstate+ndeath);l2++){
                   mu1=mu[i][(int) age]/stepm*YEARM ;            if(l2==k2) continue;
                   mu2=mu[j][(int) age]/stepm*YEARM;            j=(k2-1)*(nlstate+ndeath)+l2;
                   c12=cv12/sqrt(v1*v2);            for (k1=1; k1<=(nlstate);k1++){
                   /* Computing eigen value of matrix of covariance */              for (l1=1; l1<=(nlstate+ndeath);l1++){
                   lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;                if(l1==k1) continue;
                   lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;                i=(k1-1)*(nlstate+ndeath)+l1;
                   /* Eigen vectors */                if(i<=j) continue;
                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));                for (age=bage; age<=fage; age ++){
                   /*v21=sqrt(1.-v11*v11); *//* error */                  if ((int)age %5==0){
                   v21=(lc1-v1)/cv12*v11;                    v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   v12=-v21;                    v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   v22=v11;                    cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   tnalp=v21/v11;                    mu1=mu[i][(int) age]/stepm*YEARM ;
                   if(first1==1){                    mu2=mu[j][(int) age]/stepm*YEARM;
                     first1=0;                    c12=cv12/sqrt(v1*v2);
                     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);                    /* Computing eigen value of matrix of covariance */
                   }                    lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   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);                    lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   /*printf(fignu*/                    /* Eigen vectors */
                   /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */                    v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */                    /*v21=sqrt(1.-v11*v11); *//* error */
                   if(first==1){                    v21=(lc1-v1)/cv12*v11;
                     first=0;                    v12=-v21;
                     fprintf(ficgp,"\nset parametric;unset label");                    v22=v11;
                     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);                    tnalp=v21/v11;
                     fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");                    if(first1==1){
                     fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\                      first1=0;
  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\                      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);
 %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\                    }
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\                    fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
                             subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    /*printf(fignu*/
                     fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                     fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);                    /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                     fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                    if(first==1){
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                      first=0;
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                      fprintf(ficgp,"\nset parametric;unset label");
                     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(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);
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                      fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                      fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   }else{   :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                     first=0;  %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                     fprintf(fichtmcov," %d (%.3f),",(int) age, c12);                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                     fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);                              subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                     fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);                      fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                     fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\                      fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                             mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\                      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                             mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   }/* if first */                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                 } /* age mod 5 */                      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",\
               } /* end loop age */                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
               fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
               first=1;                    }else{
             } /*l12 */                      first=0;
           } /* k12 */                      fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
         } /*l1 */                      fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
       }/* k1 */                      fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
     } /* loop covariates */                      fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",\
   }                              mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);                              mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);                    }/* if first */
   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));                  } /* age mod 5 */
   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);                } /* end loop age */
   free_vector(xp,1,npar);                fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
   fclose(ficresprob);                first=1;
   fclose(ficresprobcov);              } /*l12 */
   fclose(ficresprobcor);            } /* k12 */
   fflush(ficgp);          } /*l1 */
   fflush(fichtmcov);        }/* k1 */
 }      } /* loop covariates */
     }
     free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 /******************* Printing html file ***********/    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   int lastpass, int stepm, int weightopt, char model[],\    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   int imx,int jmin, int jmax, double jmeanint,char rfileres[],\    free_vector(xp,1,npar);
                   int popforecast, int estepm ,\    fclose(ficresprob);
                   double jprev1, double mprev1,double anprev1, \    fclose(ficresprobcov);
                   double jprev2, double mprev2,double anprev2){    fclose(ficresprobcor);
   int jj1, k1, i1, cpt;    fflush(ficgp);
     fflush(fichtmcov);
    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \  }
    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \  
 </ul>");  
    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \  /******************* Printing html file ***********/
  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",  void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
            jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));                    int lastpass, int stepm, int weightopt, char model[],\
    fprintf(fichtm,"\                    int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",                    int popforecast, int estepm ,\
            stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));                    double jprev1, double mprev1,double anprev1, \
    fprintf(fichtm,"\                    double jprev2, double mprev2,double anprev2){
  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",    int jj1, k1, i1, cpt;
            subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));  
    fprintf(fichtm,"\     fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
  - (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): \     <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
    <a href=\"%s\">%s</a> <br>\n</li>",  </ul>");
            estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));     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 ",
              jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");     fprintf(fichtm,"\
    - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
  m=cptcoveff;             stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}     fprintf(fichtm,"\
    - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
  jj1=0;             subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
  for(k1=1; k1<=m;k1++){     fprintf(fichtm,"\
    for(i1=1; i1<=ncodemax[k1];i1++){   - (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): \
      jj1++;     <a href=\"%s\">%s</a> <br>\n",
      if (cptcovn > 0) {             estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");     fprintf(fichtm,"\
        for (cpt=1; cpt<=cptcoveff;cpt++)    - Population projections by age and states: \
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);     <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");  
      }  fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
      /* 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> \   m=cptcoveff;
 <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);        if (cptcovn < 1) {m=1;ncodemax[1]=1;}
      /* Quasi-incidences */  
      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\   jj1=0;
  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \   for(k1=1; k1<=m;k1++){
 <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);      for(i1=1; i1<=ncodemax[k1];i1++){
        /* Period (stable) prevalence in each health state */       jj1++;
        for(cpt=1; cpt<nlstate;cpt++){       if (cptcovn > 0) {
          fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);         for (cpt=1; cpt<=cptcoveff;cpt++)
        }           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
      for(cpt=1; cpt<=nlstate;cpt++) {         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
         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);       /* 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> \
    } /* end i1 */  <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);    
  }/* End k1 */       /* Quasi-incidences */
  fprintf(fichtm,"</ul>");       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> \
   <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
  fprintf(fichtm,"\         /* Period (stable) prevalence in each health state */
 \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\         for(cpt=1; cpt<nlstate;cpt++){
  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);           fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
   <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",         }
          subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));       for(cpt=1; cpt<=nlstate;cpt++) {
  fprintf(fichtm,"\          fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
          subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));       }
      } /* end i1 */
  fprintf(fichtm,"\   }/* End k1 */
  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",   fprintf(fichtm,"</ul>");
          subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));  
  fprintf(fichtm,"\  
  - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \   fprintf(fichtm,"\
    <a href=\"%s\">%s</a> <br>\n</li>",  \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
            estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));   - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
  fprintf(fichtm,"\  
  - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \   fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
    <a href=\"%s\">%s</a> <br>\n</li>",           subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
            estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));   fprintf(fichtm,"\
  fprintf(fichtm,"\   - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
  - 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",           subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
          estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));  
  fprintf(fichtm,"\   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",   - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
          subdirf2(fileres,"t"),subdirf2(fileres,"t"));           subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
  fprintf(fichtm,"\   fprintf(fichtm,"\
  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\   - 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): \
          subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));     <a href=\"%s\">%s</a> <br>\n</li>",
              estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 /*  if(popforecast==1) fprintf(fichtm,"\n */   fprintf(fichtm,"\
 /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */   - (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): \
 /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */     <a href=\"%s\">%s</a> <br>\n</li>",
 /*      <br>",fileres,fileres,fileres,fileres); */             estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 /*  else  */   fprintf(fichtm,"\
 /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */   - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), eij are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences (i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
  fflush(fichtm);           estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");   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",
  m=cptcoveff;           subdirf2(fileres,"t"),subdirf2(fileres,"t"));
  if (cptcovn < 1) {m=1;ncodemax[1]=1;}   fprintf(fichtm,"\
    - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
  jj1=0;           subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
  for(k1=1; k1<=m;k1++){  
    for(i1=1; i1<=ncodemax[k1];i1++){  /*  if(popforecast==1) fprintf(fichtm,"\n */
      jj1++;  /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
      if (cptcovn > 0) {  /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");  /*      <br>",fileres,fileres,fileres,fileres); */
        for (cpt=1; cpt<=cptcoveff;cpt++)   /*  else  */
          fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);  /*    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); */
        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");   fflush(fichtm);
      }   fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
      for(cpt=1; cpt<=nlstate;cpt++) {  
        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \   m=cptcoveff;
 prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\   if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);    
      }   jj1=0;
      fprintf(fichtm,"\n<br>- Total life expectancy by age and \   for(k1=1; k1<=m;k1++){
 health expectancies in states (1) and (2): %s%d.png<br>\     for(i1=1; i1<=ncodemax[k1];i1++){
 <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);       jj1++;
    } /* end i1 */       if (cptcovn > 0) {
  }/* End k1 */         fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
  fprintf(fichtm,"</ul>");         for (cpt=1; cpt<=cptcoveff;cpt++)
  fflush(fichtm);           fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 }         fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        }
 /******************* Gnuplot file **************/       for(cpt=1; cpt<=nlstate;cpt++) {
 void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){         fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
   prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
   char dirfileres[132],optfileres[132];  <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;       }
   int ng;       fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */  health expectancies in states (1) and (2): %s%d.png<br>\
 /*     printf("Problem with file %s",optionfilegnuplot); */  <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */     } /* end i1 */
 /*   } */   }/* End k1 */
    fprintf(fichtm,"</ul>");
   /*#ifdef windows */   fflush(fichtm);
   fprintf(ficgp,"cd \"%s\" \n",pathc);  }
     /*#endif */  
   m=pow(2,cptcoveff);  /******************* Gnuplot file **************/
   void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   strcpy(dirfileres,optionfilefiname);  
   strcpy(optfileres,"vpl");    char dirfileres[132],optfileres[132];
  /* 1eme*/    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
   for (cpt=1; cpt<= nlstate ; cpt ++) {    int ng;
    for (k1=1; k1<= m ; k1 ++) {  /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);  /*     printf("Problem with file %s",optionfilegnuplot); */
      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);  /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
      fprintf(ficgp,"set xlabel \"Age\" \n\  /*   } */
 set ylabel \"Probability\" \n\  
 set ter png small\n\    /*#ifdef windows */
 set size 0.65,0.65\n\    fprintf(ficgp,"cd \"%s\" \n",pathc);
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);      /*#endif */
     m=pow(2,cptcoveff);
      for (i=1; i<= nlstate ; i ++) {  
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");    strcpy(dirfileres,optionfilefiname);
        else fprintf(ficgp," \%%*lf (\%%*lf)");    strcpy(optfileres,"vpl");
      }   /* 1eme*/
      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);    for (cpt=1; cpt<= nlstate ; cpt ++) {
      for (i=1; i<= nlstate ; i ++) {     for (k1=1; k1<= m ; k1 ++) {
        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
        else fprintf(ficgp," \%%*lf (\%%*lf)");       fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
      }        fprintf(ficgp,"set xlabel \"Age\" \n\
      fprintf(ficgp,"\" t\"95\%% CI\" w l 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);   set ylabel \"Probability\" \n\
      for (i=1; i<= nlstate ; i ++) {  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:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
      }    
      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 ++) {
    }         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
   }         else fprintf(ficgp," \%%*lf (\%%*lf)");
   /*2 eme*/       }
          fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
   for (k1=1; k1<= m ; k1 ++) {        for (i=1; i<= nlstate ; i ++) {
     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);         else fprintf(ficgp," \%%*lf (\%%*lf)");
            }
     for (i=1; i<= nlstate+1 ; i ++) {       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);
       k=2*i;       for (i=1; i<= nlstate ; i ++) {
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);         if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
       for (j=1; j<= nlstate+1 ; j ++) {         else fprintf(ficgp," \%%*lf (\%%*lf)");
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");       }  
         else fprintf(ficgp," \%%*lf (\%%*lf)");       fprintf(ficgp,"\" t\"\" w l 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
       }        }
       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");    }
       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);    /*2 eme*/
       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 ++) {    for (k1=1; k1<= m ; k1 ++) {
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");      fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
         else fprintf(ficgp," \%%*lf (\%%*lf)");      fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
       }        
       fprintf(ficgp,"\" t\"\" w l 0,");      for (i=1; i<= nlstate+1 ; i ++) {
       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);        k=2*i;
       for (j=1; j<= nlstate+1 ; j ++) {        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
         if (j==i) fprintf(ficgp," \%%lf (\%%lf)");        for (j=1; j<= nlstate+1 ; j ++) {
         else fprintf(ficgp," \%%*lf (\%%*lf)");          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       }             else fprintf(ficgp," \%%*lf (\%%*lf)");
       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");        }  
       else fprintf(ficgp,"\" t\"\" w l 0,");        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
     }        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-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 ++) {
   /*3eme*/          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
             else fprintf(ficgp," \%%*lf (\%%*lf)");
   for (k1=1; k1<= m ; k1 ++) {         }  
     for (cpt=1; cpt<= nlstate ; cpt ++) {        fprintf(ficgp,"\" t\"\" w l 0,");
       /*       k=2+nlstate*(2*cpt-2); */        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
       k=2+(nlstate+1)*(cpt-1);        for (j=1; j<= nlstate+1 ; j ++) {
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);          if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
       fprintf(ficgp,"set ter png small\n\          else fprintf(ficgp," \%%*lf (\%%*lf)");
 set size 0.65,0.65\n\        }  
 plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);        else fprintf(ficgp,"\" t\"\" w l 0,");
         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) ");    /*3eme*/
         fprintf(ficgp,"\" t \"e%d1\" w l",cpt);   
             for (k1=1; k1<= m ; k1 ++) {
       */      for (cpt=1; cpt<= nlstate ; cpt ++) {
       for (i=1; i< nlstate ; i ++) {        /*       k=2+nlstate*(2*cpt-2); */
         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);        k=2+(nlstate+1)*(cpt-1);
         /*      fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
                 fprintf(ficgp,"set ter png small\n\
       }   set size 0.65,0.65\n\
       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);  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);
   /* CV preval stable (period) */          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
   for (k1=1; k1<= m ; k1 ++) {           for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
     for (cpt=1; cpt<=nlstate ; cpt ++) {          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
       k=3;         
       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);        */
       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\        for (i=1; i< nlstate ; i ++) {
 set ter png small\nset size 0.65,0.65\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);
 unset log y\n\          /*      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);*/
 plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);         
               }
       for (i=1; i< nlstate ; i ++)        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
         fprintf(ficgp,"+$%d",k+i+1);      }
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);    }
          
       l=3+(nlstate+ndeath)*cpt;    /* CV preval stable (period) */
       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);    for (k1=1; k1<= m ; k1 ++) {
       for (i=1; i< nlstate ; i ++) {      for (cpt=1; cpt<=nlstate ; cpt ++) {
         l=3+(nlstate+ndeath)*cpt;        k=3;
         fprintf(ficgp,"+$%d",l+i+1);        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
       }        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);     set ter png small\nset size 0.65,0.65\n\
     }   unset log y\n\
   }    plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
          
   /* proba elementaires */        for (i=1; i< nlstate ; i ++)
   for(i=1,jk=1; i <=nlstate; i++){          fprintf(ficgp,"+$%d",k+i+1);
     for(k=1; k <=(nlstate+ndeath); k++){        fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
       if (k != i) {       
         for(j=1; j <=ncovmodel; j++){        l=3+(nlstate+ndeath)*cpt;
           fprintf(ficgp,"p%d=%f ",jk,p[jk]);        fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
           jk++;         for (i=1; i< nlstate ; i ++) {
           fprintf(ficgp,"\n");          l=3+(nlstate+ndeath)*cpt;
         }          fprintf(ficgp,"+$%d",l+i+1);
       }        }
     }        fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);  
    }      }
     }  
    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/   
      for(jk=1; jk <=m; jk++) {    /* proba elementaires */
        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);     for(i=1,jk=1; i <=nlstate; i++){
        if (ng==2)      for(k=1; k <=(nlstate+ndeath); k++){
          fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");        if (k != i) {
        else          for(j=1; j <=ncovmodel; j++){
          fprintf(ficgp,"\nset title \"Probability\"\n");            fprintf(ficgp,"p%d=%f ",jk,p[jk]);
        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);            jk++;
        i=1;            fprintf(ficgp,"\n");
        for(k2=1; k2<=nlstate; k2++) {          }
          k3=i;        }
          for(k=1; k<=(nlstate+ndeath); k++) {      }
            if (k != k2){     }
              if(ng==2)  
                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);     for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
              else       for(jk=1; jk <=m; jk++) {
                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);         fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
              ij=1;         if (ng==2)
              for(j=3; j <=ncovmodel; j++) {           fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {         else
                  fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);           fprintf(ficgp,"\nset title \"Probability\"\n");
                  ij++;         fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                }         i=1;
                else         for(k2=1; k2<=nlstate; k2++) {
                  fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);           k3=i;
              }           for(k=1; k<=(nlstate+ndeath); k++) {
              fprintf(ficgp,")/(1");             if (k != k2){
                             if(ng==2)
              for(k1=1; k1 <=nlstate; k1++){                    fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);               else
                ij=1;                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                for(j=3; j <=ncovmodel; j++){               ij=1;
                  if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {               for(j=3; j <=ncovmodel; j++) {
                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                    ij++;                   fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                  }                   ij++;
                  else                 }
                    fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);                 else
                }                   fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                fprintf(ficgp,")");               }
              }               fprintf(ficgp,")/(1");
              fprintf(ficgp,") t \"p%d%d\" ", k2,k);               
              if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");               for(k1=1; k1 <=nlstate; k1++){  
              i=i+ncovmodel;                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
            }                 ij=1;
          } /* end k */                 for(j=3; j <=ncovmodel; j++){
        } /* end k2 */                   if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
      } /* end jk */                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
    } /* end ng */                     ij++;
    fflush(ficgp);                    }
 }  /* end gnuplot */                   else
                      fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                  }
 /*************** Moving average **************/                 fprintf(ficgp,")");
 int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){               }
                fprintf(ficgp,") t \"p%d%d\" ", k2,k);
   int i, cpt, cptcod;               if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
   int modcovmax =1;               i=i+ncovmodel;
   int mobilavrange, mob;             }
   double age;           } /* end k */
          } /* end k2 */
   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose        } /* end jk */
                            a covariate has 2 modalities */     } /* end ng */
   if (cptcovn<1) modcovmax=1; /* At least 1 pass */     fflush(ficgp);
   }  /* end gnuplot */
   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){  
     if(mobilav==1) mobilavrange=5; /* default */  
     else mobilavrange=mobilav;  /*************** Moving average **************/
     for (age=bage; age<=fage; age++)  int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
       for (i=1; i<=nlstate;i++)  
         for (cptcod=1;cptcod<=modcovmax;cptcod++)    int i, cpt, cptcod;
           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];    int modcovmax =1;
     /* We keep the original values on the extreme ages bage, fage and for     int mobilavrange, mob;
        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2    double age;
        we use a 5 terms etc. until the borders are no more concerned.   
     */     modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
     for (mob=3;mob <=mobilavrange;mob=mob+2){                             a covariate has 2 modalities */
       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){    if (cptcovn<1) modcovmax=1; /* At least 1 pass */
         for (i=1; i<=nlstate;i++){  
           for (cptcod=1;cptcod<=modcovmax;cptcod++){    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];      if(mobilav==1) mobilavrange=5; /* default */
               for (cpt=1;cpt<=(mob-1)/2;cpt++){      else mobilavrange=mobilav;
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];      for (age=bage; age<=fage; age++)
                 mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];        for (i=1; i<=nlstate;i++)
               }          for (cptcod=1;cptcod<=modcovmax;cptcod++)
             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;            mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
           }      /* 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
       }/* end age */         we use a 5 terms etc. until the borders are no more concerned.
     }/* end mob */      */
   }else return -1;      for (mob=3;mob <=mobilavrange;mob=mob+2){
   return 0;        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 }/* End movingaverage */          for (i=1; i<=nlstate;i++){
             for (cptcod=1;cptcod<=modcovmax;cptcod++){
               mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 /************** Forecasting ******************/                for (cpt=1;cpt<=(mob-1)/2;cpt++){
 prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){                  mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
   /* proj1, year, month, day of starting projection                   mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
      agemin, agemax range of age                }
      dateprev1 dateprev2 range of dates during which prevalence is computed              mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
      anproj2 year of en of projection (same day and month as proj1).            }
   */          }
   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;        }/* end age */
   int *popage;      }/* end mob */
   double agec; /* generic age */    }else return -1;
   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;    return 0;
   double *popeffectif,*popcount;  }/* End movingaverage */
   double ***p3mat;  
   double ***mobaverage;  
   char fileresf[FILENAMELENGTH];  /************** Forecasting ******************/
   prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
   agelim=AGESUP;    /* proj1, year, month, day of starting projection
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);       agemin, agemax range of age
         dateprev1 dateprev2 range of dates during which prevalence is computed
   strcpy(fileresf,"f");        anproj2 year of en of projection (same day and month as proj1).
   strcat(fileresf,fileres);    */
   if((ficresf=fopen(fileresf,"w"))==NULL) {    int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
     printf("Problem with forecast resultfile: %s\n", fileresf);    int *popage;
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);    double agec; /* generic age */
   }    double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
   printf("Computing forecasting: result on file '%s' \n", fileresf);    double *popeffectif,*popcount;
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);    double ***p3mat;
     double ***mobaverage;
   if (cptcoveff==0) ncodemax[cptcoveff]=1;    char fileresf[FILENAMELENGTH];
   
   if (mobilav!=0) {    agelim=AGESUP;
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){   
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    strcpy(fileresf,"f");
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    strcat(fileresf,fileres);
     }    if((ficresf=fopen(fileresf,"w"))==NULL) {
   }      printf("Problem with forecast resultfile: %s\n", fileresf);
       fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
   stepsize=(int) (stepm+YEARM-1)/YEARM;    }
   if (stepm<=12) stepsize=1;    printf("Computing forecasting: result on file '%s' \n", fileresf);
   if(estepm < stepm){    fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
     printf ("Problem %d lower than %d\n",estepm, stepm);  
   }    if (cptcoveff==0) ncodemax[cptcoveff]=1;
   else  hstepm=estepm;     
     if (mobilav!=0) {
   hstepm=hstepm/stepm;       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                                fractional in yp1 */        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
   anprojmean=yp;        printf(" Error in movingaverage mobilav=%d\n",mobilav);
   yp2=modf((yp1*12),&yp);      }
   mprojmean=yp;    }
   yp1=modf((yp2*30.5),&yp);  
   jprojmean=yp;    stepsize=(int) (stepm+YEARM-1)/YEARM;
   if(jprojmean==0) jprojmean=1;    if (stepm<=12) stepsize=1;
   if(mprojmean==0) jprojmean=1;    if(estepm < stepm){
       printf ("Problem %d lower than %d\n",estepm, stepm);
   i1=cptcoveff;    }
   if (cptcovn < 1){i1=1;}    else  hstepm=estepm;  
     
   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);     hstepm=hstepm/stepm;
       yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
   fprintf(ficresf,"#****** Routine prevforecast **\n");                                 fractional in yp1 */
     anprojmean=yp;
 /*            if (h==(int)(YEARM*yearp)){ */    yp2=modf((yp1*12),&yp);
   for(cptcov=1, k=0;cptcov<=i1;cptcov++){    mprojmean=yp;
     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){    yp1=modf((yp2*30.5),&yp);
       k=k+1;    jprojmean=yp;
       fprintf(ficresf,"\n#******");    if(jprojmean==0) jprojmean=1;
       for(j=1;j<=cptcoveff;j++) {    if(mprojmean==0) jprojmean=1;
         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]]);  
       }    i1=cptcoveff;
       fprintf(ficresf,"******\n");    if (cptcovn < 1){i1=1;}
       fprintf(ficresf,"# Covariate valuofcovar yearproj age");   
       for(j=1; j<=nlstate+ndeath;j++){     fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
         for(i=1; i<=nlstate;i++)                 
           fprintf(ficresf," p%d%d",i,j);    fprintf(ficresf,"#****** Routine prevforecast **\n");
         fprintf(ficresf," p.%d",j);  
       }  /*            if (h==(int)(YEARM*yearp)){ */
       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {     for(cptcov=1, k=0;cptcov<=i1;cptcov++){
         fprintf(ficresf,"\n");      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
         fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);           k=k+1;
         fprintf(ficresf,"\n#******");
         for (agec=fage; agec>=(ageminpar-1); agec--){         for(j=1;j<=cptcoveff;j++) {
           nhstepm=(int) rint((agelim-agec)*YEARM/stepm);           fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           nhstepm = nhstepm/hstepm;         }
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);        fprintf(ficresf,"******\n");
           oldm=oldms;savm=savms;        fprintf(ficresf,"# Covariate valuofcovar yearproj age");
           hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);          for(j=1; j<=nlstate+ndeath;j++){
                   for(i=1; i<=nlstate;i++)              
           for (h=0; h<=nhstepm; h++){            fprintf(ficresf," p%d%d",i,j);
             if (h*hstepm/YEARM*stepm ==yearp) {          fprintf(ficresf," p.%d",j);
               fprintf(ficresf,"\n");        }
               for(j=1;j<=cptcoveff;j++)         for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          fprintf(ficresf,"\n");
               fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);          fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);  
             }   
             for(j=1; j<=nlstate+ndeath;j++) {          for (agec=fage; agec>=(ageminpar-1); agec--){
               ppij=0.;            nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
               for(i=1; i<=nlstate;i++) {            nhstepm = nhstepm/hstepm;
                 if (mobilav==1)             p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];            oldm=oldms;savm=savms;
                 else {            hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];         
                 }            for (h=0; h<=nhstepm; h++){
                 if (h*hstepm/YEARM*stepm== yearp) {              if (h*hstepm/YEARM*stepm ==yearp) {
                   fprintf(ficresf," %.3f", p3mat[i][j][h]);                fprintf(ficresf,"\n");
                 }                for(j=1;j<=cptcoveff;j++)
               } /* end i */                  fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
               if (h*hstepm/YEARM*stepm==yearp) {                fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                 fprintf(ficresf," %.3f", ppij);              }
               }              for(j=1; j<=nlstate+ndeath;j++) {
             }/* end j */                ppij=0.;
           } /* end h */                for(i=1; i<=nlstate;i++) {
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                  if (mobilav==1)
         } /* end agec */                    ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
       } /* end yearp */                  else {
     } /* end cptcod */                    ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
   } /* end  cptcov */                  }
                          if (h*hstepm/YEARM*stepm== yearp) {
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);                    fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   }
   fclose(ficresf);                } /* end i */
 }                if (h*hstepm/YEARM*stepm==yearp) {
                   fprintf(ficresf," %.3f", ppij);
 /************** 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){              }/* end j */
               } /* end h */
   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   int *popage;          } /* end agec */
   double calagedatem, agelim, kk1, kk2;        } /* end yearp */
   double *popeffectif,*popcount;      } /* end cptcod */
   double ***p3mat,***tabpop,***tabpopprev;    } /* end  cptcov */
   double ***mobaverage;         
   char filerespop[FILENAMELENGTH];    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   
   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);    fclose(ficresf);
   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);  }
   agelim=AGESUP;  
   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;  /************** 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){
   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);   
       int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
       int *popage;
   strcpy(filerespop,"pop");     double calagedatem, agelim, kk1, kk2;
   strcat(filerespop,fileres);    double *popeffectif,*popcount;
   if((ficrespop=fopen(filerespop,"w"))==NULL) {    double ***p3mat,***tabpop,***tabpopprev;
     printf("Problem with forecast resultfile: %s\n", filerespop);    double ***mobaverage;
     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);    char filerespop[FILENAMELENGTH];
   }  
   printf("Computing forecasting: result on file '%s' \n", filerespop);    tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);    tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     agelim=AGESUP;
   if (cptcoveff==0) ncodemax[cptcoveff]=1;    calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
    
   if (mobilav!=0) {    prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);   
     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){   
       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);    strcpy(filerespop,"pop");
       printf(" Error in movingaverage mobilav=%d\n",mobilav);    strcat(filerespop,fileres);
     }    if((ficrespop=fopen(filerespop,"w"))==NULL) {
   }      printf("Problem with forecast resultfile: %s\n", filerespop);
       fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
   stepsize=(int) (stepm+YEARM-1)/YEARM;    }
   if (stepm<=12) stepsize=1;    printf("Computing forecasting: result on file '%s' \n", filerespop);
       fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
   agelim=AGESUP;  
       if (cptcoveff==0) ncodemax[cptcoveff]=1;
   hstepm=1;  
   hstepm=hstepm/stepm;     if (mobilav!=0) {
         mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
   if (popforecast==1) {      if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
     if((ficpop=fopen(popfile,"r"))==NULL) {        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
       printf("Problem with population file : %s\n",popfile);exit(0);        printf(" Error in movingaverage mobilav=%d\n",mobilav);
       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);      }
     }     }
     popage=ivector(0,AGESUP);  
     popeffectif=vector(0,AGESUP);    stepsize=(int) (stepm+YEARM-1)/YEARM;
     popcount=vector(0,AGESUP);    if (stepm<=12) stepsize=1;
        
     i=1;       agelim=AGESUP;
     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;   
        hstepm=1;
     imx=i;    hstepm=hstepm/stepm;
     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];   
   }    if (popforecast==1) {
       if((ficpop=fopen(popfile,"r"))==NULL) {
   for(cptcov=1,k=0;cptcov<=i2;cptcov++){        printf("Problem with population file : %s\n",popfile);exit(0);
    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){        fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
       k=k+1;      }
       fprintf(ficrespop,"\n#******");      popage=ivector(0,AGESUP);
       for(j=1;j<=cptcoveff;j++) {      popeffectif=vector(0,AGESUP);
         fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      popcount=vector(0,AGESUP);
       }     
       fprintf(ficrespop,"******\n");      i=1;  
       fprintf(ficrespop,"# Age");      while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);     
       if (popforecast==1)  fprintf(ficrespop," [Population]");      imx=i;
             for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
       for (cpt=0; cpt<=0;cpt++) {     }
         fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);     
             for(cptcov=1,k=0;cptcov<=i2;cptcov++){
         for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){      for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);         k=k+1;
           nhstepm = nhstepm/hstepm;         fprintf(ficrespop,"\n#******");
                   for(j=1;j<=cptcoveff;j++) {
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);          fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           oldm=oldms;savm=savms;        }
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);          fprintf(ficrespop,"******\n");
                 fprintf(ficrespop,"# Age");
           for (h=0; h<=nhstepm; h++){        for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
             if (h==(int) (calagedatem+YEARM*cpt)) {        if (popforecast==1)  fprintf(ficrespop," [Population]");
               fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);       
             }         for (cpt=0; cpt<=0;cpt++) {
             for(j=1; j<=nlstate+ndeath;j++) {          fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
               kk1=0.;kk2=0;         
               for(i=1; i<=nlstate;i++) {                        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
                 if (mobilav==1)             nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
                   kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];            nhstepm = nhstepm/hstepm;
                 else {           
                   kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                 }            oldm=oldms;savm=savms;
               }            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
               if (h==(int)(calagedatem+12*cpt)){         
                 tabpop[(int)(agedeb)][j][cptcod]=kk1;            for (h=0; h<=nhstepm; h++){
                   /*fprintf(ficrespop," %.3f", kk1);              if (h==(int) (calagedatem+YEARM*cpt)) {
                     if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/                fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
               }              }
             }              for(j=1; j<=nlstate+ndeath;j++) {
             for(i=1; i<=nlstate;i++){                kk1=0.;kk2=0;
               kk1=0.;                for(i=1; i<=nlstate;i++) {              
                 for(j=1; j<=nlstate;j++){                  if (mobilav==1)
                   kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];                     kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                 }                  else {
                   tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];                    kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
             }                  }
                 }
             if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)                 if (h==(int)(calagedatem+12*cpt)){
               fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);                  tabpop[(int)(agedeb)][j][cptcod]=kk1;
           }                    /*fprintf(ficrespop," %.3f", kk1);
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                      if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
         }                }
       }              }
                for(i=1; i<=nlstate;i++){
   /******/                kk1=0.;
                   for(j=1; j<=nlstate;j++){
       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {                     kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
         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--){                     tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);               }
           nhstepm = nhstepm/hstepm;   
                         if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
           oldm=oldms;savm=savms;            }
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);              free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           for (h=0; h<=nhstepm; h++){          }
             if (h==(int) (calagedatem+YEARM*cpt)) {        }
               fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);   
             }     /******/
             for(j=1; j<=nlstate+ndeath;j++) {  
               kk1=0.;kk2=0;        for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
               for(i=1; i<=nlstate;i++) {                        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);  
                 kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];              for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
               }            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
               if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);                    nhstepm = nhstepm/hstepm;
             }           
           }            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            oldm=oldms;savm=savms;
         }            hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
       }            for (h=0; h<=nhstepm; h++){
    }               if (h==(int) (calagedatem+YEARM*cpt)) {
   }                fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                }
   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);              for(j=1; j<=nlstate+ndeath;j++) {
                 kk1=0.;kk2=0;
   if (popforecast==1) {                for(i=1; i<=nlstate;i++) {              
     free_ivector(popage,0,AGESUP);                  kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
     free_vector(popeffectif,0,AGESUP);                }
     free_vector(popcount,0,AGESUP);                if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
   }              }
   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            }
   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
   fclose(ficrespop);          }
 } /* End of popforecast */        }
      }
 int fileappend(FILE *fichier, char *optionfich)    }
 {   
   if((fichier=fopen(optionfich,"a"))==NULL) {    if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     printf("Problem with file: %s\n", optionfich);  
     fprintf(ficlog,"Problem with file: %s\n", optionfich);    if (popforecast==1) {
     return (0);      free_ivector(popage,0,AGESUP);
   }      free_vector(popeffectif,0,AGESUP);
   fflush(fichier);      free_vector(popcount,0,AGESUP);
   return (1);    }
 }    free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
     fclose(ficrespop);
 /**************** function prwizard **********************/  } /* End of popforecast */
 void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)  
 {  int fileappend(FILE *fichier, char *optionfich)
   {
   /* Wizard to print covariance matrix template */    if((fichier=fopen(optionfich,"a"))==NULL) {
       printf("Problem with file: %s\n", optionfich);
   char ca[32], cb[32], cc[32];      fprintf(ficlog,"Problem with file: %s\n", optionfich);
   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;      return (0);
   int numlinepar;    }
     fflush(fichier);
   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");    return (1);
   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");  }
   for(i=1; i <=nlstate; i++){  
     jj=0;  
     for(j=1; j <=nlstate+ndeath; j++){  /**************** function prwizard **********************/
       if(j==i) continue;  void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
       jj++;  {
       /*ca[0]= k+'a'-1;ca[1]='\0';*/  
       printf("%1d%1d",i,j);    /* Wizard to print covariance matrix template */
       fprintf(ficparo,"%1d%1d",i,j);  
       for(k=1; k<=ncovmodel;k++){    char ca[32], cb[32], cc[32];
         /*        printf(" %lf",param[i][j][k]); */    int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
         /*        fprintf(ficparo," %lf",param[i][j][k]); */    int numlinepar;
         printf(" 0.");  
         fprintf(ficparo," 0.");    printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       }    fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
       printf("\n");    for(i=1; i <=nlstate; i++){
       fprintf(ficparo,"\n");      jj=0;
     }      for(j=1; j <=nlstate+ndeath; j++){
   }        if(j==i) continue;
   printf("# Scales (for hessian or gradient estimation)\n");        jj++;
   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");        /*ca[0]= k+'a'-1;ca[1]='\0';*/
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/         printf("%1d%1d",i,j);
   for(i=1; i <=nlstate; i++){        fprintf(ficparo,"%1d%1d",i,j);
     jj=0;        for(k=1; k<=ncovmodel;k++){
     for(j=1; j <=nlstate+ndeath; j++){          /*        printf(" %lf",param[i][j][k]); */
       if(j==i) continue;          /*        fprintf(ficparo," %lf",param[i][j][k]); */
       jj++;          printf(" 0.");
       fprintf(ficparo,"%1d%1d",i,j);          fprintf(ficparo," 0.");
       printf("%1d%1d",i,j);        }
       fflush(stdout);        printf("\n");
       for(k=1; k<=ncovmodel;k++){        fprintf(ficparo,"\n");
         /*      printf(" %le",delti3[i][j][k]); */      }
         /*      fprintf(ficparo," %le",delti3[i][j][k]); */    }
         printf(" 0.");    printf("# Scales (for hessian or gradient estimation)\n");
         fprintf(ficparo," 0.");    fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
       }    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
       numlinepar++;    for(i=1; i <=nlstate; i++){
       printf("\n");      jj=0;
       fprintf(ficparo,"\n");      for(j=1; j <=nlstate+ndeath; j++){
     }        if(j==i) continue;
   }        jj++;
   printf("# Covariance matrix\n");        fprintf(ficparo,"%1d%1d",i,j);
 /* # 121 Var(a12)\n\ */        printf("%1d%1d",i,j);
 /* # 122 Cov(b12,a12) Var(b12)\n\ */        fflush(stdout);
 /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */        for(k=1; k<=ncovmodel;k++){
 /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */          /*      printf(" %le",delti3[i][j][k]); */
 /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */          /*      fprintf(ficparo," %le",delti3[i][j][k]); */
 /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */          printf(" 0.");
 /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */          fprintf(ficparo," 0.");
 /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */        }
   fflush(stdout);        numlinepar++;
   fprintf(ficparo,"# Covariance matrix\n");        printf("\n");
   /* # 121 Var(a12)\n\ */        fprintf(ficparo,"\n");
   /* # 122 Cov(b12,a12) Var(b12)\n\ */      }
   /* #   ...\n\ */    }
   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */    printf("# Covariance matrix\n");
     /* # 121 Var(a12)\n\ */
   for(itimes=1;itimes<=2;itimes++){  /* # 122 Cov(b12,a12) Var(b12)\n\ */
     jj=0;  /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
     for(i=1; i <=nlstate; i++){  /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
       for(j=1; j <=nlstate+ndeath; j++){  /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
         if(j==i) continue;  /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
         for(k=1; k<=ncovmodel;k++){  /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
           jj++;  /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
           ca[0]= k+'a'-1;ca[1]='\0';    fflush(stdout);
           if(itimes==1){    fprintf(ficparo,"# Covariance matrix\n");
             printf("#%1d%1d%d",i,j,k);    /* # 121 Var(a12)\n\ */
             fprintf(ficparo,"#%1d%1d%d",i,j,k);    /* # 122 Cov(b12,a12) Var(b12)\n\ */
           }else{    /* #   ...\n\ */
             printf("%1d%1d%d",i,j,k);    /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
             fprintf(ficparo,"%1d%1d%d",i,j,k);   
             /*  printf(" %.5le",matcov[i][j]); */    for(itimes=1;itimes<=2;itimes++){
           }      jj=0;
           ll=0;      for(i=1; i <=nlstate; i++){
           for(li=1;li <=nlstate; li++){        for(j=1; j <=nlstate+ndeath; j++){
             for(lj=1;lj <=nlstate+ndeath; lj++){          if(j==i) continue;
               if(lj==li) continue;          for(k=1; k<=ncovmodel;k++){
               for(lk=1;lk<=ncovmodel;lk++){            jj++;
                 ll++;            ca[0]= k+'a'-1;ca[1]='\0';
                 if(ll<=jj){            if(itimes==1){
                   cb[0]= lk +'a'-1;cb[1]='\0';              printf("#%1d%1d%d",i,j,k);
                   if(ll<jj){              fprintf(ficparo,"#%1d%1d%d",i,j,k);
                     if(itimes==1){            }else{
                       printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);              printf("%1d%1d%d",i,j,k);
                       fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);              fprintf(ficparo,"%1d%1d%d",i,j,k);
                     }else{              /*  printf(" %.5le",matcov[i][j]); */
                       printf(" 0.");            }
                       fprintf(ficparo," 0.");            ll=0;
                     }            for(li=1;li <=nlstate; li++){
                   }else{              for(lj=1;lj <=nlstate+ndeath; lj++){
                     if(itimes==1){                if(lj==li) continue;
                       printf(" Var(%s%1d%1d)",ca,i,j);                for(lk=1;lk<=ncovmodel;lk++){
                       fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);                  ll++;
                     }else{                  if(ll<=jj){
                       printf(" 0.");                    cb[0]= lk +'a'-1;cb[1]='\0';
                       fprintf(ficparo," 0.");                    if(ll<jj){
                     }                      if(itimes==1){
                   }                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                 }                        fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
               } /* end lk */                      }else{
             } /* end lj */                        printf(" 0.");
           } /* end li */                        fprintf(ficparo," 0.");
           printf("\n");                      }
           fprintf(ficparo,"\n");                    }else{
           numlinepar++;                      if(itimes==1){
         } /* end k*/                        printf(" Var(%s%1d%1d)",ca,i,j);
       } /*end j */                        fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
     } /* end i */                      }else{
   } /* end itimes */                        printf(" 0.");
                         fprintf(ficparo," 0.");
 } /* end of prwizard */                      }
 /******************* Gompertz Likelihood ******************************/                    }
 double gompertz(double x[])                  }
 {                 } /* end lk */
   double A,B,L=0.0,sump=0.,num=0.;              } /* end lj */
   int i,n=0; /* n is the size of the sample */            } /* end li */
             printf("\n");
   for (i=0;i<=imx-1 ; i++) {            fprintf(ficparo,"\n");
     sump=sump+weight[i];            numlinepar++;
     /*    sump=sump+1;*/          } /* end k*/
     num=num+1;        } /*end j */
   }      } /* end i */
      } /* end itimes */
    
   /* for (i=0; i<=imx; i++)   } /* end of prwizard */
      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]);*/  /******************* Gompertz Likelihood ******************************/
   double gompertz(double x[])
   for (i=1;i<=imx ; i++)  {
     {    double A,B,L=0.0,sump=0.,num=0.;
       if (cens[i] == 1 && wav[i]>1)    int i,n=0; /* n is the size of the sample */
         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));  
           for (i=0;i<=imx-1 ; i++) {
       if (cens[i] == 0 && wav[i]>1)      sump=sump+weight[i];
         A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))      /*    sump=sump+1;*/
              +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);        num=num+1;
           }
       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */   
       if (wav[i] > 1 ) { /* ??? */   
         L=L+A*weight[i];    /* for (i=0; i<=imx; i++)
         /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/       if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
       }  
     }    for (i=1;i<=imx ; i++)
       {
  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/        if (cens[i] == 1 && wav[i]>1)
            A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
   return -2*L*num/sump;       
 }        if (cens[i] == 0 && wav[i]>1)
           A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 /******************* Printing html file ***********/               +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \       
                   int lastpass, int stepm, int weightopt, char model[],\        /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   int imx,  double p[],double **matcov,double agemortsup){        if (wav[i] > 1 ) { /* ??? */
   int i,k;          L=L+A*weight[i];
           /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");        }
   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);      }
   for (i=1;i<=2;i++)   
     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]));   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");   
   fprintf(fichtm,"</ul>");    return -2*L*num/sump;
   }
 fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");  
   /******************* Printing html file ***********/
  fprintf(fichtm,"\nAge   l<inf>x</inf>     q<inf>x</inf> d(x,x+1)    L<inf>x</inf>     T<inf>x</inf>     e<infx</inf><br>");  void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                     int lastpass, int stepm, int weightopt, char model[],\
  for (k=agegomp;k<(agemortsup-2);k++)                     int imx,  double p[],double **matcov,double agemortsup){
    fprintf(fichtm,"%d %.0lf %lf %.0lf %.0lf %.0lf %lf<br>\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);    int i,k;
   
      fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
   fflush(fichtm);    fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 }    for (i=1;i<=2;i++)
       fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 /******************* Gnuplot file **************/    fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){    fprintf(fichtm,"</ul>");
   
   char dirfileres[132],optfileres[132];  fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;  
   int ng;   fprintf(fichtm,"\nAge   l<inf>x</inf>     q<inf>x</inf> d(x,x+1)    L<inf>x</inf>     T<inf>x</inf>     e<infx</inf><br>");
   
    for (k=agegomp;k<(agemortsup-2);k++)
   /*#ifdef windows */     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]);
   fprintf(ficgp,"cd \"%s\" \n",pathc);  
     /*#endif */   
     fflush(fichtm);
   }
   strcpy(dirfileres,optionfilefiname);  
   strcpy(optfileres,"vpl");  /******************* Gnuplot file **************/
   fprintf(ficgp,"set out \"graphmort.png\"\n ");   void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");   
   fprintf(ficgp, "set ter png small\n set log y\n");     char dirfileres[132],optfileres[132];
   fprintf(ficgp, "set size 0.65,0.65\n");    int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);    int ng;
   
 }   
     /*#ifdef windows */
     fprintf(ficgp,"cd \"%s\" \n",pathc);
       /*#endif */
   
   
 /***********************************************/    strcpy(dirfileres,optionfilefiname);
 /**************** Main Program *****************/    strcpy(optfileres,"vpl");
 /***********************************************/    fprintf(ficgp,"set out \"graphmort.png\"\n ");
     fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
 int main(int argc, char *argv[])    fprintf(ficgp, "set ter png small\n set log y\n");
 {    fprintf(ficgp, "set size 0.65,0.65\n");
   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);    fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;  
   int linei, month, year,iout;  }
   int jj, ll, li, lj, lk, imk;  
   int numlinepar=0; /* Current linenumber of parameter file */  
   int itimes;  
   int NDIM=2;  
   
   char ca[32], cb[32], cc[32];  /***********************************************/
   char dummy[]="                         ";  /**************** Main Program *****************/
   /*  FILE *fichtm; *//* Html File */  /***********************************************/
   /* FILE *ficgp;*/ /*Gnuplot File */  
   struct stat info;  int main(int argc, char *argv[])
   double agedeb, agefin,hf;  {
   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;    int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
     int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
   double fret;    int linei, month, year,iout;
   double **xi,tmp,delta;    int jj, ll, li, lj, lk, imk;
     int numlinepar=0; /* Current linenumber of parameter file */
   double dum; /* Dummy variable */    int itimes;
   double ***p3mat;    int NDIM=2;
   double ***mobaverage;  
   int *indx;    char ca[32], cb[32], cc[32];
   char line[MAXLINE], linepar[MAXLINE];    char dummy[]="                         ";
   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];    /*  FILE *fichtm; *//* Html File */
   char pathr[MAXLINE], pathimach[MAXLINE];     /* FILE *ficgp;*/ /*Gnuplot File */
   char **bp, *tok, *val; /* pathtot */    struct stat info;
   int firstobs=1, lastobs=10;    double agedeb, agefin,hf;
   int sdeb, sfin; /* Status at beginning and end */    double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
   int c,  h , cpt,l;  
   int ju,jl, mi;    double fret;
   int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;    double **xi,tmp,delta;
   int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;   
   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */    double dum; /* Dummy variable */
   int mobilav=0,popforecast=0;    double ***p3mat;
   int hstepm, nhstepm;    double ***mobaverage;
   int agemortsup;    int *indx;
   float  sumlpop=0.;    char line[MAXLINE], linepar[MAXLINE];
   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;    char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;    char pathr[MAXLINE], pathimach[MAXLINE];
     char **bp, *tok, *val; /* pathtot */
   double bage, fage, age, agelim, agebase;    int firstobs=1, lastobs=10;
   double ftolpl=FTOL;    int sdeb, sfin; /* Status at beginning and end */
   double **prlim;    int c,  h , cpt,l;
   double *severity;    int ju,jl, mi;
   double ***param; /* Matrix of parameters */    int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
   double  *p;    int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
   double **matcov; /* Matrix of covariance */    int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
   double ***delti3; /* Scale */    int mobilav=0,popforecast=0;
   double *delti; /* Scale */    int hstepm, nhstepm;
   double ***eij, ***vareij;    int agemortsup;
   double **varpl; /* Variances of prevalence limits by age */    float  sumlpop=0.;
   double *epj, vepp;    double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
   double kk1, kk2;    double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;  
   double **ximort;    double bage, fage, age, agelim, agebase;
   char *alph[]={"a","a","b","c","d","e"}, str[4];    double ftolpl=FTOL;
   int *dcwave;    double **prlim;
     double *severity;
   char z[1]="c", occ;    double ***param; /* Matrix of parameters */
     double  *p;
   char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];    double **matcov; /* Matrix of covariance */
   char  *strt, strtend[80];    double ***delti3; /* Scale */
   char *stratrunc;    double *delti; /* Scale */
   int lstra;    double ***eij, ***vareij;
     double **varpl; /* Variances of prevalence limits by age */
   long total_usecs;    double *epj, vepp;
      double kk1, kk2;
 /*   setlocale (LC_ALL, ""); */    double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 /*   bindtextdomain (PACKAGE, LOCALEDIR); */    double **ximort;
 /*   textdomain (PACKAGE); */    char *alph[]={"a","a","b","c","d","e"}, str[4];
 /*   setlocale (LC_CTYPE, ""); */    int *dcwave;
 /*   setlocale (LC_MESSAGES, ""); */  
     char z[1]="c", occ;
   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */  
   (void) gettimeofday(&start_time,&tzp);    char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
   curr_time=start_time;    char  *strt, strtend[80];
   tm = *localtime(&start_time.tv_sec);    char *stratrunc;
   tmg = *gmtime(&start_time.tv_sec);    int lstra;
   strcpy(strstart,asctime(&tm));  
     long total_usecs;
 /*  printf("Localtime (at start)=%s",strstart); */   
 /*  tp.tv_sec = tp.tv_sec +86400; */  /*   setlocale (LC_ALL, ""); */
 /*  tm = *localtime(&start_time.tv_sec); */  /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */  /*   textdomain (PACKAGE); */
 /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */  /*   setlocale (LC_CTYPE, ""); */
 /*   tmg.tm_hour=tmg.tm_hour + 1; */  /*   setlocale (LC_MESSAGES, ""); */
 /*   tp.tv_sec = mktime(&tmg); */  
 /*   strt=asctime(&tmg); */    /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 /*   printf("Time(after) =%s",strstart);  */    (void) gettimeofday(&start_time,&tzp);
 /*  (void) time (&time_value);    curr_time=start_time;
 *  printf("time=%d,t-=%d\n",time_value,time_value-86400);    tm = *localtime(&start_time.tv_sec);
 *  tm = *localtime(&time_value);    tmg = *gmtime(&start_time.tv_sec);
 *  strstart=asctime(&tm);    strcpy(strstart,asctime(&tm));
 *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);   
 */  /*  printf("Localtime (at start)=%s",strstart); */
   /*  tp.tv_sec = tp.tv_sec +86400; */
   nberr=0; /* Number of errors and warnings */  /*  tm = *localtime(&start_time.tv_sec); */
   nbwarn=0;  /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
   getcwd(pathcd, size);  /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
   /*   tmg.tm_hour=tmg.tm_hour + 1; */
   printf("\n%s\n%s",version,fullversion);  /*   tp.tv_sec = mktime(&tmg); */
   if(argc <=1){  /*   strt=asctime(&tmg); */
     printf("\nEnter the parameter file name: ");  /*   printf("Time(after) =%s",strstart);  */
     fgets(pathr,FILENAMELENGTH,stdin);  /*  (void) time (&time_value);
     i=strlen(pathr);  *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
     if(pathr[i-1]=='\n')  *  tm = *localtime(&time_value);
       pathr[i-1]='\0';  *  strstart=asctime(&tm);
    for (tok = pathr; tok != NULL; ){  *  printf("tim_value=%d,asctime=%s\n",time_value,strstart);
       printf("Pathr |%s|\n",pathr);  */
       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');  
       printf("val= |%s| pathr=%s\n",val,pathr);    nberr=0; /* Number of errors and warnings */
       strcpy (pathtot, val);    nbwarn=0;
       if(pathr[0] == '\0') break; /* Dirty */    getcwd(pathcd, size);
     }  
   }    printf("\n%s\n%s",version,fullversion);
   else{    if(argc <=1){
     strcpy(pathtot,argv[1]);      printf("\nEnter the parameter file name: ");
   }      fgets(pathr,FILENAMELENGTH,stdin);
   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/      i=strlen(pathr);
   /*cygwin_split_path(pathtot,path,optionfile);      if(pathr[i-1]=='\n')
     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/        pathr[i-1]='\0';
   /* cutv(path,optionfile,pathtot,'\\');*/     for (tok = pathr; tok != NULL; ){
         printf("Pathr |%s|\n",pathr);
   /* Split argv[0], imach program to get pathimach */        while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);        printf("val= |%s| pathr=%s\n",val,pathr);
   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);        strcpy (pathtot, val);
   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);        if(pathr[0] == '\0') break; /* Dirty */
  /*   strcpy(pathimach,argv[0]); */      }
   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */    }
   split(pathtot,path,optionfile,optionfilext,optionfilefiname);    else{
   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);      strcpy(pathtot,argv[1]);
   chdir(path); /* Can be a relative path */    }
   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */    /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
     printf("Current directory %s!\n",pathcd);    /*cygwin_split_path(pathtot,path,optionfile);
   strcpy(command,"mkdir ");      printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
   strcat(command,optionfilefiname);    /* cutv(path,optionfile,pathtot,'\\');*/
   if((outcmd=system(command)) != 0){  
     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);    /* Split argv[0], imach program to get pathimach */
     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */    printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
     /* fclose(ficlog); */    split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 /*     exit(1); */    printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
   }   /*   strcpy(pathimach,argv[0]); */
 /*   if((imk=mkdir(optionfilefiname))<0){ */    /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 /*     perror("mkdir"); */    split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 /*   } */    printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
     chdir(path); /* Can be a relative path */
   /*-------- arguments in the command line --------*/    if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
       printf("Current directory %s!\n",pathcd);
   /* Log file */    strcpy(command,"mkdir ");
   strcat(filelog, optionfilefiname);    strcat(command,optionfilefiname);
   strcat(filelog,".log");    /* */    if((outcmd=system(command)) != 0){
   if((ficlog=fopen(filelog,"w"))==NULL)    {      printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
     printf("Problem with logfile %s\n",filelog);      /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
     goto end;      /* fclose(ficlog); */
   }  /*     exit(1); */
   fprintf(ficlog,"Log filename:%s\n",filelog);    }
   fprintf(ficlog,"\n%s\n%s",version,fullversion);  /*   if((imk=mkdir(optionfilefiname))<0){ */
   fprintf(ficlog,"\nEnter the parameter file name: \n");  /*     perror("mkdir"); */
   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\  /*   } */
  path=%s \n\  
  optionfile=%s\n\    /*-------- arguments in the command line --------*/
  optionfilext=%s\n\  
  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);    /* Log file */
     strcat(filelog, optionfilefiname);
   printf("Local time (at start):%s",strstart);    strcat(filelog,".log");    /* */
   fprintf(ficlog,"Local time (at start): %s",strstart);    if((ficlog=fopen(filelog,"w"))==NULL)    {
   fflush(ficlog);      printf("Problem with logfile %s\n",filelog);
 /*   (void) gettimeofday(&curr_time,&tzp); */      goto end;
 /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */    }
     fprintf(ficlog,"Log filename:%s\n",filelog);
   /* */    fprintf(ficlog,"\n%s\n%s",version,fullversion);
   strcpy(fileres,"r");    fprintf(ficlog,"\nEnter the parameter file name: \n");
   strcat(fileres, optionfilefiname);    fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
   strcat(fileres,".txt");    /* Other files have txt extension */   path=%s \n\
    optionfile=%s\n\
   /*---------arguments file --------*/   optionfilext=%s\n\
    optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
   if((ficpar=fopen(optionfile,"r"))==NULL)    {  
     printf("Problem with optionfile %s\n",optionfile);    printf("Local time (at start):%s",strstart);
     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);    fprintf(ficlog,"Local time (at start): %s",strstart);
     fflush(ficlog);    fflush(ficlog);
     goto end;  /*   (void) gettimeofday(&curr_time,&tzp); */
   }  /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
   
     /* */
     strcpy(fileres,"r");
   strcpy(filereso,"o");    strcat(fileres, optionfilefiname);
   strcat(filereso,fileres);    strcat(fileres,".txt");    /* Other files have txt extension */
   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */  
     printf("Problem with Output resultfile: %s\n", filereso);    /*---------arguments file --------*/
     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);  
     fflush(ficlog);    if((ficpar=fopen(optionfile,"r"))==NULL)    {
     goto end;      printf("Problem with optionfile %s\n",optionfile);
   }      fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
       fflush(ficlog);
   /* Reads comments: lines beginning with '#' */      goto end;
   numlinepar=0;    }
   while((c=getc(ficpar))=='#' && c!= EOF){  
     ungetc(c,ficpar);  
     fgets(line, MAXLINE, ficpar);  
     numlinepar++;    strcpy(filereso,"o");
     puts(line);    strcat(filereso,fileres);
     fputs(line,ficparo);    if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
     fputs(line,ficlog);      printf("Problem with Output resultfile: %s\n", filereso);
   }      fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
   ungetc(c,ficpar);      fflush(ficlog);
       goto end;
   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);    }
   numlinepar++;  
   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);    /* Reads comments: lines beginning with '#' */
   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);    numlinepar=0;
   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);    while((c=getc(ficpar))=='#' && c!= EOF){
   fflush(ficlog);      ungetc(c,ficpar);
   while((c=getc(ficpar))=='#' && c!= EOF){      fgets(line, MAXLINE, ficpar);
     ungetc(c,ficpar);      numlinepar++;
     fgets(line, MAXLINE, ficpar);      puts(line);
     numlinepar++;      fputs(line,ficparo);
     puts(line);      fputs(line,ficlog);
     fputs(line,ficparo);    }
     fputs(line,ficlog);    ungetc(c,ficpar);
   }  
   ungetc(c,ficpar);    fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
     numlinepar++;
        printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
   covar=matrix(0,NCOVMAX,1,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);
   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/    fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
   if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;    fflush(ficlog);
     while((c=getc(ficpar))=='#' && c!= EOF){
   ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */      ungetc(c,ficpar);
   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */      fgets(line, MAXLINE, ficpar);
   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/      numlinepar++;
       puts(line);
   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);      fputs(line,ficparo);
   delti=delti3[1][1];      fputs(line,ficlog);
   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/    }
   if(mle==-1){ /* Print a wizard for help writing covariance matrix */    ungetc(c,ficpar);
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);  
     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);     
     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);    covar=matrix(0,NCOVMAX,1,n);
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);     cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
     fclose (ficparo);    if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
     fclose (ficlog);  
     goto end;    ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
     exit(0);    nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
   }    npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
   else if(mle==-3) {  
     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);    delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    delti=delti3[1][1];
     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);    /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    if(mle==-1){ /* Print a wizard for help writing covariance matrix */
     matcov=matrix(1,npar,1,npar);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
   }      printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
   else{      fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
     /* Read guess parameters */      free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
     /* Reads comments: lines beginning with '#' */      fclose (ficparo);
     while((c=getc(ficpar))=='#' && c!= EOF){      fclose (ficlog);
       ungetc(c,ficpar);      goto end;
       fgets(line, MAXLINE, ficpar);      exit(0);
       numlinepar++;    }
       puts(line);    else if(mle==-3) {
       fputs(line,ficparo);      prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
       fputs(line,ficlog);      printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     }      fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
     ungetc(c,ficpar);      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
           matcov=matrix(1,npar,1,npar);
     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);    }
     for(i=1; i <=nlstate; i++){    else{
       j=0;      /* Read guess parameters */
       for(jj=1; jj <=nlstate+ndeath; jj++){      /* Reads comments: lines beginning with '#' */
         if(jj==i) continue;      while((c=getc(ficpar))=='#' && c!= EOF){
         j++;        ungetc(c,ficpar);
         fscanf(ficpar,"%1d%1d",&i1,&j1);        fgets(line, MAXLINE, ficpar);
         if ((i1 != i) && (j1 != j)){        numlinepar++;
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \        puts(line);
 It might be a problem of design; if ncovcol and the model are correct\n \        fputs(line,ficparo);
 run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);        fputs(line,ficlog);
           exit(1);      }
         }      ungetc(c,ficpar);
         fprintf(ficparo,"%1d%1d",i1,j1);     
         if(mle==1)      param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
           printf("%1d%1d",i,j);      for(i=1; i <=nlstate; i++){
         fprintf(ficlog,"%1d%1d",i,j);        j=0;
         for(k=1; k<=ncovmodel;k++){        for(jj=1; jj <=nlstate+ndeath; jj++){
           fscanf(ficpar," %lf",&param[i][j][k]);          if(jj==i) continue;
           if(mle==1){          j++;
             printf(" %lf",param[i][j][k]);          fscanf(ficpar,"%1d%1d",&i1,&j1);
             fprintf(ficlog," %lf",param[i][j][k]);          if ((i1 != i) && (j1 != j)){
           }            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
           else  It might be a problem of design; if ncovcol and the model are correct\n \
             fprintf(ficlog," %lf",param[i][j][k]);  run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
           fprintf(ficparo," %lf",param[i][j][k]);            exit(1);
         }          }
         fscanf(ficpar,"\n");          fprintf(ficparo,"%1d%1d",i1,j1);
         numlinepar++;          if(mle==1)
         if(mle==1)            printf("%1d%1d",i,j);
           printf("\n");          fprintf(ficlog,"%1d%1d",i,j);
         fprintf(ficlog,"\n");          for(k=1; k<=ncovmodel;k++){
         fprintf(ficparo,"\n");            fscanf(ficpar," %lf",&param[i][j][k]);
       }            if(mle==1){
     }                printf(" %lf",param[i][j][k]);
     fflush(ficlog);              fprintf(ficlog," %lf",param[i][j][k]);
             }
     p=param[1][1];            else
                   fprintf(ficlog," %lf",param[i][j][k]);
     /* Reads comments: lines beginning with '#' */            fprintf(ficparo," %lf",param[i][j][k]);
     while((c=getc(ficpar))=='#' && c!= EOF){          }
       ungetc(c,ficpar);          fscanf(ficpar,"\n");
       fgets(line, MAXLINE, ficpar);          numlinepar++;
       numlinepar++;          if(mle==1)
       puts(line);            printf("\n");
       fputs(line,ficparo);          fprintf(ficlog,"\n");
       fputs(line,ficlog);          fprintf(ficparo,"\n");
     }        }
     ungetc(c,ficpar);      }  
       fflush(ficlog);
     for(i=1; i <=nlstate; i++){  
       for(j=1; j <=nlstate+ndeath-1; j++){      p=param[1][1];
         fscanf(ficpar,"%1d%1d",&i1,&j1);     
         if ((i1-i)*(j1-j)!=0){      /* Reads comments: lines beginning with '#' */
           printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);      while((c=getc(ficpar))=='#' && c!= EOF){
           exit(1);        ungetc(c,ficpar);
         }        fgets(line, MAXLINE, ficpar);
         printf("%1d%1d",i,j);        numlinepar++;
         fprintf(ficparo,"%1d%1d",i1,j1);        puts(line);
         fprintf(ficlog,"%1d%1d",i1,j1);        fputs(line,ficparo);
         for(k=1; k<=ncovmodel;k++){        fputs(line,ficlog);
           fscanf(ficpar,"%le",&delti3[i][j][k]);      }
           printf(" %le",delti3[i][j][k]);      ungetc(c,ficpar);
           fprintf(ficparo," %le",delti3[i][j][k]);  
           fprintf(ficlog," %le",delti3[i][j][k]);      for(i=1; i <=nlstate; i++){
         }        for(j=1; j <=nlstate+ndeath-1; j++){
         fscanf(ficpar,"\n");          fscanf(ficpar,"%1d%1d",&i1,&j1);
         numlinepar++;          if ((i1-i)*(j1-j)!=0){
         printf("\n");            printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
         fprintf(ficparo,"\n");            exit(1);
         fprintf(ficlog,"\n");          }
       }          printf("%1d%1d",i,j);
     }          fprintf(ficparo,"%1d%1d",i1,j1);
     fflush(ficlog);          fprintf(ficlog,"%1d%1d",i1,j1);
           for(k=1; k<=ncovmodel;k++){
     delti=delti3[1][1];            fscanf(ficpar,"%le",&delti3[i][j][k]);
             printf(" %le",delti3[i][j][k]);
             fprintf(ficparo," %le",delti3[i][j][k]);
     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */            fprintf(ficlog," %le",delti3[i][j][k]);
             }
     /* Reads comments: lines beginning with '#' */          fscanf(ficpar,"\n");
     while((c=getc(ficpar))=='#' && c!= EOF){          numlinepar++;
       ungetc(c,ficpar);          printf("\n");
       fgets(line, MAXLINE, ficpar);          fprintf(ficparo,"\n");
       numlinepar++;          fprintf(ficlog,"\n");
       puts(line);        }
       fputs(line,ficparo);      }
       fputs(line,ficlog);      fflush(ficlog);
     }  
     ungetc(c,ficpar);      delti=delti3[1][1];
     
     matcov=matrix(1,npar,1,npar);  
     for(i=1; i <=npar; i++){      /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
       fscanf(ficpar,"%s",&str);   
       if(mle==1)      /* Reads comments: lines beginning with '#' */
         printf("%s",str);      while((c=getc(ficpar))=='#' && c!= EOF){
       fprintf(ficlog,"%s",str);        ungetc(c,ficpar);
       fprintf(ficparo,"%s",str);        fgets(line, MAXLINE, ficpar);
       for(j=1; j <=i; j++){        numlinepar++;
         fscanf(ficpar," %le",&matcov[i][j]);        puts(line);
         if(mle==1){        fputs(line,ficparo);
           printf(" %.5le",matcov[i][j]);        fputs(line,ficlog);
         }      }
         fprintf(ficlog," %.5le",matcov[i][j]);      ungetc(c,ficpar);
         fprintf(ficparo," %.5le",matcov[i][j]);   
       }      matcov=matrix(1,npar,1,npar);
       fscanf(ficpar,"\n");      for(i=1; i <=npar; i++){
       numlinepar++;        fscanf(ficpar,"%s",&str);
       if(mle==1)        if(mle==1)
         printf("\n");          printf("%s",str);
       fprintf(ficlog,"\n");        fprintf(ficlog,"%s",str);
       fprintf(ficparo,"\n");        fprintf(ficparo,"%s",str);
     }        for(j=1; j <=i; j++){
     for(i=1; i <=npar; i++)          fscanf(ficpar," %le",&matcov[i][j]);
       for(j=i+1;j<=npar;j++)          if(mle==1){
         matcov[i][j]=matcov[j][i];            printf(" %.5le",matcov[i][j]);
               }
     if(mle==1)          fprintf(ficlog," %.5le",matcov[i][j]);
       printf("\n");          fprintf(ficparo," %.5le",matcov[i][j]);
     fprintf(ficlog,"\n");        }
             fscanf(ficpar,"\n");
     fflush(ficlog);        numlinepar++;
             if(mle==1)
     /*-------- Rewriting parameter file ----------*/          printf("\n");
     strcpy(rfileres,"r");    /* "Rparameterfile */        fprintf(ficlog,"\n");
     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/        fprintf(ficparo,"\n");
     strcat(rfileres,".");    /* */      }
     strcat(rfileres,optionfilext);    /* Other files have txt extension */      for(i=1; i <=npar; i++)
     if((ficres =fopen(rfileres,"w"))==NULL) {        for(j=i+1;j<=npar;j++)
       printf("Problem writing new parameter file: %s\n", fileres);goto end;          matcov[i][j]=matcov[j][i];
       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;     
     }      if(mle==1)
     fprintf(ficres,"#%s\n",version);        printf("\n");
   }    /* End of mle != -3 */      fprintf(ficlog,"\n");
      
   /*-------- data file ----------*/      fflush(ficlog);
   if((fic=fopen(datafile,"r"))==NULL)    {     
     printf("Problem while opening datafile: %s\n", datafile);goto end;      /*-------- Rewriting parameter file ----------*/
     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;      strcpy(rfileres,"r");    /* "Rparameterfile */
   }      strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
       strcat(rfileres,".");    /* */
   n= lastobs;      strcat(rfileres,optionfilext);    /* Other files have txt extension */
   severity = vector(1,maxwav);      if((ficres =fopen(rfileres,"w"))==NULL) {
   outcome=imatrix(1,maxwav+1,1,n);        printf("Problem writing new parameter file: %s\n", fileres);goto end;
   num=lvector(1,n);        fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
   moisnais=vector(1,n);      }
   annais=vector(1,n);      fprintf(ficres,"#%s\n",version);
   moisdc=vector(1,n);    }    /* End of mle != -3 */
   andc=vector(1,n);  
   agedc=vector(1,n);    /*-------- data file ----------*/
   cod=ivector(1,n);    if((fic=fopen(datafile,"r"))==NULL)    {
   weight=vector(1,n);      printf("Problem while opening datafile: %s\n", datafile);goto end;
   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */      fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
   mint=matrix(1,maxwav,1,n);    }
   anint=matrix(1,maxwav,1,n);  
   s=imatrix(1,maxwav+1,1,n);    n= lastobs;
   tab=ivector(1,NCOVMAX);    severity = vector(1,maxwav);
   ncodemax=ivector(1,8);    outcome=imatrix(1,maxwav+1,1,n);
     num=lvector(1,n);
   i=1;    moisnais=vector(1,n);
   linei=0;    annais=vector(1,n);
   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {    moisdc=vector(1,n);
     linei=linei+1;    andc=vector(1,n);
     for(j=strlen(line); j>=0;j--){  /* Untabifies line */    agedc=vector(1,n);
       if(line[j] == '\t')    cod=ivector(1,n);
         line[j] = ' ';    weight=vector(1,n);
     }    for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){    mint=matrix(1,maxwav,1,n);
       ;    anint=matrix(1,maxwav,1,n);
     };    s=imatrix(1,maxwav+1,1,n);
     line[j+1]=0;  /* Trims blanks at end of line */    tab=ivector(1,NCOVMAX);
     if(line[0]=='#'){    ncodemax=ivector(1,8);
       fprintf(ficlog,"Comment line\n%s\n",line);  
       printf("Comment line\n%s\n",line);    i=1;
       continue;    linei=0;
     }    while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
       linei=linei+1;
     for (j=maxwav;j>=1;j--){      for(j=strlen(line); j>=0;j--){  /* Untabifies line */
       cutv(stra, strb,line,' ');         if(line[j] == '\t')
       errno=0;          line[j] = ' ';
       lval=strtol(strb,&endptr,10);       }
       /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/      for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
       if( strb[0]=='\0' || (*endptr != '\0')){        ;
         printf("Error reading data around '%d' at line number %d %s for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);      };
         exit(1);      line[j+1]=0;  /* Trims blanks at end of line */
       }      if(line[0]=='#'){
       s[j][i]=lval;        fprintf(ficlog,"Comment line\n%s\n",line);
               printf("Comment line\n%s\n",line);
       strcpy(line,stra);        continue;
       cutv(stra, strb,line,' ');      }
       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){  
       }      for (j=maxwav;j>=1;j--){
       else  if(iout=sscanf(strb,"%s.") != 0){        cutv(stra, strb,line,' ');
         month=99;        errno=0;
         year=9999;        lval=strtol(strb,&endptr,10);
       }else{        /*        if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
         printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);        if( strb[0]=='\0' || (*endptr != '\0')){
         exit(1);          printf("Error reading data around '%d' at line number %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);
       anint[j][i]= (double) year;         }
       mint[j][i]= (double)month;         s[j][i]=lval;
       strcpy(line,stra);       
     } /* ENd Waves */        strcpy(line,stra);
             cutv(stra, strb,line,' ');
     cutv(stra, strb,line,' ');         if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){        }
     }        else  if(iout=sscanf(strb,"%s.") != 0){
     else  if(iout=sscanf(strb,"%s.",dummy) != 0){          month=99;
       month=99;          year=9999;
       year=9999;        }else{
     }else{          printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
       printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);          exit(1);
       exit(1);        }
     }        anint[j][i]= (double) year;
     andc[i]=(double) year;         mint[j][i]= (double)month;
     moisdc[i]=(double) month;         strcpy(line,stra);
     strcpy(line,stra);      } /* ENd Waves */
          
     cutv(stra, strb,line,' ');       cutv(stra, strb,line,' ');
     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     }      }
     else  if(iout=sscanf(strb,"%s.") != 0){      else  if(iout=sscanf(strb,"%s.",dummy) != 0){
       month=99;        month=99;
       year=9999;        year=9999;
     }else{      }else{
       printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line,j);        printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
       exit(1);        exit(1);
     }      }
     annais[i]=(double)(year);      andc[i]=(double) year;
     moisnais[i]=(double)(month);       moisdc[i]=(double) month;
     strcpy(line,stra);      strcpy(line,stra);
          
     cutv(stra, strb,line,' ');       cutv(stra, strb,line,' ');
     errno=0;      if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
     dval=strtod(strb,&endptr);       }
     if( strb[0]=='\0' || (*endptr != '\0')){      else  if(iout=sscanf(strb,"%s.") != 0){
       printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);        month=99;
       exit(1);        year=9999;
     }      }else{
     weight[i]=dval;         printf("Error reading data around '%s' at line number %ld %s for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line,j);
     strcpy(line,stra);        exit(1);
           }
     for (j=ncovcol;j>=1;j--){      annais[i]=(double)(year);
       cutv(stra, strb,line,' ');       moisnais[i]=(double)(month);
       errno=0;      strcpy(line,stra);
       lval=strtol(strb,&endptr,10);      
       if( strb[0]=='\0' || (*endptr != '\0')){      cutv(stra, strb,line,' ');
         printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a covar (meaning 0 for the reference or 1).  Exiting.\n",lval, linei,i, line);      errno=0;
         exit(1);      dval=strtod(strb,&endptr);
       }      if( strb[0]=='\0' || (*endptr != '\0')){
       if(lval <-1 || lval >1){        printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
         printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \        exit(1);
  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \      }
  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \      weight[i]=dval;
  For example, for multinomial values like 1, 2 and 3,\n \      strcpy(line,stra);
  build V1=0 V2=0 for the reference value (1),\n \     
         V1=1 V2=0 for (2) \n \      for (j=ncovcol;j>=1;j--){
  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \        cutv(stra, strb,line,' ');
  output of IMaCh is often meaningless.\n \        errno=0;
  Exiting.\n",lval,linei, i,line,j);        lval=strtol(strb,&endptr,10);
         exit(1);        if( strb[0]=='\0' || (*endptr != '\0')){
       }          printf("Error reading data around '%d' at line number %ld %s for individual %d, '%s'\nShould be a covar (meaning 0 for the reference or 1).  Exiting.\n",lval, linei,i, line);
       covar[j][i]=(double)(lval);          exit(1);
       strcpy(line,stra);        }
     }         if(lval <-1 || lval >1){
     lstra=strlen(stra);          printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
        Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */   for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
       stratrunc = &(stra[lstra-9]);   For example, for multinomial values like 1, 2 and 3,\n \
       num[i]=atol(stratrunc);   build V1=0 V2=0 for the reference value (1),\n \
     }          V1=1 V2=0 for (2) \n \
     else   and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
       num[i]=atol(stra);   output of IMaCh is often meaningless.\n \
     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){   Exiting.\n",lval,linei, i,line,j);
       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;}*/          exit(1);
             }
     i=i+1;        covar[j][i]=(double)(lval);
   } /* End loop reading  data */        strcpy(line,stra);
   fclose(fic);      }
   /* printf("ii=%d", ij);      lstra=strlen(stra);
      scanf("%d",i);*/     
   imx=i-1; /* Number of individuals */      if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
         stratrunc = &(stra[lstra-9]);
   /* for (i=1; i<=imx; i++){        num[i]=atol(stratrunc);
     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;      else
     if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;        num[i]=atol(stra);
     }*/      /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
    /*  for (i=1; i<=imx; i++){        printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/
      if (s[4][i]==9)  s[4][i]=-1;      
      printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]), (weight[i]), (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i]));}*/      i=i+1;
       } /* End loop reading  data */
   /* for (i=1; i<=imx; i++) */    fclose(fic);
      /* printf("ii=%d", ij);
    /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;       scanf("%d",i);*/
      else weight[i]=1;*/    imx=i-1; /* Number of individuals */
   
   /* Calculation of the number of parameters from char model */    /* for (i=1; i<=imx; i++){
   Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */      if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
   Tprod=ivector(1,15);       if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
   Tvaraff=ivector(1,15);       if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
   Tvard=imatrix(1,15,1,2);      }*/
   Tage=ivector(1,15);           /*  for (i=1; i<=imx; i++){
           if (s[4][i]==9)  s[4][i]=-1;
   if (strlen(model) >1){ /* If there is at least 1 covariate */       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]));}*/
     j=0, j1=0, k1=1, k2=1;   
     j=nbocc(model,'+'); /* j=Number of '+' */    /* for (i=1; i<=imx; i++) */
     j1=nbocc(model,'*'); /* j1=Number of '*' */   
     cptcovn=j+1;      /*if ((s[3][i]==3) ||  (s[4][i]==3)) weight[i]=0.08;
     cptcovprod=j1; /*Number of products */       else weight[i]=1;*/
       
     strcpy(modelsav,model);     /* Calculation of the number of parameters from char model */
     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){    Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
       printf("Error. Non available option model=%s ",model);    Tprod=ivector(1,15);
       fprintf(ficlog,"Error. Non available option model=%s ",model);    Tvaraff=ivector(1,15);
       goto end;    Tvard=imatrix(1,15,1,2);
     }    Tage=ivector(1,15);      
          
     /* This loop fills the array Tvar from the string 'model'.*/    if (strlen(model) >1){ /* If there is at least 1 covariate */
       j=0, j1=0, k1=1, k2=1;
     for(i=(j+1); i>=1;i--){      j=nbocc(model,'+'); /* j=Number of '+' */
       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */       j1=nbocc(model,'*'); /* j1=Number of '*' */
       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */      cptcovn=j+1;
       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/      cptcovprod=j1; /*Number of products */
       /*scanf("%d",i);*/     
       if (strchr(strb,'*')) {  /* Model includes a product */      strcpy(modelsav,model);
         cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/      if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
         if (strcmp(strc,"age")==0) { /* Vn*age */        printf("Error. Non available option model=%s ",model);
           cptcovprod--;        fprintf(ficlog,"Error. Non available option model=%s ",model);
           cutv(strb,stre,strd,'V');        goto end;
           Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/      }
           cptcovage++;     
             Tage[cptcovage]=i;      /* This loop fills the array Tvar from the string 'model'.*/
             /*printf("stre=%s ", stre);*/  
         }      for(i=(j+1); i>=1;i--){
         else if (strcmp(strd,"age")==0) { /* or age*Vn */        cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
           cptcovprod--;        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
           cutv(strb,stre,strc,'V');        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
           Tvar[i]=atoi(stre);        /*scanf("%d",i);*/
           cptcovage++;        if (strchr(strb,'*')) {  /* Model includes a product */
           Tage[cptcovage]=i;          cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn (if not *age)*/
         }          if (strcmp(strc,"age")==0) { /* Vn*age */
         else {  /* Age is not in the model */            cptcovprod--;
           cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/            cutv(strb,stre,strd,'V');
           Tvar[i]=ncovcol+k1;            Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
           cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */            cptcovage++;
           Tprod[k1]=i;              Tage[cptcovage]=i;
           Tvard[k1][1]=atoi(strc); /* m*/              /*printf("stre=%s ", stre);*/
           Tvard[k1][2]=atoi(stre); /* n */          }
           Tvar[cptcovn+k2]=Tvard[k1][1];          else if (strcmp(strd,"age")==0) { /* or age*Vn */
           Tvar[cptcovn+k2+1]=Tvard[k1][2];             cptcovprod--;
           for (k=1; k<=lastobs;k++)             cutv(strb,stre,strc,'V');
             covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];            Tvar[i]=atoi(stre);
           k1++;            cptcovage++;
           k2=k2+2;            Tage[cptcovage]=i;
         }          }
       }          else {  /* Age is not in the model */
       else { /* no more sum */            cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
         /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/            Tvar[i]=ncovcol+k1;
        /*  scanf("%d",i);*/            cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
       cutv(strd,strc,strb,'V');            Tprod[k1]=i;
       Tvar[i]=atoi(strc);            Tvard[k1][1]=atoi(strc); /* m*/
       }            Tvard[k1][2]=atoi(stre); /* n */
       strcpy(modelsav,stra);              Tvar[cptcovn+k2]=Tvard[k1][1];
       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);            Tvar[cptcovn+k2+1]=Tvard[k1][2];
         scanf("%d",i);*/            for (k=1; k<=lastobs;k++)
     } /* end of loop + */              covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
   } /* end model */            k1++;
               k2=k2+2;
   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.          }
     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/        }
         else { /* no more sum */
   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
   printf("cptcovprod=%d ", cptcovprod);         /*  scanf("%d",i);*/
   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);        cutv(strd,strc,strb,'V');
         Tvar[i]=atoi(strc);
   scanf("%d ",i);*/        }
         strcpy(modelsav,stra);  
     /*  if(mle==1){*/        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
   if (weightopt != 1) { /* Maximisation without weights*/          scanf("%d",i);*/
     for(i=1;i<=n;i++) weight[i]=1.0;      } /* end of loop + */
   }    } /* end model */
     /*-calculation of age at interview from date of interview and age at death -*/   
   agev=matrix(1,maxwav,1,imx);    /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
       If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
   for (i=1; i<=imx; i++) {  
     for(m=2; (m<= maxwav); m++) {    /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){    printf("cptcovprod=%d ", cptcovprod);
         anint[m][i]=9999;    fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
         s[m][i]=-1;  
       }    scanf("%d ",i);*/
       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){  
         nberr++;      /*  if(mle==1){*/
         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);    if (weightopt != 1) { /* Maximisation without weights*/
         fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);      for(i=1;i<=n;i++) weight[i]=1.0;
         s[m][i]=-1;    }
       }      /*-calculation of age at interview from date of interview and age at death -*/
       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){    agev=matrix(1,maxwav,1,imx);
         nberr++;  
         printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]);     for (i=1; i<=imx; 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]);       for(m=2; (m<= maxwav); m++) {
         s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */        if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
       }          anint[m][i]=9999;
     }          s[m][i]=-1;
   }        }
         if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
   for (i=1; i<=imx; i++)  {          nberr++;
     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);          printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
     for(m=firstpass; (m<= lastpass); m++){          fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){          s[m][i]=-1;
         if (s[m][i] >= nlstate+1) {        }
           if(agedc[i]>0)        if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
             if((int)moisdc[i]!=99 && (int)andc[i]!=9999)          nberr++;
               agev[m][i]=agedc[i];          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]);
           /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/          fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]);
             else {          s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
               if ((int)andc[i]!=9999){        }
                 nbwarn++;      }
                 printf("Warning negative age at death: %ld line:%d\n",num[i],i);    }
                 fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);  
                 agev[m][i]=-1;    for (i=1; i<=imx; i++)  {
               }      agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
             }      for(m=firstpass; (m<= lastpass); m++){
         }        if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
         else if(s[m][i] !=9){ /* Standard case, age in fractional          if (s[m][i] >= nlstate+1) {
                                  years but with the precision of a month */            if(agedc[i]>0)
           agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);              if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
           if((int)mint[m][i]==99 || (int)anint[m][i]==9999)                agev[m][i]=agedc[i];
             agev[m][i]=1;            /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
           else if(agev[m][i] <agemin){               else {
             agemin=agev[m][i];                if ((int)andc[i]!=9999){
             /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/                  nbwarn++;
           }                  printf("Warning negative age at death: %ld line:%d\n",num[i],i);
           else if(agev[m][i] >agemax){                  fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
             agemax=agev[m][i];                  agev[m][i]=-1;
             /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/                }
           }              }
           /*agev[m][i]=anint[m][i]-annais[i];*/          }
           /*     agev[m][i] = age[i]+2*m;*/          else if(s[m][i] !=9){ /* Standard case, age in fractional
         }                                   years but with the precision of a month */
         else { /* =9 */            agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
           agev[m][i]=1;            if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
           s[m][i]=-1;              agev[m][i]=1;
         }            else if(agev[m][i] <agemin){
       }              agemin=agev[m][i];
       else /*= 0 Unknown */              /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
         agev[m][i]=1;            }
     }            else if(agev[m][i] >agemax){
                   agemax=agev[m][i];
   }              /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
   for (i=1; i<=imx; i++)  {            }
     for(m=firstpass; (m<=lastpass); m++){            /*agev[m][i]=anint[m][i]-annais[i];*/
       if (s[m][i] > (nlstate+ndeath)) {            /*     agev[m][i] = age[i]+2*m;*/
         nberr++;          }
         printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);               else { /* =9 */
         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);                 agev[m][i]=1;
         goto end;            s[m][i]=-1;
       }          }
     }        }
   }        else /*= 0 Unknown */
           agev[m][i]=1;
   /*for (i=1; i<=imx; i++){      }
   for (m=firstpass; (m<lastpass); m++){     
      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);    }
 }    for (i=1; i<=imx; i++)  {
       for(m=firstpass; (m<=lastpass); m++){
 }*/        if (s[m][i] > (nlstate+ndeath)) {
           nberr++;
           printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);    
   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);          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);    
   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);           goto end;
         }
   agegomp=(int)agemin;      }
   free_vector(severity,1,maxwav);    }
   free_imatrix(outcome,1,maxwav+1,1,n);  
   free_vector(moisnais,1,n);    /*for (i=1; i<=imx; i++){
   free_vector(annais,1,n);    for (m=firstpass; (m<lastpass); m++){
   /* free_matrix(mint,1,maxwav,1,n);       printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
      free_matrix(anint,1,maxwav,1,n);*/  }
   free_vector(moisdc,1,n);  
   free_vector(andc,1,n);  }*/
   
      
   wav=ivector(1,imx);    printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
   dh=imatrix(1,lastpass-firstpass+1,1,imx);    fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
   bh=imatrix(1,lastpass-firstpass+1,1,imx);  
   mw=imatrix(1,lastpass-firstpass+1,1,imx);    agegomp=(int)agemin;
        free_vector(severity,1,maxwav);
   /* Concatenates waves */    free_imatrix(outcome,1,maxwav+1,1,n);
   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);    free_vector(moisnais,1,n);
     free_vector(annais,1,n);
   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */    /* free_matrix(mint,1,maxwav,1,n);
        free_matrix(anint,1,maxwav,1,n);*/
   Tcode=ivector(1,100);    free_vector(moisdc,1,n);
   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);     free_vector(andc,1,n);
   ncodemax[1]=1;  
   if (cptcovn > 0) tricode(Tvar,nbcode,imx);     
           wav=ivector(1,imx);
   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of     dh=imatrix(1,lastpass-firstpass+1,1,imx);
                                  the estimations*/    bh=imatrix(1,lastpass-firstpass+1,1,imx);
   h=0;    mw=imatrix(1,lastpass-firstpass+1,1,imx);
   m=pow(2,cptcoveff);     
      /* Concatenates waves */
   for(k=1;k<=cptcoveff; k++){    concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
     for(i=1; i <=(m/pow(2,k));i++){  
       for(j=1; j <= ncodemax[k]; j++){    /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
         for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){  
           h++;    Tcode=ivector(1,100);
           if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;    nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
           /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/    ncodemax[1]=1;
         }     if (cptcovn > 0) tricode(Tvar,nbcode,imx);
       }       
     }    codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
   }                                    the estimations*/
   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);     h=0;
      codtab[1][2]=1;codtab[2][2]=2; */    m=pow(2,cptcoveff);
   /* for(i=1; i <=m ;i++){    
      for(k=1; k <=cptcovn; k++){    for(k=1;k<=cptcoveff; k++){
      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);      for(i=1; i <=(m/pow(2,k));i++){
      }        for(j=1; j <= ncodemax[k]; j++){
      printf("\n");          for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
      }            h++;
      scanf("%d",i);*/            if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
                 /*  printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
   /*------------ gnuplot -------------*/          }
   strcpy(optionfilegnuplot,optionfilefiname);        }
   if(mle==-3)      }
     strcat(optionfilegnuplot,"-mort");    }
   strcat(optionfilegnuplot,".gp");    /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
        codtab[1][2]=1;codtab[2][2]=2; */
   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {    /* for(i=1; i <=m ;i++){
     printf("Problem with file %s",optionfilegnuplot);       for(k=1; k <=cptcovn; k++){
   }       printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
   else{       }
     fprintf(ficgp,"\n# %s\n", version);        printf("\n");
     fprintf(ficgp,"# %s\n", optionfilegnuplot);        }
     fprintf(ficgp,"set missing 'NaNq'\n");       scanf("%d",i);*/
   }     
   /*  fclose(ficgp);*/    /*------------ gnuplot -------------*/
   /*--------- index.htm --------*/    strcpy(optionfilegnuplot,optionfilefiname);
     if(mle==-3)
   strcpy(optionfilehtm,optionfilefiname); /* Main html file */      strcat(optionfilegnuplot,"-mort");
   if(mle==-3)    strcat(optionfilegnuplot,".gp");
     strcat(optionfilehtm,"-mort");  
   strcat(optionfilehtm,".htm");    if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {      printf("Problem with file %s",optionfilegnuplot);
     printf("Problem with %s \n",optionfilehtm), exit(0);    }
   }    else{
       fprintf(ficgp,"\n# %s\n", version);
   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */      fprintf(ficgp,"# %s\n", optionfilegnuplot);
   strcat(optionfilehtmcov,"-cov.htm");      fprintf(ficgp,"set missing 'NaNq'\n");
   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {    }
     printf("Problem with %s \n",optionfilehtmcov), exit(0);    /*  fclose(ficgp);*/
   }    /*--------- index.htm --------*/
   else{  
   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \    strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 <hr size=\"2\" color=\"#EC5E5E\"> \n\    if(mle==-3)
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\      strcat(optionfilehtm,"-mort");
           optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);    strcat(optionfilehtm,".htm");
   }    if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
       printf("Problem with %s \n",optionfilehtm), exit(0);
   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \    }
 <hr size=\"2\" color=\"#EC5E5E\"> \n\  
 Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\    strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 \n\    strcat(optionfilehtmcov,"-cov.htm");
 <hr  size=\"2\" color=\"#EC5E5E\">\    if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
  <ul><li><h4>Parameter files</h4>\n\      printf("Problem with %s \n",optionfilehtmcov), exit(0);
  - 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\    else{
  - Log file of the run: <a href=\"%s\">%s</a><br>\n\    fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\  <hr size=\"2\" color=\"#EC5E5E\"> \n\
  - Date and time at start: %s</ul>\n",\  Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
           optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\            optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
           optionfilefiname,optionfilext,optionfilefiname,optionfilext,\    }
           fileres,fileres,\  
           filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);    fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
   fflush(fichtm);  <hr size=\"2\" color=\"#EC5E5E\"> \n\
   Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
   strcpy(pathr,path);  \n\
   strcat(pathr,optionfilefiname);  <hr  size=\"2\" color=\"#EC5E5E\">\
   chdir(optionfilefiname); /* Move to directory named optionfile */   <ul><li><h4>Parameter files</h4>\n\
      - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
   /* Calculates basic frequencies. Computes observed prevalence at single age   - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
      and prints on file fileres'p'. */   - Log file of the run: <a href=\"%s\">%s</a><br>\n\
   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);   - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
    - Date and time at start: %s</ul>\n",\
   fprintf(fichtm,"\n");            optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\            optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\            fileres,fileres,\
 Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\            filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
           imx,agemin,agemax,jmin,jmax,jmean);    fflush(fichtm);
   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */  
     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    strcpy(pathr,path);
     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    strcat(pathr,optionfilefiname);
     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */    chdir(optionfilefiname); /* Move to directory named optionfile */
     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */   
         /* Calculates basic frequencies. Computes observed prevalence at single age
           and prints on file fileres'p'. */
   /* For Powell, parameters are in a vector p[] starting at p[1]    freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */  
   p=param[1][1]; /* *(*(*(param +1)+1)+0) */    fprintf(fichtm,"\n");
     fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/  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",\
   if (mle==-3){            imx,agemin,agemax,jmin,jmax,jmean);
     ximort=matrix(1,NDIM,1,NDIM);    pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     cens=ivector(1,n);      oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     ageexmed=vector(1,n);      newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     agecens=vector(1,n);      savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
     dcwave=ivector(1,n);      oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
       
     for (i=1; i<=imx; i++){     
       dcwave[i]=-1;    /* For Powell, parameters are in a vector p[] starting at p[1]
       for (m=firstpass; m<=lastpass; m++)       so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
         if (s[m][i]>nlstate) {    p=param[1][1]; /* *(*(*(param +1)+1)+0) */
           dcwave[i]=m;  
           /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/    globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
           break;  
         }    if (mle==-3){
     }      ximort=matrix(1,NDIM,1,NDIM);
       cens=ivector(1,n);
     for (i=1; i<=imx; i++) {      ageexmed=vector(1,n);
       if (wav[i]>0){      agecens=vector(1,n);
         ageexmed[i]=agev[mw[1][i]][i];      dcwave=ivector(1,n);
         j=wav[i];   
         agecens[i]=1.;       for (i=1; i<=imx; i++){
         dcwave[i]=-1;
         if (ageexmed[i]> 1 && wav[i] > 0){        for (m=firstpass; m<=lastpass; m++)
           agecens[i]=agev[mw[j][i]][i];          if (s[m][i]>nlstate) {
           cens[i]= 1;            dcwave[i]=m;
         }else if (ageexmed[i]< 1)             /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
           cens[i]= -1;            break;
         if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)          }
           cens[i]=0 ;      }
       }  
       else cens[i]=-1;      for (i=1; i<=imx; i++) {
     }        if (wav[i]>0){
               ageexmed[i]=agev[mw[1][i]][i];
     for (i=1;i<=NDIM;i++) {          j=wav[i];
       for (j=1;j<=NDIM;j++)          agecens[i]=1.;
         ximort[i][j]=(i == j ? 1.0 : 0.0);  
     }          if (ageexmed[i]> 1 && wav[i] > 0){
                 agecens[i]=agev[mw[j][i]][i];
     p[1]=0.0268; p[NDIM]=0.083;            cens[i]= 1;
     /*printf("%lf %lf", p[1], p[2]);*/          }else if (ageexmed[i]< 1)
                 cens[i]= -1;
               if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
     printf("Powell\n");  fprintf(ficlog,"Powell\n");            cens[i]=0 ;
     strcpy(filerespow,"pow-mort");         }
     strcat(filerespow,fileres);        else cens[i]=-1;
     if((ficrespow=fopen(filerespow,"w"))==NULL) {      }
       printf("Problem with resultfile: %s\n", filerespow);     
       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);      for (i=1;i<=NDIM;i++) {
     }        for (j=1;j<=NDIM;j++)
     fprintf(ficrespow,"# Powell\n# iter -2*LL");          ximort[i][j]=(i == j ? 1.0 : 0.0);
     /*  for (i=1;i<=nlstate;i++)      }
         for(j=1;j<=nlstate+ndeath;j++)     
         if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);      p[1]=0.0268; p[NDIM]=0.083;
     */      /*printf("%lf %lf", p[1], p[2]);*/
     fprintf(ficrespow,"\n");     
          
     powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);      printf("Powell\n");  fprintf(ficlog,"Powell\n");
     fclose(ficrespow);      strcpy(filerespow,"pow-mort");
           strcat(filerespow,fileres);
     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);       if((ficrespow=fopen(filerespow,"w"))==NULL) {
         printf("Problem with resultfile: %s\n", filerespow);
     for(i=1; i <=NDIM; i++)        fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
       for(j=i+1;j<=NDIM;j++)      }
         matcov[i][j]=matcov[j][i];      fprintf(ficrespow,"# Powell\n# iter -2*LL");
           /*  for (i=1;i<=nlstate;i++)
     printf("\nCovariance matrix\n ");          for(j=1;j<=nlstate+ndeath;j++)
     for(i=1; i <=NDIM; i++) {          if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
       for(j=1;j<=NDIM;j++){       */
         printf("%f ",matcov[i][j]);      fprintf(ficrespow,"\n");
       }     
       printf("\n ");      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
     }      fclose(ficrespow);
          
     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);      hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
     for (i=1;i<=NDIM;i++)   
       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));      for(i=1; i <=NDIM; i++)
         for(j=i+1;j<=NDIM;j++)
     lsurv=vector(1,AGESUP);          matcov[i][j]=matcov[j][i];
     lpop=vector(1,AGESUP);     
     tpop=vector(1,AGESUP);      printf("\nCovariance matrix\n ");
     lsurv[agegomp]=100000;      for(i=1; i <=NDIM; i++) {
             for(j=1;j<=NDIM;j++){
     for (k=agegomp;k<=AGESUP;k++) {          printf("%f ",matcov[i][j]);
       agemortsup=k;        }
       if (p[1]*exp(p[2]*(k-agegomp))>1) break;        printf("\n ");
     }      }
          
     for (k=agegomp;k<agemortsup;k++)      printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));      for (i=1;i<=NDIM;i++)
             printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
     for (k=agegomp;k<agemortsup;k++){  
       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;      lsurv=vector(1,AGESUP);
       sumlpop=sumlpop+lpop[k];      lpop=vector(1,AGESUP);
     }      tpop=vector(1,AGESUP);
           lsurv[agegomp]=100000;
     tpop[agegomp]=sumlpop;     
     for (k=agegomp;k<(agemortsup-3);k++){      for (k=agegomp;k<=AGESUP;k++) {
       /*  tpop[k+1]=2;*/        agemortsup=k;
       tpop[k+1]=tpop[k]-lpop[k];        if (p[1]*exp(p[2]*(k-agegomp))>1) break;
     }      }
          
           for (k=agegomp;k<agemortsup;k++)
     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");        lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
     for (k=agegomp;k<(agemortsup-2);k++)      
       printf("%d %.0lf %lf %.0lf %.0lf %.0lf %lf\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);      for (k=agegomp;k<agemortsup;k++){
             lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
             sumlpop=sumlpop+lpop[k];
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      }
     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);     
           tpop[agegomp]=sumlpop;
     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \      for (k=agegomp;k<(agemortsup-3);k++){
                      stepm, weightopt,\        /*  tpop[k+1]=2;*/
                      model,imx,p,matcov,agemortsup);        tpop[k+1]=tpop[k]-lpop[k];
           }
     free_vector(lsurv,1,AGESUP);     
     free_vector(lpop,1,AGESUP);     
     free_vector(tpop,1,AGESUP);      printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
   } /* Endof if mle==-3 */      for (k=agegomp;k<(agemortsup-2);k++)
           printf("%d %.0lf %lf %.0lf %.0lf %.0lf %lf\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);
   else{ /* For mle >=1 */     
        
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);      printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     for (k=1; k<=npar;k++)     
       printf(" %d %8.5f",k,p[k]);      printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
     printf("\n");                       stepm, weightopt,\
     globpr=1; /* to print the contributions */                       model,imx,p,matcov,agemortsup);
     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */     
     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);      free_vector(lsurv,1,AGESUP);
     for (k=1; k<=npar;k++)      free_vector(lpop,1,AGESUP);
       printf(" %d %8.5f",k,p[k]);      free_vector(tpop,1,AGESUP);
     printf("\n");    } /* Endof if mle==-3 */
     if(mle>=1){ /* Could be 1 or 2 */   
       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);    else{ /* For mle >=1 */
     }   
           likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
     /*--------- results files --------------*/      printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
     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);      for (k=1; k<=npar;k++)
             printf(" %d %8.5f",k,p[k]);
           printf("\n");
     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      globpr=1; /* to print the contributions */
     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");      printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
     for(i=1,jk=1; i <=nlstate; i++){      for (k=1; k<=npar;k++)
       for(k=1; k <=(nlstate+ndeath); k++){        printf(" %d %8.5f",k,p[k]);
         if (k != i) {      printf("\n");
           printf("%d%d ",i,k);      if(mle>=1){ /* Could be 1 or 2 */
           fprintf(ficlog,"%d%d ",i,k);        mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
           fprintf(ficres,"%1d%1d ",i,k);      }
           for(j=1; j <=ncovmodel; j++){     
             printf("%f ",p[jk]);      /*--------- results files --------------*/
             fprintf(ficlog,"%f ",p[jk]);      fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
             fprintf(ficres,"%f ",p[jk]);     
             jk++;      
           }      fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
           printf("\n");      printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
           fprintf(ficlog,"\n");      fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
           fprintf(ficres,"\n");      for(i=1,jk=1; i <=nlstate; i++){
         }        for(k=1; k <=(nlstate+ndeath); k++){
       }          if (k != i) {
     }            printf("%d%d ",i,k);
     if(mle!=0){            fprintf(ficlog,"%d%d ",i,k);
       /* Computing hessian and covariance matrix */            fprintf(ficres,"%1d%1d ",i,k);
       ftolhess=ftol; /* Usually correct */            for(j=1; j <=ncovmodel; j++){
       hesscov(matcov, p, npar, delti, ftolhess, func);              printf("%lf ",p[jk]);
     }              fprintf(ficlog,"%lf ",p[jk]);
     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");              fprintf(ficres,"%lf ",p[jk]);
     printf("# Scales (for hessian or gradient estimation)\n");              jk++;
     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");            }
     for(i=1,jk=1; i <=nlstate; i++){            printf("\n");
       for(j=1; j <=nlstate+ndeath; j++){            fprintf(ficlog,"\n");
         if (j!=i) {            fprintf(ficres,"\n");
           fprintf(ficres,"%1d%1d",i,j);          }
           printf("%1d%1d",i,j);        }
           fprintf(ficlog,"%1d%1d",i,j);      }
           for(k=1; k<=ncovmodel;k++){      if(mle!=0){
             printf(" %.5e",delti[jk]);        /* Computing hessian and covariance matrix */
             fprintf(ficlog," %.5e",delti[jk]);        ftolhess=ftol; /* Usually correct */
             fprintf(ficres," %.5e",delti[jk]);        hesscov(matcov, p, npar, delti, ftolhess, func);
             jk++;      }
           }      fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
           printf("\n");      printf("# Scales (for hessian or gradient estimation)\n");
           fprintf(ficlog,"\n");      fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
           fprintf(ficres,"\n");      for(i=1,jk=1; i <=nlstate; i++){
         }        for(j=1; j <=nlstate+ndeath; j++){
       }          if (j!=i) {
     }            fprintf(ficres,"%1d%1d",i,j);
                 printf("%1d%1d",i,j);
     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(ficlog,"%1d%1d",i,j);
     if(mle>=1)            for(k=1; k<=ncovmodel;k++){
       printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");              printf(" %.5e",delti[jk]);
     fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");              fprintf(ficlog," %.5e",delti[jk]);
     /* # 121 Var(a12)\n\ */              fprintf(ficres," %.5e",delti[jk]);
     /* # 122 Cov(b12,a12) Var(b12)\n\ */              jk++;
     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */            }
     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */            printf("\n");
     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */            fprintf(ficlog,"\n");
     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */            fprintf(ficres,"\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" */        }
           }
          
     /* Just to have a covariance matrix which will be more understandable      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");
        even is we still don't want to manage dictionary of variables      if(mle>=1)
     */        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");
     for(itimes=1;itimes<=2;itimes++){      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");
       jj=0;      /* # 121 Var(a12)\n\ */
       for(i=1; i <=nlstate; i++){      /* # 122 Cov(b12,a12) Var(b12)\n\ */
         for(j=1; j <=nlstate+ndeath; j++){      /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
           if(j==i) continue;      /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
           for(k=1; k<=ncovmodel;k++){      /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
             jj++;      /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
             ca[0]= k+'a'-1;ca[1]='\0';      /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
             if(itimes==1){      /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
               if(mle>=1)     
                 printf("#%1d%1d%d",i,j,k);     
               fprintf(ficlog,"#%1d%1d%d",i,j,k);      /* Just to have a covariance matrix which will be more understandable
               fprintf(ficres,"#%1d%1d%d",i,j,k);         even is we still don't want to manage dictionary of variables
             }else{      */
               if(mle>=1)      for(itimes=1;itimes<=2;itimes++){
                 printf("%1d%1d%d",i,j,k);        jj=0;
               fprintf(ficlog,"%1d%1d%d",i,j,k);        for(i=1; i <=nlstate; i++){
               fprintf(ficres,"%1d%1d%d",i,j,k);          for(j=1; j <=nlstate+ndeath; j++){
             }            if(j==i) continue;
             ll=0;            for(k=1; k<=ncovmodel;k++){
             for(li=1;li <=nlstate; li++){              jj++;
               for(lj=1;lj <=nlstate+ndeath; lj++){              ca[0]= k+'a'-1;ca[1]='\0';
                 if(lj==li) continue;              if(itimes==1){
                 for(lk=1;lk<=ncovmodel;lk++){                if(mle>=1)
                   ll++;                  printf("#%1d%1d%d",i,j,k);
                   if(ll<=jj){                fprintf(ficlog,"#%1d%1d%d",i,j,k);
                     cb[0]= lk +'a'-1;cb[1]='\0';                fprintf(ficres,"#%1d%1d%d",i,j,k);
                     if(ll<jj){              }else{
                       if(itimes==1){                if(mle>=1)
                         if(mle>=1)                  printf("%1d%1d%d",i,j,k);
                           printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                fprintf(ficlog,"%1d%1d%d",i,j,k);
                         fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);                fprintf(ficres,"%1d%1d%d",i,j,k);
                         fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);              }
                       }else{              ll=0;
                         if(mle>=1)              for(li=1;li <=nlstate; li++){
                           printf(" %.5e",matcov[jj][ll]);                 for(lj=1;lj <=nlstate+ndeath; lj++){
                         fprintf(ficlog," %.5e",matcov[jj][ll]);                   if(lj==li) continue;
                         fprintf(ficres," %.5e",matcov[jj][ll]);                   for(lk=1;lk<=ncovmodel;lk++){
                       }                    ll++;
                     }else{                    if(ll<=jj){
                       if(itimes==1){                      cb[0]= lk +'a'-1;cb[1]='\0';
                         if(mle>=1)                      if(ll<jj){
                           printf(" Var(%s%1d%1d)",ca,i,j);                        if(itimes==1){
                         fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);                          if(mle>=1)
                         fprintf(ficres," Var(%s%1d%1d)",ca,i,j);                            printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                       }else{                          fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                         if(mle>=1)                          fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                           printf(" %.5e",matcov[jj][ll]);                         }else{
                         fprintf(ficlog," %.5e",matcov[jj][ll]);                           if(mle>=1)
                         fprintf(ficres," %.5e",matcov[jj][ll]);                             printf(" %.5e",matcov[jj][ll]);
                       }                          fprintf(ficlog," %.5e",matcov[jj][ll]);
                     }                          fprintf(ficres," %.5e",matcov[jj][ll]);
                   }                        }
                 } /* end lk */                      }else{
               } /* end lj */                        if(itimes==1){
             } /* end li */                          if(mle>=1)
             if(mle>=1)                            printf(" Var(%s%1d%1d)",ca,i,j);
               printf("\n");                          fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
             fprintf(ficlog,"\n");                          fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
             fprintf(ficres,"\n");                        }else{
             numlinepar++;                          if(mle>=1)
           } /* end k*/                            printf(" %.5e",matcov[jj][ll]);
         } /*end j */                          fprintf(ficlog," %.5e",matcov[jj][ll]);
       } /* end i */                          fprintf(ficres," %.5e",matcov[jj][ll]);
     } /* end itimes */                        }
                           }
     fflush(ficlog);                    }
     fflush(ficres);                  } /* end lk */
                     } /* end lj */
     while((c=getc(ficpar))=='#' && c!= EOF){              } /* end li */
       ungetc(c,ficpar);              if(mle>=1)
       fgets(line, MAXLINE, ficpar);                printf("\n");
       puts(line);              fprintf(ficlog,"\n");
       fputs(line,ficparo);              fprintf(ficres,"\n");
     }              numlinepar++;
     ungetc(c,ficpar);            } /* end k*/
               } /*end j */
     estepm=0;        } /* end i */
     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);      } /* end itimes */
     if (estepm==0 || estepm < stepm) estepm=stepm;     
     if (fage <= 2) {      fflush(ficlog);
       bage = ageminpar;      fflush(ficres);
       fage = agemaxpar;     
     }      while((c=getc(ficpar))=='#' && c!= EOF){
             ungetc(c,ficpar);
     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");        fgets(line, MAXLINE, ficpar);
     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);        puts(line);
     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);        fputs(line,ficparo);
           }
     while((c=getc(ficpar))=='#' && c!= EOF){      ungetc(c,ficpar);
       ungetc(c,ficpar);     
       fgets(line, MAXLINE, ficpar);      estepm=0;
       puts(line);      fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
       fputs(line,ficparo);      if (estepm==0 || estepm < stepm) estepm=stepm;
     }      if (fage <= 2) {
     ungetc(c,ficpar);        bage = ageminpar;
             fage = agemaxpar;
     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);     
     fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);      fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
     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(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
     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(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
          
     while((c=getc(ficpar))=='#' && c!= EOF){      while((c=getc(ficpar))=='#' && c!= EOF){
       ungetc(c,ficpar);        ungetc(c,ficpar);
       fgets(line, MAXLINE, ficpar);        fgets(line, MAXLINE, ficpar);
       puts(line);        puts(line);
       fputs(line,ficparo);        fputs(line,ficparo);
     }      }
     ungetc(c,ficpar);      ungetc(c,ficpar);
          
           fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;      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);
     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;      fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
           printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
     fscanf(ficpar,"pop_based=%d\n",&popbased);      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(ficparo,"pop_based=%d\n",popbased);        
     fprintf(ficres,"pop_based=%d\n",popbased);         while((c=getc(ficpar))=='#' && c!= EOF){
             ungetc(c,ficpar);
     while((c=getc(ficpar))=='#' && c!= EOF){        fgets(line, MAXLINE, ficpar);
       ungetc(c,ficpar);        puts(line);
       fgets(line, MAXLINE, ficpar);        fputs(line,ficparo);
       puts(line);      }
       fputs(line,ficparo);      ungetc(c,ficpar);
     }     
     ungetc(c,ficpar);     
           dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
     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);      dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
     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);      fscanf(ficpar,"pop_based=%d\n",&popbased);
     fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      fprintf(ficparo,"pop_based=%d\n",popbased);  
     fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);      fprintf(ficres,"pop_based=%d\n",popbased);  
     /* day and month of proj2 are not used but only year anproj2.*/     
           while((c=getc(ficpar))=='#' && c!= EOF){
             ungetc(c,ficpar);
             fgets(line, MAXLINE, ficpar);
     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/        puts(line);
     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/        fputs(line,ficparo);
           }
     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */      ungetc(c,ficpar);
     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);     
           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);
     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\      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);
                  model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\      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);
                  jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);      fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
             fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
    /*------------ free_vector  -------------*/      /* day and month of proj2 are not used but only year anproj2.*/
    /*  chdir(path); */     
       
     free_ivector(wav,1,imx);     
     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);      /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);      /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);        
     free_lvector(num,1,n);      replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
     free_vector(agedc,1,n);      printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
     /*free_matrix(covar,0,NCOVMAX,1,n);*/     
     /*free_matrix(covar,1,NCOVMAX,1,n);*/      printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
     fclose(ficparo);                   model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
     fclose(ficres);                   jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
        
      /*------------ free_vector  -------------*/
     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/     /*  chdir(path); */
      
     strcpy(filerespl,"pl");      free_ivector(wav,1,imx);
     strcat(filerespl,fileres);      free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
     if((ficrespl=fopen(filerespl,"w"))==NULL) {      free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;      free_imatrix(mw,1,lastpass-firstpass+1,1,imx);  
       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;      free_lvector(num,1,n);
     }      free_vector(agedc,1,n);
     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);      /*free_matrix(covar,0,NCOVMAX,1,n);*/
     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);      /*free_matrix(covar,1,NCOVMAX,1,n);*/
     pstamp(ficrespl);      fclose(ficparo);
     fprintf(ficrespl,"# Period (stable) prevalence \n");      fclose(ficres);
     fprintf(ficrespl,"#Age ");  
     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);  
     fprintf(ficrespl,"\n");      /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
      
     prlim=matrix(1,nlstate,1,nlstate);      strcpy(filerespl,"pl");
       strcat(filerespl,fileres);
     agebase=ageminpar;      if((ficrespl=fopen(filerespl,"w"))==NULL) {
     agelim=agemaxpar;        printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     ftolpl=1.e-10;        fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
     i1=cptcoveff;      }
     if (cptcovn < 1){i1=1;}      printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
       fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      pstamp(ficrespl);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      fprintf(ficrespl,"# Period (stable) prevalence \n");
         k=k+1;      fprintf(ficrespl,"#Age ");
         /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/      for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
         fprintf(ficrespl,"\n#******");      fprintf(ficrespl,"\n");
         printf("\n#******");   
         fprintf(ficlog,"\n#******");      prlim=matrix(1,nlstate,1,nlstate);
         for(j=1;j<=cptcoveff;j++) {  
           fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      agebase=ageminpar;
           printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      agelim=agemaxpar;
           fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      ftolpl=1.e-10;
         }      i1=cptcoveff;
         fprintf(ficrespl,"******\n");      if (cptcovn < 1){i1=1;}
         printf("******\n");  
         fprintf(ficlog,"******\n");      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                 for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
         for (age=agebase; age<=agelim; age++){          k=k+1;
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);          /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
           fprintf(ficrespl,"%.0f ",age );          fprintf(ficrespl,"\n#******");
           for(j=1;j<=cptcoveff;j++)          printf("\n#******");
             fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          fprintf(ficlog,"\n#******");
           for(i=1; i<=nlstate;i++)          for(j=1;j<=cptcoveff;j++) {
             fprintf(ficrespl," %.5f", prlim[i][i]);            fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficrespl,"\n");            printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         }            fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
       }          }
     }          fprintf(ficrespl,"******\n");
     fclose(ficrespl);          printf("******\n");
           fprintf(ficlog,"******\n");
     /*------------- h Pij x at various ages ------------*/         
             for (age=agebase; age<=agelim; age++){
     strcpy(filerespij,"pij");  strcat(filerespij,fileres);            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
     if((ficrespij=fopen(filerespij,"w"))==NULL) {            fprintf(ficrespl,"%.0f ",age );
       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;            for(j=1;j<=cptcoveff;j++)
       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;              fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
     }            for(i=1; i<=nlstate;i++)
     printf("Computing pij: result on file '%s' \n", filerespij);              fprintf(ficrespl," %.5f", prlim[i][i]);
     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);            fprintf(ficrespl,"\n");
             }
     stepsize=(int) (stepm+YEARM-1)/YEARM;        }
     /*if (stepm<=24) stepsize=2;*/      }
       fclose(ficrespl);
     agelim=AGESUP;  
     hstepm=stepsize*YEARM; /* Every year of age */      /*------------- h Pij x at various ages ------------*/
     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */    
       strcpy(filerespij,"pij");  strcat(filerespij,fileres);
     /* hstepm=1;   aff par mois*/      if((ficrespij=fopen(filerespij,"w"))==NULL) {
     pstamp(ficrespij);        printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");        fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      }
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      printf("Computing pij: result on file '%s' \n", filerespij);
         k=k+1;      fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
         fprintf(ficrespij,"\n#****** ");   
         for(j=1;j<=cptcoveff;j++)       stepsize=(int) (stepm+YEARM-1)/YEARM;
           fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);      /*if (stepm<=24) stepsize=2;*/
         fprintf(ficrespij,"******\n");  
               agelim=AGESUP;
         for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */      hstepm=stepsize*YEARM; /* Every year of age */
           nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */       hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
           nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */  
       /* hstepm=1;   aff par mois*/
           /*      nhstepm=nhstepm*YEARM; aff par mois*/      pstamp(ficrespij);
       fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
           p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
           oldm=oldms;savm=savms;        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);            k=k+1;
           fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");          fprintf(ficrespij,"\n#****** ");
           for(i=1; i<=nlstate;i++)          for(j=1;j<=cptcoveff;j++)
             for(j=1; j<=nlstate+ndeath;j++)            fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
               fprintf(ficrespij," %1d-%1d",i,j);          fprintf(ficrespij,"******\n");
           fprintf(ficrespij,"\n");         
           for (h=0; h<=nhstepm; h++){          for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
             fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );            nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
             for(i=1; i<=nlstate;i++)            nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
               for(j=1; j<=nlstate+ndeath;j++)  
                 fprintf(ficrespij," %.5f", p3mat[i][j][h]);            /*      nhstepm=nhstepm*YEARM; aff par mois*/
             fprintf(ficrespij,"\n");  
           }            p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
           free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);            oldm=oldms;savm=savms;
           fprintf(ficrespij,"\n");            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++)
                 fprintf(ficrespij," %1d-%1d",i,j);
     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);            fprintf(ficrespij,"\n");
             for (h=0; h<=nhstepm; h++){
     fclose(ficrespij);              fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
               for(i=1; i<=nlstate;i++)
     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);                for(j=1; j<=nlstate+ndeath;j++)
     for(i=1;i<=AGESUP;i++)                  fprintf(ficrespij," %.5f", p3mat[i][j][h]);
       for(j=1;j<=NCOVMAX;j++)              fprintf(ficrespij,"\n");
         for(k=1;k<=NCOVMAX;k++)            }
           probs[i][j][k]=0.;            free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
             fprintf(ficrespij,"\n");
     /*---------- Forecasting ------------------*/          }
     /*if((stepm == 1) && (strcmp(model,".")==0)){*/        }
     if(prevfcast==1){      }
       /*    if(stepm ==1){*/  
       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);      varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/  
       /*      }  */      fclose(ficrespij);
       /*      else{ */  
       /*        erreur=108; */      probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
       /*        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); */      for(i=1;i<=AGESUP;i++)
       /*        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); */        for(j=1;j<=NCOVMAX;j++)
       /*      } */          for(k=1;k<=NCOVMAX;k++)
     }            probs[i][j][k]=0.;
     
       /*---------- Forecasting ------------------*/
     /*---------- Health expectancies and variances ------------*/      /*if((stepm == 1) && (strcmp(model,".")==0)){*/
       if(prevfcast==1){
     strcpy(filerest,"t");        /*    if(stepm ==1){*/
     strcat(filerest,fileres);        prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
     if((ficrest=fopen(filerest,"w"))==NULL) {        /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
       printf("Problem with total LE resultfile: %s\n", filerest);goto end;        /*      }  */
       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;        /*      else{ */
     }        /*        erreur=108; */
     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);         /*        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,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);         /*        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); */
         /*      } */
       }
     strcpy(filerese,"e");   
     strcat(filerese,fileres);  
     if((ficreseij=fopen(filerese,"w"))==NULL) {      /*---------- Health expectancies and variances ------------*/
       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);  
       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);      strcpy(filerest,"t");
     }      strcat(filerest,fileres);
     printf("Computing Health Expectancies: result on file '%s' \n", filerese);      if((ficrest=fopen(filerest,"w"))==NULL) {
     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);        printf("Problem with total LE resultfile: %s\n", filerest);goto end;
         fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
     strcpy(fileresstde,"stde");      }
     strcat(fileresstde,fileres);      printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {      fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);  
       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);  
     }      strcpy(filerese,"e");
     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);      strcat(filerese,fileres);
     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);      if((ficreseij=fopen(filerese,"w"))==NULL) {
         printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
     strcpy(filerescve,"cve");        fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
     strcat(filerescve,fileres);      }
     if((ficrescveij=fopen(filerescve,"w"))==NULL) {      printf("Computing Health Expectancies: result on file '%s' \n", filerese);
       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);      fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);  
     }      strcpy(fileresstde,"stde");
     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      strcat(fileresstde,fileres);
     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);      if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
         printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
     strcpy(fileresv,"v");        fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
     strcat(fileresv,fileres);      }
     if((ficresvij=fopen(fileresv,"w"))==NULL) {      printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);      fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);  
     }      strcpy(filerescve,"cve");
     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);      strcat(filerescve,fileres);
     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);      if((ficrescveij=fopen(filerescve,"w"))==NULL) {
         printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */        fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
     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",\      printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
         ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);      fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
     */  
       strcpy(fileresv,"v");
     if (mobilav!=0) {      strcat(fileresv,fileres);
       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);      if((ficresvij=fopen(fileresv,"w"))==NULL) {
       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){        printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
         fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);        fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
         printf(" Error in movingaverage mobilav=%d\n",mobilav);      }
       }      printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
     }      fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
   
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
         k=k+1;       /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
         fprintf(ficrest,"\n#****** ");          ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
         for(j=1;j<=cptcoveff;j++)       */
           fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
         fprintf(ficrest,"******\n");      if (mobilav!=0) {
         mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
         fprintf(ficreseij,"\n#****** ");        if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
         fprintf(ficresstdeij,"\n#****** ");          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
         fprintf(ficrescveij,"\n#****** ");          printf(" Error in movingaverage mobilav=%d\n",mobilav);
         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]]);      for(cptcov=1,k=0;cptcov<=i1;cptcov++){
         }        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
         fprintf(ficreseij,"******\n");          k=k+1;
         fprintf(ficresstdeij,"******\n");          fprintf(ficrest,"\n#****** ");
         fprintf(ficrescveij,"******\n");          for(j=1;j<=cptcoveff;j++)
             fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         fprintf(ficresvij,"\n#****** ");          fprintf(ficrest,"******\n");
         for(j=1;j<=cptcoveff;j++)   
           fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);          fprintf(ficreseij,"\n#****** ");
         fprintf(ficresvij,"******\n");          fprintf(ficresstdeij,"\n#****** ");
           fprintf(ficrescveij,"\n#****** ");
         eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);          for(j=1;j<=cptcoveff;j++) {
         oldm=oldms;savm=savms;            fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);              fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);              fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
            }
         vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);          fprintf(ficreseij,"******\n");
         oldm=oldms;savm=savms;          fprintf(ficresstdeij,"******\n");
         varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);          fprintf(ficrescveij,"******\n");
         if(popbased==1){  
           varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);          fprintf(ficresvij,"\n#****** ");
         }          for(j=1;j<=cptcoveff;j++)
             fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
         pstamp(ficrest);          fprintf(ficresvij,"******\n");
         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);          eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
         fprintf(ficrest,"\n");          oldm=oldms;savm=savms;
           evsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
         epj=vector(1,nlstate+1);          cvevsij(fileres, eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
         for(age=bage; age <=fage ;age++){   
           prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);          vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
           if (popbased==1) {          oldm=oldms;savm=savms;
             if(mobilav ==0){          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,0, mobilav, strstart);
               for(i=1; i<=nlstate;i++)          if(popbased==1){
                 prlim[i][i]=probs[(int)age][i][k];            varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,popbased,mobilav, strstart);
             }else{ /* mobilav */           }
               for(i=1; i<=nlstate;i++)  
                 prlim[i][i]=mobaverage[(int)age][i][k];          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");
           fprintf(ficrest," %4.0f",age);  
           for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){          epj=vector(1,nlstate+1);
             for(i=1, epj[j]=0.;i <=nlstate;i++) {          for(age=bage; age <=fage ;age++){
               epj[j] += prlim[i][i]*eij[i][j][(int)age];            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
               /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/            if (popbased==1) {
             }              if(mobilav ==0){
             epj[nlstate+1] +=epj[j];                for(i=1; i<=nlstate;i++)
           }                  prlim[i][i]=probs[(int)age][i][k];
               }else{ /* mobilav */
           for(i=1, vepp=0.;i <=nlstate;i++)                for(i=1; i<=nlstate;i++)
             for(j=1;j <=nlstate;j++)                  prlim[i][i]=mobaverage[(int)age][i][k];
               vepp += vareij[i][j][(int)age];              }
           fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));            }
           for(j=1;j <=nlstate;j++){         
             fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));            fprintf(ficrest," %4.0f",age);
           }            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
           fprintf(ficrest,"\n");              for(i=1, epj[j]=0.;i <=nlstate;i++) {
         }                epj[j] += prlim[i][i]*eij[i][j][(int)age];
         free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
         free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);              }
         free_vector(epj,1,nlstate+1);              epj[nlstate+1] +=epj[j];
       }            }
     }  
     free_vector(weight,1,n);            for(i=1, vepp=0.;i <=nlstate;i++)
     free_imatrix(Tvard,1,15,1,2);              for(j=1;j <=nlstate;j++)
     free_imatrix(s,1,maxwav+1,1,n);                vepp += vareij[i][j][(int)age];
     free_matrix(anint,1,maxwav,1,n);             fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
     free_matrix(mint,1,maxwav,1,n);            for(j=1;j <=nlstate;j++){
     free_ivector(cod,1,n);              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
     free_ivector(tab,1,NCOVMAX);            }
     fclose(ficreseij);            fprintf(ficrest,"\n");
     fclose(ficresstdeij);          }
     fclose(ficrescveij);          free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     fclose(ficresvij);          free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
     fclose(ficrest);          free_vector(epj,1,nlstate+1);
     fclose(ficpar);        }
         }
     /*------- Variance of period (stable) prevalence------*/         free_vector(weight,1,n);
       free_imatrix(Tvard,1,15,1,2);
     strcpy(fileresvpl,"vpl");      free_imatrix(s,1,maxwav+1,1,n);
     strcat(fileresvpl,fileres);      free_matrix(anint,1,maxwav,1,n);
     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {      free_matrix(mint,1,maxwav,1,n);
       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);      free_ivector(cod,1,n);
       exit(0);      free_ivector(tab,1,NCOVMAX);
     }      fclose(ficreseij);
     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);      fclose(ficresstdeij);
       fclose(ficrescveij);
     for(cptcov=1,k=0;cptcov<=i1;cptcov++){      fclose(ficresvij);
       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){      fclose(ficrest);
         k=k+1;      fclose(ficpar);
         fprintf(ficresvpl,"\n#****** ");   
         for(j=1;j<=cptcoveff;j++)       /*------- Variance of period (stable) prevalence------*/  
           fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);  
         fprintf(ficresvpl,"******\n");      strcpy(fileresvpl,"vpl");
             strcat(fileresvpl,fileres);
         varpl=matrix(1,nlstate,(int) bage, (int) fage);      if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
         oldm=oldms;savm=savms;        printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
         varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);        exit(0);
         free_matrix(varpl,1,nlstate,(int) bage, (int)fage);      }
       }      printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
     }  
       for(cptcov=1,k=0;cptcov<=i1;cptcov++){
     fclose(ficresvpl);        for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
           k=k+1;
     /*---------- End : free ----------------*/          fprintf(ficresvpl,"\n#****** ");
     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);          for(j=1;j<=cptcoveff;j++)
     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);            fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
           fprintf(ficresvpl,"******\n");
   }  /* mle==-3 arrives here for freeing */       
   free_matrix(prlim,1,nlstate,1,nlstate);          varpl=matrix(1,nlstate,(int) bage, (int) fage);
     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);          oldm=oldms;savm=savms;
     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);          varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);          free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
     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);*/      fclose(ficresvpl);
     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);   
     free_matrix(agev,1,maxwav,1,imx);      /*---------- End : free ----------------*/
     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);      if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
       free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
     free_ivector(ncodemax,1,8);  
     free_ivector(Tvar,1,15);    }  /* mle==-3 arrives here for freeing */
     free_ivector(Tprod,1,15);    free_matrix(prlim,1,nlstate,1,nlstate);
     free_ivector(Tvaraff,1,15);      free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
     free_ivector(Tage,1,15);      free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
     free_ivector(Tcode,1,100);      free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
       free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);      free_matrix(covar,0,NCOVMAX,1,n);
     free_imatrix(codtab,1,100,1,10);      free_matrix(matcov,1,npar,1,npar);
   fflush(fichtm);      /*free_vector(delti,1,npar);*/
   fflush(ficgp);      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);
   if((nberr >0) || (nbwarn>0)){  
     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);      free_ivector(ncodemax,1,8);
     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);      free_ivector(Tvar,1,15);
   }else{      free_ivector(Tprod,1,15);
     printf("End of Imach\n");      free_ivector(Tvaraff,1,15);
     fprintf(ficlog,"End of Imach\n");      free_ivector(Tage,1,15);
   }      free_ivector(Tcode,1,100);
   printf("See log file on %s\n",filelog);  
   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */      free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
   (void) gettimeofday(&end_time,&tzp);      free_imatrix(codtab,1,100,1,10);
   tm = *localtime(&end_time.tv_sec);    fflush(fichtm);
   tmg = *gmtime(&end_time.tv_sec);    fflush(ficgp);
   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);     if((nberr >0) || (nbwarn>0)){
   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));      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);
   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);    }else{
   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));      printf("End of Imach\n");
   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);      fprintf(ficlog,"End of Imach\n");
   /*  printf("Total time was %d uSec.\n", total_usecs);*/    }
 /*   if(fileappend(fichtm,optionfilehtm)){ */    printf("See log file on %s\n",filelog);
   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);    /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
   fclose(fichtm);    (void) gettimeofday(&end_time,&tzp);
   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);    tm = *localtime(&end_time.tv_sec);
   fclose(fichtmcov);    tmg = *gmtime(&end_time.tv_sec);
   fclose(ficgp);    strcpy(strtend,asctime(&tm));
   fclose(ficlog);    printf("Local time at start %s\nLocal time at end   %s",strstart, strtend);
   /*------ End -----------*/    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("Before Current directory %s!\n",pathcd);    printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
    if(chdir(pathcd) != 0)    fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
     printf("Can't move to directory %s!\n",path);    fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
   if(getcwd(pathcd,MAXLINE) > 0)    /*  printf("Total time was %d uSec.\n", total_usecs);*/
     printf("Current directory %s!\n",pathcd);  /*   if(fileappend(fichtm,optionfilehtm)){ */
   /*strcat(plotcmd,CHARSEPARATOR);*/    fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
   sprintf(plotcmd,"gnuplot");    fclose(fichtm);
 #ifndef UNIX    fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);    fclose(fichtmcov);
 #endif    fclose(ficgp);
   if(!stat(plotcmd,&info)){    fclose(ficlog);
     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);    /*------ End -----------*/
     if(!stat(getenv("GNUPLOTBIN"),&info)){  
       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);  
     }else     printf("Before Current directory %s!\n",pathcd);
       strcpy(pplotcmd,plotcmd);     if(chdir(pathcd) != 0)
 #ifdef UNIX      printf("Can't move to directory %s!\n",path);
     strcpy(plotcmd,GNUPLOTPROGRAM);    if(getcwd(pathcd,MAXLINE) > 0)
     if(!stat(plotcmd,&info)){      printf("Current directory %s!\n",pathcd);
       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);    /*strcat(plotcmd,CHARSEPARATOR);*/
     }else    sprintf(plotcmd,"gnuplot");
       strcpy(pplotcmd,plotcmd);  #ifndef UNIX
 #endif    sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
   }else  #endif
     strcpy(pplotcmd,plotcmd);    if(!stat(plotcmd,&info)){
         printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);      if(!stat(getenv("GNUPLOTBIN"),&info)){
   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);        printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
       }else
   if((outcmd=system(plotcmd)) != 0){        strcpy(pplotcmd,plotcmd);
     printf("\n Problem with gnuplot\n");  #ifdef UNIX
   }      strcpy(plotcmd,GNUPLOTPROGRAM);
   printf(" Wait...");      if(!stat(plotcmd,&info)){
   while (z[0] != 'q') {        printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
     /* chdir(path); */      }else
     printf("\nType e to edit output files, g to graph again and q for exiting: ");        strcpy(pplotcmd,plotcmd);
     scanf("%s",z);  #endif
 /*     if (z[0] == 'c') system("./imach"); */    }else
     if (z[0] == 'e') {      strcpy(pplotcmd,plotcmd);
       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);   
       system(optionfilehtm);    sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
     }    printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
     else if (z[0] == 'g') system(plotcmd);  
     else if (z[0] == 'q') exit(0);    if((outcmd=system(plotcmd)) != 0){
   }      printf("\n Problem with gnuplot\n");
   end:    }
   while (z[0] != 'q') {    printf(" Wait...");
     printf("\nType  q for exiting: ");    while (z[0] != 'q') {
     scanf("%s",z);      /* 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.123  
changed lines
  Added in v.1.125


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